{"id":13578879,"url":"https://github.com/GINK03/keras-distillation","last_synced_at":"2025-04-05T19:34:00.682Z","repository":{"id":72065794,"uuid":"108727666","full_name":"GINK03/keras-distillation","owner":"GINK03","description":"keras google-vision's distillation","archived":false,"fork":false,"pushed_at":"2017-11-12T09:07:49.000Z","size":231,"stargazers_count":9,"open_issues_count":1,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-05T16:49:37.611Z","etag":null,"topics":["keras","keras-distillation","tensorflow-basics","vision-api"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GINK03.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-10-29T11:19:10.000Z","updated_at":"2024-07-24T19:59:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"8fdbfe12-56d5-460d-83a5-9ffecce2f5ae","html_url":"https://github.com/GINK03/keras-distillation","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GINK03%2Fkeras-distillation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GINK03%2Fkeras-distillation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GINK03%2Fkeras-distillation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GINK03%2Fkeras-distillation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GINK03","download_url":"https://codeload.github.com/GINK03/keras-distillation/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247393095,"owners_count":20931804,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["keras","keras-distillation","tensorflow-basics","vision-api"],"created_at":"2024-08-01T15:01:34.601Z","updated_at":"2025-04-05T19:34:00.382Z","avatar_url":"https://github.com/GINK03.png","language":"Python","funding_links":[],"categories":["Python","Keras"],"sub_categories":[],"readme":"# Kerasを使ったGoogle VisionサービスのDistillation(蒸留)\n\n## Vision APIをVGGで蒸留する\nVision APIの出力は実はタグの値を予想する問題でしかない \n\n出力するベクトルが任意の次元に収まっており、値の範囲を持つ場合には、特定の活性化関数で近似できる  \n\n例えば、Vision APIはメジャーなタグに限定すれば、5000個程度のタグの予想問題であり、5000個程度であればVGGを改良したモデルで近似できることを示す  \n\n(2017/11/08　データセットをスクリーニングして、問題のあるデータセット（一定の確率で特定のタグによってしまう）を排除したところ、だいぶ改善しました)\n\n## 理論\n去年の今頃、話題になっていたテクノロジーで、モデルのクローンが行えるとされているものである。  \nGoogle VISION APIなどの入出力がわかれば、特定のデータセットを用意することで、何を入力したら、何が得られるかの対応が得られる \n\nこの対応を元に、VISION APIの入出力と同等の値になるように、VGG16を学習させる  \n\nDeepLearning界の大御所のHinton先生の論文によると、モデルはより小さいモデルで近似することができて、性能はさほど落ちないし、同等の表現力を得られるとのことです[2]  \n\n(蒸留を行う上で重要な、仕組みはいくつかあるのですが、KL Divergenceという目的関数の作り方と、softmaxを逆算して値を出すことがポイントな気がしています）  \n\nイメージするモデル\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"600px\" src=\"https://user-images.githubusercontent.com/4949982/32262340-71c10378-bf17-11e7-9be0-f86fdf42de69.png\"\u003e\n\u003c/div\u003e\n\u003cdiv align=\"center\"\u003e 図1. クローン対象のモデルをブラックボックスとして、任意のモデルで近似する \u003c/div\u003e\n\n論文などによると、人間が真偽値を0,1で与えるのではなく、機械学習のモデルの出力値である 0.0 ~ 1.0までの連続値を与えることで、蒸留の対象もととなるモデルの癖や特徴量の把握の仕方まで仔細にクローンできるので効率的なのだそうです　　\n\n## 実験環境\n- pixabox.comという写真のデータセット200万枚を利用\n- 特徴しては5000個の頻出する特徴を利用\n- KL Divergenceではなく、Binary Cross Entropyを利用（Epoch 180時点においてこちらの方が表現力が良かった）  \n- 事前に200万枚に対してGoogle Cloud Vision APIでデータセットを作成し、Distillationで使うデータセットに変換  \n- AdamとSGDでAdamをとりあえず選択\n- 訓練用に195万枚を利用して、テスト用に5万枚を利用した\n\n## モデル\n様々なパラメータ探索を行なったが、収束速度と学習の安定性の観点から学習済みのVGG16のモデルを改良して用いるとパフォーマンスが良かった\n```python\ninput_tensor = Input(shape=(224, 224, 3))\nvgg_model = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)\nfor layer in vgg_model.layers[:6]: # default 15\n  layer.trainable = False\nx = vgg_model.layers[-1].output\nx = Flatten()(x)\nx = BN()(x)\nx = Dense(5000, activation='relu')(x)\nx = Dropout(0.35)(x)\nx = Dense(5000, activation='sigmoid')(x)\nmodel = Model(inputs=vgg_model.input, outputs=x)\nmodel.compile(loss='binary_crossentropy', optimizer='adam')\n```\n\n## 結果\nスナップショットして250epoch時点の結果を載せる  \nまだ計算すれば性能は上がりそうである  \n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"600px\" src=\"https://user-images.githubusercontent.com/4949982/32542082-e3e2eea6-c4b4-11e7-83cd-642a876b3bf6.png\"\u003e\n\u003c/div\u003e\n\u003cdiv align=\"center\"\u003e 図2. ざくろ \u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"600px\" src=\"https://user-images.githubusercontent.com/4949982/32364115-5eca4158-c0b6-11e7-839c-485a6716cfdf.png\"\u003e\n\u003c/div\u003e\n\u003cdiv align=\"center\"\u003e 図3. ビーチと人と馬（馬が検出できていない）　\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"600px\" src=\"https://user-images.githubusercontent.com/4949982/32542304-7c252d6e-c4b5-11e7-881a-7da6024ea00f.png\"\u003e\n\u003c/div\u003e\n\u003cdiv align=\"center\"\u003e 図4. ベトナムの夕日　\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"600px\" src=\"https://user-images.githubusercontent.com/4949982/32412410-7f5bb390-c23a-11e7-935c-93fa5800bde9.png\"\u003e\n\u003c/div\u003e\n\u003cdiv align=\"center\"\u003e 図5. アステカのデザインパターン \u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg width=\"600px\" src=\"https://user-images.githubusercontent.com/4949982/32412616-ca63799e-c240-11e7-9780-ff4eae2a1932.png\"\u003e\n\u003c/div\u003e\n\u003cdiv align=\"center\"\u003e 図6. 水と花の合成写真 \u003c/div\u003e\n\n## 学習時の注意点  \n\n膨大な検証と試行錯誤を行なったのですが、KL Divを最小化するのもいいですが、Binary Cross Entropyの最小化でもどうにかなります  \n\nまた、分布を真似するというタスクの制約からか、分布を似せようとしてくるので、必然的に頻出回数が多いSitiationに一致していまします。こういう時は単純な力技でデータ増やすこと汎化させているのですが、今回は100万枚を超えるデータセットが必要で大変データ集めに苦労しました（１０万枚具体で見積もっていたら全然うまくいかなくて焦りました。。。）  \n\n## プロジェクトのコード\n[https://github.com/GINK03/keras-distillation:embed]\n\n## 学習済みのモデル\nminioの自宅サーバにおいておきます（常時起動している訳でないので、落ちてることもあります）\n[models0][http://121.2.69.245:10002/minio/google-vision-distillation/keras-distillation/]\n\n### 使用した学習データセット\n\n[minimize.zip](http://121.2.69.245:10001/vision-distillation/minimize.zip)\n[vision.zip](http://121.2.69.245:10001/vision-distillation/vision.zip)\n\n## データセットを集める\n[pixabayなどをスクレイピングしたスクレイパーが入っているgithubのプロジェクト](https://github.com/GINK03/image-free-download-scraper)です  \npixabayはデフォルトではタグ情報がロシア語であってちょっと扱いにくいのですが、これはこれで何かできそうです\n(leveldbやBeautifulSoupなどの依存が必要です)  \n**スクレイピング**\n```console\n$ python3 pixabay_downloader.py\n```\n**Google Visonが認識できるサイズにリサイズする**\n```console\n$ python3 google_vision.py --minimize\n```\n**GCPのGoogle Visionのキーを環境変数に反映させる(Pythonのスクリプトが認証に使用します)**\n```console\nexport GOOGLE=AIzaSyDpuzmfCIAZPzug69****************\n```\n**Google Visionによりなんのタグがどの程度の確率でつくか計算し、結果をjsonで保存**\n```console\n$ python3 google_vision.py --scan\n```\n**学習に使用するデータセットを作ります**\n```console\n$ python3 --make_tag_index #\u003c-タグ情報を作ります\n$ python3 --make_pair #\u003c-学習に使用するデータセットを作ります\n```\n\n## 学習\n任意のデータセットを224x244にして255でノーマライズした状態Yvと、タグ情報のベクトルXvでタプルを作ります  \nタプルをpickleでシリアライズしてgzipで圧縮したファイル一つが一つの画像のデータセットになります  \n```python\none_data = gzip.compress( pickle.dumps( (X, y) ) )\n```\n任意のデータセットでこのフォーマットが成り立つものをdatasetのディレクトリに納めていただき、次のコマンドで実行します  \n```console\n$ python3 distillation.py --train\n```\n\n## 予想\n学習に使用したフォーマットを引数に指定して、predオプションをつけることで予想できます  \n```console\n$ python3 distillation.py --pred dataset/${WHAT_YOU_WANT_TO_PREDICT}.pkl\n...\n(タグの確率値が表示されます)\n```\n\n## 蒸留における法的な扱い\n参考文献[1]に書いてある限りしか調査していないですが、蒸留や転移学習に関しては法的な解釈がまだ定まってないように見受けられました  \n\n\u003e 既存の学習済みモデルのいわゆるデータコピーではないので，直ちに複製ということはできない。ただし，部分的に利用を行ったり，その結果を模したネットワークを再構築したりといった行為にあたるので，そもそも複製にあたるか否か，元の学習済みモデルの権利者（がもし存在すれば）との間でどのような利益の調整が行われるのか，許諾の要否，元のネットワークに課されていた権利上の制約（例えば，第 47 条の 7 の例外規定におけるデータベースの著作物の複製権の許諾等），といった論点がある。これらがどのように重み付けされて考慮されるかについては，文化的な側面，及び経済的な側面から，制度設計が必要であると考えられる。\n\nビジネスで使用するのは避けて、当面は、学術研究に留めておいた方が良さそうです。\n\n## ライセンス\nMIT\n\n## 参考文献\n- [ディープラーニングと著作物](https://system.jpaa.or.jp/patent/viewPdf/2741)\n- [Distilling the Knowledge in a Neural Network](https://www.cs.toronto.edu/%7Ehinton/absps/distillation.pdf)\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGINK03%2Fkeras-distillation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGINK03%2Fkeras-distillation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGINK03%2Fkeras-distillation/lists"}