20200823のTensorFlowに関する記事は8件です。

ColaboratoryでTensorFlowのチュートリアルPart1+α

前回<<今回>>

初めに

前回は映画レビューによるテキスト分類を行いました。しかし、検証データが改善されていないのに関わらず学習を続けてしまいました。今回は、検証データに改善が見られない場合、学習を中断するコールバックを実装します。

実装

前回 のモデル学習のコードだけ変えます。

code
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)

history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1,
                    callbacks=[early_stop])

EarlyStoppingというコールバックを実装します。3Epochの間にval_lossの改善が見られない場合、学習を途中で中断します。

result
Epoch 1/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7688 - accuracy: 0.4990 - val_loss: 0.6927 - val_accuracy: 0.5696
Epoch 2/40
30/30 [==============================] - 2s 60ms/step - loss: 0.6624 - accuracy: 0.6114 - val_loss: 0.6355 - val_accuracy: 0.6446
                                        
                                       省略
                      ・
Epoch 23/40
30/30 [==============================] - 2s 60ms/step - loss: 0.1407 - accuracy: 0.9535 - val_loss: 0.3139 - val_accuracy: 0.8738
Epoch 24/40
30/30 [==============================] - 2s 60ms/step - loss: 0.1337 - accuracy: 0.9553 - val_loss: 0.3146 - val_accuracy: 0.8734

結果24Epochで中断されました。グラフはこんな感じ。
映画レビュー2Loss.png

映画レビュー2Acc.png

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ColaboratoryでTensorFlowのチュートリアルをやるPart1+α

前回<<今回>>

初めに

前回は映画レビューによるテキスト分類を行いました。しかし、検証データが改善されていないのに関わらず学習を続けてしまいました。今回は、検証データに改善が見られない場合、学習を中断するコールバックを実装します。

実装

前回 のモデル学習のコードだけ変えます。

code
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)

history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1,
                    callbacks=[early_stop])

EarlyStoppingというコールバックを実装します。3Epochの間にval_lossの改善が見られない場合、学習を途中で中断します。

result
Epoch 1/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7688 - accuracy: 0.4990 - val_loss: 0.6927 - val_accuracy: 0.5696
Epoch 2/40
30/30 [==============================] - 2s 60ms/step - loss: 0.6624 - accuracy: 0.6114 - val_loss: 0.6355 - val_accuracy: 0.6446
                                        
                                       省略
                      ・
Epoch 23/40
30/30 [==============================] - 2s 60ms/step - loss: 0.1407 - accuracy: 0.9535 - val_loss: 0.3139 - val_accuracy: 0.8738
Epoch 24/40
30/30 [==============================] - 2s 60ms/step - loss: 0.1337 - accuracy: 0.9553 - val_loss: 0.3146 - val_accuracy: 0.8734

結果24Epochで中断されました。グラフはこんな感じ。
映画レビュー2Loss.png

映画レビュー2Acc.png

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ColaboratoryでTensorFlowのチュートリアル+α

前回

初めに

前回は映画レビューによるテキスト分類を行いました。しかし、検証データが改善されていないのに関わらず学習を続けてしまいました。今回は、検証データに改善が見られない場合、学習を中断するコールバックを実装します。

実装

前回 のモデル学習のコードだけ変えます。

code
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)

history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1,
                    callbacks=[early_stop])

EarlyStoppingというコールバックを実装します。3Epochの間にval_lossの改善が見られない場合、学習を途中で中断します。

result
Epoch 1/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7688 - accuracy: 0.4990 - val_loss: 0.6927 - val_accuracy: 0.5696
Epoch 2/40
30/30 [==============================] - 2s 60ms/step - loss: 0.6624 - accuracy: 0.6114 - val_loss: 0.6355 - val_accuracy: 0.6446
                                        
                                       省略
                      ・
Epoch 23/40
30/30 [==============================] - 2s 60ms/step - loss: 0.1407 - accuracy: 0.9535 - val_loss: 0.3139 - val_accuracy: 0.8738
Epoch 24/40
30/30 [==============================] - 2s 60ms/step - loss: 0.1337 - accuracy: 0.9553 - val_loss: 0.3146 - val_accuracy: 0.8734

結果24Epochで中断されました。グラフはこんな感じ。
映画レビュー2Loss.png

映画レビュー2Acc.png

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

iPadでPythonプログラミングする方法を考える

前置き

Qiita初投稿です.「自分で見返すため」「同様の悩みを持つ人の役に立つため」に投稿できればと思っています.
不慣れで本投稿は文字ばかりです.
徐々に使い方に慣れていこうと思うのでよろしくお願いいたしますm(__)m

はじめに

業務ではMatlabを使ってDeep Leaning等やっているのですが、tensorflowの方が自由度も高いし最新のモデルも使える…ということでPython、もっというとtensorflowを手軽に勉強できる環境を構築しようと思い立ち、いろいろ調べてみました。
タイトル記載のわざわざiPadで…というのは家でゴロゴロしながら、あるいは出先でもどこでも自由にコーディング・実行できる環境を作れたらなというだけの理由です。

目指す環境

目指す環境はiPad Pro 11inch(2018)を使ってPython3系のコーディング、プログラム実行ができるようになることです.
また,Deep Learningをしたいので,特定のPythonライブラリ(※1)が使用できることも必要条件.

また,無料で出来る環境を目指します.少なくともサブスク系は避けたいので,各種クラウドサービス(AzureやAWSなど)は現状検討していません.

(※1) 最低限以下のPythonライブラリは使いたいです.
・numpy
・matplotlib
・tensorflow
・Pillow (Open CVも使いたいがPillowだけでも良いかも)

本投稿ではPython環境の候補の調査まで行います.

結論

次章でダラダラと書いているので,先に結論を述べます.
iPadを使って,Python(tensorflow)のコーディング,実行をしたい場合,以下の環境が良さそうだとわかりました.

  • "code-server" or "Eclipse Theia"
  • "Gitpod"
  • "Jupyter Lab"

ただし,Gitpod以外はiPad以外に別途PCを準備する必要があります.
調べてみた感じ,iPad単体でtensorflowのお勉強をする方法は見つからず,いずれの方法もLinux,あるいはWindowsのOS上でPythonを実行させることとなります.
iOS, iPadOS上でPython本体や各種ライブラリを実行させるのはなかなか難しいということでしょう.

私はPCもiPadも持っていますが,両マシンの起動が必要ですし制約としてはかなり大きいかもしれません.
調べてみると思ったより面倒だったという次第です.

とりあえず,iPad単体で完結させたい場合はGitpodが有力です.

候補となる環境

活用できそうなPython環境をざっくり調べてみました.
本章で各環境についてメモ感覚で記載していきますが,だらだらと書いていますので読み飛ばし推奨です.

Pythonista3を購入する

iPadのローカル環境上でPythonを実行できる,Pythonista31というiPadアプリがあります.
¥1,220のアプリで当初の「無料で…」という目標からいきなりブレますが,買い切りのアプリだし評価もかなり高いので悪くないのでは?と思った次第です.

しかし…

使えるライブラリに制約があるようで,tensorflowが使えないのでダメそうです.
そもそもiPadのローカル環境上でDeep Learningするのが現実的でないですよね.

とはいえ,先に述べたように評価の高いアプリで,手軽にGUIアプリを作ったりできるみたいで凄いアプリみたいです.
本投稿ではこれ以上扱いませんが,気になる方は是非調べてみてください.
Pythonista3
* 上記画像はPythonista3の公式サイト2の画像を引用.

ブラウザで動くIDEのサーバーをLinuxで立てる("code-server" or "Eclipse Theia")

こちらが本命の方法となりそうです.
Linux環境上でサーバーを立てて,リモートでブラウザからアクセスできるVS CodeライクなIDEがあるようです.
iPadのブラウザから使える,ローカル(iPad)のマシンパワーに依存しない,Linuxの環境上で自由度高く作業できそう,無料,VS Codeのように拡張機能が使える,などの理由から本命だと考えています.

code-server3Eclipse Theia4というよく似た2種類のIDEがあります.
よく似ているので「どう違うのか」「どちらが良いのか」は現時点ではわかっていません.(日本語の情報はあまり多くなかったためです).

code-server
* 上記画像はcode-serverのGithubレポジトリ3より引用.

VS codeによく似た画面がブラウザ上で扱えます.

GitPodを利用する

上述のEclipse Theiaを利用したクラウドのIDEサービスのようです.
クラウドのサブスク系は避けると言っていたのに,またもや目標からブレます.
言い訳すると,制限付きですが無料で利用でき,使い勝手もなかなか良さそうなので候補とした次第です.

こちらはGithubアカウントがあれば利用でき,Github上のコードを変更,デバッグしてコミットすることができるようです.

【使い方】
GithubのレポジトリのURLは以下のようになっていると思います.

https://github.com/[アカウント名]/[レポジトリ名]

↑これを↓以下のように,"gitpod.io/"とつけるだけでgitpodのIDE画面に遷移します.(初回はGitpod利用のためのアカウント紐付けが必要)

https://gitpod.io/github.com/[アカウント名]/[レポジトリ名]

アクセスが簡単なので有力な候補です.
ただし長時間利用には課金が必要.軽く試すのには一番良さそうですが自由にがっつりやるとなると課金必須ですので注意してください.
Githubのソースコードを少し修正してデバッグ→コミットみたいな時にベストな気がします.
以下画像のように,こちらもブラウザで使えるVS codeのようなイメージです.

Gitpod
* 上記画像はGitpod公式サイト5より引用

WindowsでJupyterサーバーを作成する(Linuxでも可能)

WindowsまたはLinuxサーバーでJupyterサーバーをたてて,iPadのブラウザからアクセスするという方法です.
こちらは,Gitpodやcode-server, Eclipse Theiaのような強力なIDEという訳ではないのですが,Notebook形式(.ipynb)で実行できれば良いという方にはおすすめの方法となりそうです.
実際,Deep LearningするならNotebook形式のほうがデータを見やすいと思うので一番有力かもしれません.

どうやら最近ではJupyter NotebookではなくJupyter Labが積極的に開発されている6そうなので,Jupyter Labが良さげですね.
以下画像のように(これもVS Codeに若干似ていますが)ブラウザからアクセスしてPythonのコーディング,実行ができます.ただし,一般的な.pyファイルではなく.ipynbファイルのNotebook形式を扱うことになる点に注意.(.pyファイルも実行できますが,ちょっと使いにくいと思います)

Jupyter Lab
* 上記画像はJupyter Lab公式サイト7より引用

最後に

長々と書きましたが,iPadでtensorflowのお勉強というのは割と敷居が高いように感じました.
素直にPCで(あるいはそこそこスペックのノートPCで)やったほうが楽そうです.

ただ,なんとか環境構築できればゴロゴロしながらiPadで機械学習のお勉強もできそうだとわかりました.

補足

一番有力候補の"Google Colab"について書くのを失念しておりました!!!
(制限付きで)無料のクラウドサービスですので,おそらく環境構築も不要で最も有力な候補なのですが,しっかり調査できておりません.
従いまして,本投稿内では扱わないこととします.申し訳無いですがご容赦ください.(余裕があれば調査 & 追記いたします.)


  1. Pythonista3のApp StoreのURL:https://apps.apple.com/jp/app/pythonista-3/id1085978097 

  2. Pythonista3の公式サイト:http://omz-software.com/pythonista/ 

  3. code-serverのGithubレポジトリ:https://github.com/cdr/code-server 

  4. Eclipse TheiaのGithubレポジトリ:https://github.com/eclipse-theia/theia 

  5. Gitpodの公式サイトURL:https://www.gitpod.io/ 

  6. Jupyter Labについてよく説明してくださっている方がいます.タメになりましたので是非見てください.
    https://qiita.com/kirikei/items/a1639954ce5ccaf7ac3c 

  7. Jupyter Lab公式サイトURL:https://jupyterlab.readthedocs.io/en/stable/index.html 

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ColaboratoryでTensorFlowのチュートリアルPart1

初めに

映画レビューによるテキスト分類をやります。映画レビューをポジティブまたはネガティブに分類します。これは、2クラス分類の例で、基本的で重要な機械学習問題らしいです。Colaboratoryの使い方は【秒速で無料GPUを使う】深層学習実践Tips on Colaboratoryなどを見るといいです。

1. セットアップ

https://colab.research.google.com/notebooks/welcome.ipynb?hl=ja#scrollTo=GJBs_flRovLc にアクセスし、[ファイル]>>[ノートブックの新規作成]を選択します。

② ハードウェアアクセラレータをGPUにしてください。詳しいやり方はこちら

③ 以下のコードを実行します。

code
import numpy as np

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

import matplotlib.pyplot as plt

print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

このように表示されればOKです。

result
Version:  2.3.0
Eager mode:  True
Hub version:  0.8.0
GPU is available

2. IMDBデータをダウンロードする

① IMDBデータはhttps://github.com/tensorflow/datasets/tree/master/tensorflow_datasets の中にあります。以下のコードでColaboratoryランタイムにダウンロードできます。

code
train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"], 
                                  batch_size=-1, as_supervised=True)

train_examples, train_labels = tfds.as_numpy(train_data)
test_examples, test_labels = tfds.as_numpy(test_data)

②データをいくつか表示させてみます。

code
for i in range(10):
  print('{}: {}'.format(train_labels[i], train_examples[i]))
result
0: b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it."
0: b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.'
0: b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.'
1: b'This is the kind of film for a snowy Sunday afternoon when the rest of the world can go ahead with its own business as you descend into a big arm-chair and mellow for a couple of hours. Wonderful performances from Cher and Nicolas Cage (as always) gently row the plot along. There are no rapids to cross, no dangerous waters, just a warm and witty paddle through New York life at its best. A family film in every sense and one that deserves the praise it received.'
1: b'As others have mentioned, all the women that go nude in this film are mostly absolutely gorgeous. The plot very ably shows the hypocrisy of the female libido. When men are around they want to be pursued, but when no "men" are around, they become the pursuers of a 14 year old boy. And the boy becomes a man really fast (we should all be so lucky at this age!). He then gets up the courage to pursue his true love.'
1: b"This is a film which should be seen by anybody interested in, effected by, or suffering from an eating disorder. It is an amazingly accurate and sensitive portrayal of bulimia in a teenage girl, its causes and its symptoms. The girl is played by one of the most brilliant young actresses working in cinema today, Alison Lohman, who was later so spectacular in 'Where the Truth Lies'. I would recommend that this film be shown in all schools, as you will never see a better on this subject. Alison Lohman is absolutely outstanding, and one marvels at her ability to convey the anguish of a girl suffering from this compulsive disorder. If barometers tell us the air pressure, Alison Lohman tells us the emotional pressure with the same degree of accuracy. Her emotional range is so precise, each scene could be measured microscopically for its gradations of trauma, on a scale of rising hysteria and desperation which reaches unbearable intensity. Mare Winningham is the perfect choice to play her mother, and does so with immense sympathy and a range of emotions just as finely tuned as Lohman's. Together, they make a pair of sensitive emotional oscillators vibrating in resonance with one another. This film is really an astonishing achievement, and director Katt Shea should be proud of it. The only reason for not seeing it is if you are not interested in people. But even if you like nature films best, this is after all animal behaviour at the sharp edge. Bulimia is an extreme version of how a tormented soul can destroy her own body in a frenzy of despair. And if we don't sympathise with people suffering from the depths of despair, then we are dead inside."
0: b'Okay, you have:<br /><br />Penelope Keith as Miss Herringbone-Tweed, B.B.E. (Backbone of England.) She\'s killed off in the first scene - that\'s right, folks; this show has no backbone!<br /><br />Peter O\'Toole as Ol\' Colonel Cricket from The First War and now the emblazered Lord of the Manor.<br /><br />Joanna Lumley as the ensweatered Lady of the Manor, 20 years younger than the colonel and 20 years past her own prime but still glamourous (Brit spelling, not mine) enough to have a toy-boy on the side. It\'s alright, they have Col. Cricket\'s full knowledge and consent (they guy even comes \'round for Christmas!) Still, she\'s considerate of the colonel enough to have said toy-boy her own age (what a gal!)<br /><br />David McCallum as said toy-boy, equally as pointlessly glamourous as his squeeze. Pilcher couldn\'t come up with any cover for him within the story, so she gave him a hush-hush job at the Circus.<br /><br />and finally:<br /><br />Susan Hampshire as Miss Polonia Teacups, Venerable Headmistress of the Venerable Girls\' Boarding-School, serving tea in her office with a dash of deep, poignant advice for life in the outside world just before graduation. Her best bit of advice: "I\'ve only been to Nancherrow (the local Stately Home of England) once. I thought it was very beautiful but, somehow, not part of the real world." Well, we can\'t say they didn\'t warn us.<br /><br />Ah, Susan - time was, your character would have been running the whole show. They don\'t write \'em like that any more. Our loss, not yours.<br /><br />So - with a cast and setting like this, you have the re-makings of "Brideshead Revisited," right?<br /><br />Wrong! They took these 1-dimensional supporting roles because they paid so well. After all, acting is one of the oldest temp-jobs there is (YOU name another!)<br /><br />First warning sign: lots and lots of backlighting. They get around it by shooting outdoors - "hey, it\'s just the sunlight!"<br /><br />Second warning sign: Leading Lady cries a lot. When not crying, her eyes are moist. That\'s the law of romance novels: Leading Lady is "dewy-eyed."<br /><br />Henceforth, Leading Lady shall be known as L.L.<br /><br />Third warning sign: L.L. actually has stars in her eyes when she\'s in love. Still, I\'ll give Emily Mortimer an award just for having to act with that spotlight in her eyes (I wonder . did they use contacts?)<br /><br />And lastly, fourth warning sign: no on-screen female character is "Mrs." She\'s either "Miss" or "Lady."<br /><br />When all was said and done, I still couldn\'t tell you who was pursuing whom and why. I couldn\'t even tell you what was said and done.<br /><br />To sum up: they all live through World War II without anything happening to them at all.<br /><br />OK, at the end, L.L. finds she\'s lost her parents to the Japanese prison camps and baby sis comes home catatonic. Meanwhile (there\'s always a "meanwhile,") some young guy L.L. had a crush on (when, I don\'t know) comes home from some wartime tough spot and is found living on the street by Lady of the Manor (must be some street if SHE\'s going to find him there.) Both war casualties are whisked away to recover at Nancherrow (SOMEBODY has to be "whisked away" SOMEWHERE in these romance stories!)<br /><br />Great drama.'
0: b'The film is based on a genuine 1950s novel.<br /><br />Journalist Colin McInnes wrote a set of three "London novels": "Absolute Beginners", "City of Spades" and "Mr Love and Justice". I have read all three. The first two are excellent. The last, perhaps an experiment that did not come off. But McInnes\'s work is highly acclaimed; and rightly so. This musical is the novelist\'s ultimate nightmare - to see the fruits of one\'s mind being turned into a glitzy, badly-acted, soporific one-dimensional apology of a film that says it captures the spirit of 1950s London, and does nothing of the sort.<br /><br />Thank goodness Colin McInnes wasn\'t alive to witness it.'
0: b'I really love the sexy action and sci-fi films of the sixties and its because of the actress\'s that appeared in them. They found the sexiest women to be in these films and it didn\'t matter if they could act (Remember "Candy"?). The reason I was disappointed by this film was because it wasn\'t nostalgic enough. The story here has a European sci-fi film called "Dragonfly" being made and the director is fired. So the producers decide to let a young aspiring filmmaker (Jeremy Davies) to complete the picture. They\'re is one real beautiful woman in the film who plays Dragonfly but she\'s barely in it. Film is written and directed by Roman Coppola who uses some of his fathers exploits from his early days and puts it into the script. I wish the film could have been an homage to those early films. They could have lots of cameos by actors who appeared in them. There is one actor in this film who was popular from the sixties and its John Phillip Law (Barbarella). Gerard Depardieu, Giancarlo Giannini and Dean Stockwell appear as well. I guess I\'m going to have to continue waiting for a director to make a good homage to the films of the sixties. If any are reading this, "Make it as sexy as you can"! I\'ll be waiting!'
0: b'Sure, this one isn\'t really a blockbuster, nor does it target such a position. "Dieter" is the first name of a quite popular German musician, who is either loved or hated for his kind of acting and thats exactly what this movie is about. It is based on the autobiography "Dieter Bohlen" wrote a few years ago but isn\'t meant to be accurate on that. The movie is filled with some sexual offensive content (at least for American standard) which is either amusing (not for the other "actors" of course) or dumb - it depends on your individual kind of humor or on you being a "Bohlen"-Fan or not. Technically speaking there isn\'t much to criticize. Speaking of me I find this movie to be an OK-movie.'

0がネガティブなレビュー、1がポジティブなレビューです。

3.モデルの作成

①今回は一層目のレイヤーにTensorflowHubの学習済みテキスト埋め込みモデル(https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1) を使用します。これにより、テキストをベクトルとして扱えるようになります。まず、データのダウンロードです。

code
model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], 
                           dtype=tf.string, trainable=True)
hub_layer(train_examples[:3])
result
<tf.Tensor: shape=(3, 20), dtype=float32, numpy=
array([[ 1.765786  , -3.882232  ,  3.9134233 , -1.5557289 , -3.3362343 ,
        -1.7357955 , -1.9954445 ,  1.2989551 ,  5.081598  , -1.1041286 ,
        -2.0503852 , -0.72675157, -0.65675956,  0.24436149, -3.7208383 ,
         2.0954835 ,  2.2969332 , -2.0689783 , -2.9489717 , -1.1315987 ],
       [ 1.8804485 , -2.5852382 ,  3.4066997 ,  1.0982676 , -4.056685  ,
        -4.891284  , -2.785554  ,  1.3874227 ,  3.8476458 , -0.9256538 ,
        -1.896706  ,  1.2113281 ,  0.11474707,  0.76209456, -4.8791065 ,
         2.906149  ,  4.7087674 , -2.3652055 , -3.5015898 , -1.6390051 ],
       [ 0.71152234, -0.6353217 ,  1.7385626 , -1.1168286 , -0.5451594 ,
        -1.1808156 ,  0.09504455,  1.4653089 ,  0.66059524,  0.79308075,
        -2.2268345 ,  0.07446612, -1.4075904 , -0.70645386, -1.907037  ,
         1.4419787 ,  1.9551861 , -0.42660055, -2.8022065 ,  0.43727064]],
      dtype=float32)>

②それではモデルを作成します。

code
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

model.summary()

モデルの構造は、[入力]>>[学習済みテキスト埋め込み層]>>[全結合層]>>[Relu]>>[全結合層]>>[出力] といった形ですね。

result
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 20)                400020    
_________________________________________________________________
dense (Dense)                (None, 16)                336       
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 17        
=================================================================
Total params: 400,373
Trainable params: 400,373
Non-trainable params: 0
_________________________________________________________________

4. モデルの学習

①まず、モデルのコンパイルを行います。

code
model.compile(optimizer='adam',
              loss=tf.losses.BinaryCrossentropy(from_logits=True),
              metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])

今回は2クラス分類なので、binary-crossentropy誤差をつかいます。

②次に検証データを作成します。

code
x_val = train_examples[:10000]
partial_x_train = train_examples[10000:]

y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]

③そして訓練データを使って学習します。

code
history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
result
Epoch 1/40
30/30 [==============================] - 2s 74ms/step - loss: 1.2141 - accuracy: 0.4967 - val_loss: 0.7402 - val_accuracy: 0.4946
Epoch 2/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7026 - accuracy: 0.5345 - val_loss: 0.6801 - val_accuracy: 0.5754

                                       省略
                      
Epoch 39/40
30/30 [==============================] - 2s 62ms/step - loss: 0.0750 - accuracy: 0.9826 - val_loss: 0.3420 - val_accuracy: 0.8738
Epoch 40/40
30/30 [==============================] - 2s 63ms/step - loss: 0.0710 - accuracy: 0.9836 - val_loss: 0.3470 - val_accuracy: 0.8729

5. モデルの評価

①最後に作成したモデルの評価をします。横軸Epoch数、縦軸Lossのグラフを書きます。

code
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

epochs = range(1, len(acc) + 1)

# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

映画レビュー.png

②今度は縦軸Accuracyのグラフを書きます。

code
plt.clf()   # clear figure

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()

plt.show()

映画レビューAcc.png

この2つのグラフを見ると、トレーニングデータは改善されているのに対して、検証データは20Epochあたりから、一向に改善されてないことがわかります。つまり、20Epoch移行は無駄な学習をしているということです。それだけ、過学習するリスクも高まります。

6. 最後に

Colaboratoryを使うと、とてもスピーディーに機械学習が行えることがわかりました。次回は、検証データの改善が見られない場合、トレーニングを停止するコールバックを実装します。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ColaboratoryでTensorFlowのチュートリアルをやるPart1

初めに

映画レビューによるテキスト分類をやります。映画レビューをポジティブまたはネガティブに分類します。これは、2クラス分類の例で、基本的で重要な機械学習問題らしいです。Colaboratoryの使い方は【秒速で無料GPUを使う】深層学習実践Tips on Colaboratoryなどを見るといいです。

1. セットアップ

https://colab.research.google.com/notebooks/welcome.ipynb?hl=ja#scrollTo=GJBs_flRovLc にアクセスし、[ファイル]>>[ノートブックの新規作成]を選択します。

② ハードウェアアクセラレータをGPUにしてください。詳しいやり方はこちら

③ 以下のコードを実行します。

code
import numpy as np

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

import matplotlib.pyplot as plt

print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

このように表示されればOKです。

result
Version:  2.3.0
Eager mode:  True
Hub version:  0.8.0
GPU is available

2. IMDBデータをダウンロードする

① IMDBデータはhttps://github.com/tensorflow/datasets/tree/master/tensorflow_datasets の中にあります。以下のコードでColaboratoryランタイムにダウンロードできます。

code
train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"], 
                                  batch_size=-1, as_supervised=True)

train_examples, train_labels = tfds.as_numpy(train_data)
test_examples, test_labels = tfds.as_numpy(test_data)

②データをいくつか表示させてみます。

code
for i in range(10):
  print('{}: {}'.format(train_labels[i], train_examples[i]))
result
0: b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it."
0: b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.'
0: b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.'
1: b'This is the kind of film for a snowy Sunday afternoon when the rest of the world can go ahead with its own business as you descend into a big arm-chair and mellow for a couple of hours. Wonderful performances from Cher and Nicolas Cage (as always) gently row the plot along. There are no rapids to cross, no dangerous waters, just a warm and witty paddle through New York life at its best. A family film in every sense and one that deserves the praise it received.'
1: b'As others have mentioned, all the women that go nude in this film are mostly absolutely gorgeous. The plot very ably shows the hypocrisy of the female libido. When men are around they want to be pursued, but when no "men" are around, they become the pursuers of a 14 year old boy. And the boy becomes a man really fast (we should all be so lucky at this age!). He then gets up the courage to pursue his true love.'
1: b"This is a film which should be seen by anybody interested in, effected by, or suffering from an eating disorder. It is an amazingly accurate and sensitive portrayal of bulimia in a teenage girl, its causes and its symptoms. The girl is played by one of the most brilliant young actresses working in cinema today, Alison Lohman, who was later so spectacular in 'Where the Truth Lies'. I would recommend that this film be shown in all schools, as you will never see a better on this subject. Alison Lohman is absolutely outstanding, and one marvels at her ability to convey the anguish of a girl suffering from this compulsive disorder. If barometers tell us the air pressure, Alison Lohman tells us the emotional pressure with the same degree of accuracy. Her emotional range is so precise, each scene could be measured microscopically for its gradations of trauma, on a scale of rising hysteria and desperation which reaches unbearable intensity. Mare Winningham is the perfect choice to play her mother, and does so with immense sympathy and a range of emotions just as finely tuned as Lohman's. Together, they make a pair of sensitive emotional oscillators vibrating in resonance with one another. This film is really an astonishing achievement, and director Katt Shea should be proud of it. The only reason for not seeing it is if you are not interested in people. But even if you like nature films best, this is after all animal behaviour at the sharp edge. Bulimia is an extreme version of how a tormented soul can destroy her own body in a frenzy of despair. And if we don't sympathise with people suffering from the depths of despair, then we are dead inside."
0: b'Okay, you have:<br /><br />Penelope Keith as Miss Herringbone-Tweed, B.B.E. (Backbone of England.) She\'s killed off in the first scene - that\'s right, folks; this show has no backbone!<br /><br />Peter O\'Toole as Ol\' Colonel Cricket from The First War and now the emblazered Lord of the Manor.<br /><br />Joanna Lumley as the ensweatered Lady of the Manor, 20 years younger than the colonel and 20 years past her own prime but still glamourous (Brit spelling, not mine) enough to have a toy-boy on the side. It\'s alright, they have Col. Cricket\'s full knowledge and consent (they guy even comes \'round for Christmas!) Still, she\'s considerate of the colonel enough to have said toy-boy her own age (what a gal!)<br /><br />David McCallum as said toy-boy, equally as pointlessly glamourous as his squeeze. Pilcher couldn\'t come up with any cover for him within the story, so she gave him a hush-hush job at the Circus.<br /><br />and finally:<br /><br />Susan Hampshire as Miss Polonia Teacups, Venerable Headmistress of the Venerable Girls\' Boarding-School, serving tea in her office with a dash of deep, poignant advice for life in the outside world just before graduation. Her best bit of advice: "I\'ve only been to Nancherrow (the local Stately Home of England) once. I thought it was very beautiful but, somehow, not part of the real world." Well, we can\'t say they didn\'t warn us.<br /><br />Ah, Susan - time was, your character would have been running the whole show. They don\'t write \'em like that any more. Our loss, not yours.<br /><br />So - with a cast and setting like this, you have the re-makings of "Brideshead Revisited," right?<br /><br />Wrong! They took these 1-dimensional supporting roles because they paid so well. After all, acting is one of the oldest temp-jobs there is (YOU name another!)<br /><br />First warning sign: lots and lots of backlighting. They get around it by shooting outdoors - "hey, it\'s just the sunlight!"<br /><br />Second warning sign: Leading Lady cries a lot. When not crying, her eyes are moist. That\'s the law of romance novels: Leading Lady is "dewy-eyed."<br /><br />Henceforth, Leading Lady shall be known as L.L.<br /><br />Third warning sign: L.L. actually has stars in her eyes when she\'s in love. Still, I\'ll give Emily Mortimer an award just for having to act with that spotlight in her eyes (I wonder . did they use contacts?)<br /><br />And lastly, fourth warning sign: no on-screen female character is "Mrs." She\'s either "Miss" or "Lady."<br /><br />When all was said and done, I still couldn\'t tell you who was pursuing whom and why. I couldn\'t even tell you what was said and done.<br /><br />To sum up: they all live through World War II without anything happening to them at all.<br /><br />OK, at the end, L.L. finds she\'s lost her parents to the Japanese prison camps and baby sis comes home catatonic. Meanwhile (there\'s always a "meanwhile,") some young guy L.L. had a crush on (when, I don\'t know) comes home from some wartime tough spot and is found living on the street by Lady of the Manor (must be some street if SHE\'s going to find him there.) Both war casualties are whisked away to recover at Nancherrow (SOMEBODY has to be "whisked away" SOMEWHERE in these romance stories!)<br /><br />Great drama.'
0: b'The film is based on a genuine 1950s novel.<br /><br />Journalist Colin McInnes wrote a set of three "London novels": "Absolute Beginners", "City of Spades" and "Mr Love and Justice". I have read all three. The first two are excellent. The last, perhaps an experiment that did not come off. But McInnes\'s work is highly acclaimed; and rightly so. This musical is the novelist\'s ultimate nightmare - to see the fruits of one\'s mind being turned into a glitzy, badly-acted, soporific one-dimensional apology of a film that says it captures the spirit of 1950s London, and does nothing of the sort.<br /><br />Thank goodness Colin McInnes wasn\'t alive to witness it.'
0: b'I really love the sexy action and sci-fi films of the sixties and its because of the actress\'s that appeared in them. They found the sexiest women to be in these films and it didn\'t matter if they could act (Remember "Candy"?). The reason I was disappointed by this film was because it wasn\'t nostalgic enough. The story here has a European sci-fi film called "Dragonfly" being made and the director is fired. So the producers decide to let a young aspiring filmmaker (Jeremy Davies) to complete the picture. They\'re is one real beautiful woman in the film who plays Dragonfly but she\'s barely in it. Film is written and directed by Roman Coppola who uses some of his fathers exploits from his early days and puts it into the script. I wish the film could have been an homage to those early films. They could have lots of cameos by actors who appeared in them. There is one actor in this film who was popular from the sixties and its John Phillip Law (Barbarella). Gerard Depardieu, Giancarlo Giannini and Dean Stockwell appear as well. I guess I\'m going to have to continue waiting for a director to make a good homage to the films of the sixties. If any are reading this, "Make it as sexy as you can"! I\'ll be waiting!'
0: b'Sure, this one isn\'t really a blockbuster, nor does it target such a position. "Dieter" is the first name of a quite popular German musician, who is either loved or hated for his kind of acting and thats exactly what this movie is about. It is based on the autobiography "Dieter Bohlen" wrote a few years ago but isn\'t meant to be accurate on that. The movie is filled with some sexual offensive content (at least for American standard) which is either amusing (not for the other "actors" of course) or dumb - it depends on your individual kind of humor or on you being a "Bohlen"-Fan or not. Technically speaking there isn\'t much to criticize. Speaking of me I find this movie to be an OK-movie.'

0がネガティブなレビュー、1がポジティブなレビューです。

3.モデルの作成

①今回は一層目のレイヤーにTensorflowHubの学習済みテキスト埋め込みモデル(https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1) を使用します。これにより、テキストをベクトルとして扱えるようになります。まず、データのダウンロードです。

code
model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], 
                           dtype=tf.string, trainable=True)
hub_layer(train_examples[:3])
result
<tf.Tensor: shape=(3, 20), dtype=float32, numpy=
array([[ 1.765786  , -3.882232  ,  3.9134233 , -1.5557289 , -3.3362343 ,
        -1.7357955 , -1.9954445 ,  1.2989551 ,  5.081598  , -1.1041286 ,
        -2.0503852 , -0.72675157, -0.65675956,  0.24436149, -3.7208383 ,
         2.0954835 ,  2.2969332 , -2.0689783 , -2.9489717 , -1.1315987 ],
       [ 1.8804485 , -2.5852382 ,  3.4066997 ,  1.0982676 , -4.056685  ,
        -4.891284  , -2.785554  ,  1.3874227 ,  3.8476458 , -0.9256538 ,
        -1.896706  ,  1.2113281 ,  0.11474707,  0.76209456, -4.8791065 ,
         2.906149  ,  4.7087674 , -2.3652055 , -3.5015898 , -1.6390051 ],
       [ 0.71152234, -0.6353217 ,  1.7385626 , -1.1168286 , -0.5451594 ,
        -1.1808156 ,  0.09504455,  1.4653089 ,  0.66059524,  0.79308075,
        -2.2268345 ,  0.07446612, -1.4075904 , -0.70645386, -1.907037  ,
         1.4419787 ,  1.9551861 , -0.42660055, -2.8022065 ,  0.43727064]],
      dtype=float32)>

②それではモデルを作成します。

code
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

model.summary()

モデルの構造は、[入力]>>[学習済みテキスト埋め込み層]>>[全結合層]>>[Relu]>>[全結合層]>>[出力] といった形ですね。

result
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 20)                400020    
_________________________________________________________________
dense (Dense)                (None, 16)                336       
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 17        
=================================================================
Total params: 400,373
Trainable params: 400,373
Non-trainable params: 0
_________________________________________________________________

4. モデルの学習

①まず、モデルのコンパイルを行います。

code
model.compile(optimizer='adam',
              loss=tf.losses.BinaryCrossentropy(from_logits=True),
              metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])

今回は2クラス分類なので、binary-crossentropy誤差をつかいます。

②次に検証データを作成します。

code
x_val = train_examples[:10000]
partial_x_train = train_examples[10000:]

y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]

③そして訓練データを使って学習します。

code
history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
result
Epoch 1/40
30/30 [==============================] - 2s 74ms/step - loss: 1.2141 - accuracy: 0.4967 - val_loss: 0.7402 - val_accuracy: 0.4946
Epoch 2/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7026 - accuracy: 0.5345 - val_loss: 0.6801 - val_accuracy: 0.5754

                                       省略
                      
Epoch 39/40
30/30 [==============================] - 2s 62ms/step - loss: 0.0750 - accuracy: 0.9826 - val_loss: 0.3420 - val_accuracy: 0.8738
Epoch 40/40
30/30 [==============================] - 2s 63ms/step - loss: 0.0710 - accuracy: 0.9836 - val_loss: 0.3470 - val_accuracy: 0.8729

5. モデルの評価

①最後に作成したモデルの評価をします。横軸Epoch数、縦軸Lossのグラフを書きます。

code
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

epochs = range(1, len(acc) + 1)

# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

映画レビュー.png

②今度は縦軸Accuracyのグラフを書きます。

code
plt.clf()   # clear figure

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()

plt.show()

映画レビューAcc.png

この2つのグラフを見ると、トレーニングデータは改善されているのに対して、検証データは20Epochあたりから、一向に改善されてないことがわかります。つまり、20Epoch移行は無駄な学習をしているということです。それだけ、過学習するリスクも高まります。

6. 最後に

Colaboratoryを使うと、とてもスピーディーに機械学習が行えることがわかりました。次回は、検証データの改善が見られない場合、トレーニングを停止するコールバックを実装します。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ColaboratoryでTensorFlowのチュートリアルPart1~映画レビューによるテキスト分類~

初めに

映画レビューによるテキスト分類をやります。映画レビューをポジティブまたはネガティブに分類します。これは、2クラス分類の例で、基本的で重要な機械学習問題らしいです。Colaboratoryの使い方は【秒速で無料GPUを使う】深層学習実践Tips on Colaboratoryなどを見るといいです。

1. セットアップ

https://colab.research.google.com/notebooks/welcome.ipynb?hl=ja#scrollTo=GJBs_flRovLc にアクセスし、[ファイル]>>[ノートブックの新規作成]を選択します。

② ハードウェアアクセラレータをGPUにしてください。詳しいやり方はこちら

③ 以下のコードを実行します。

code
import numpy as np

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

import matplotlib.pyplot as plt

print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

このように表示されればOKです。

result
Version:  2.3.0
Eager mode:  True
Hub version:  0.8.0
GPU is available

2. IMDBデータをダウンロードする

① IMDBデータはhttps://github.com/tensorflow/datasets/tree/master/tensorflow_datasets の中にあります。以下のコードでColaboratoryランタイムにダウンロードできます。

code
train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"], 
                                  batch_size=-1, as_supervised=True)

train_examples, train_labels = tfds.as_numpy(train_data)
test_examples, test_labels = tfds.as_numpy(test_data)

②データをいくつか表示させてみます。

code
for i in range(10):
  print('{}: {}'.format(train_labels[i], train_examples[i]))
result
0: b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it."
0: b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.'
0: b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.'
1: b'This is the kind of film for a snowy Sunday afternoon when the rest of the world can go ahead with its own business as you descend into a big arm-chair and mellow for a couple of hours. Wonderful performances from Cher and Nicolas Cage (as always) gently row the plot along. There are no rapids to cross, no dangerous waters, just a warm and witty paddle through New York life at its best. A family film in every sense and one that deserves the praise it received.'
1: b'As others have mentioned, all the women that go nude in this film are mostly absolutely gorgeous. The plot very ably shows the hypocrisy of the female libido. When men are around they want to be pursued, but when no "men" are around, they become the pursuers of a 14 year old boy. And the boy becomes a man really fast (we should all be so lucky at this age!). He then gets up the courage to pursue his true love.'
1: b"This is a film which should be seen by anybody interested in, effected by, or suffering from an eating disorder. It is an amazingly accurate and sensitive portrayal of bulimia in a teenage girl, its causes and its symptoms. The girl is played by one of the most brilliant young actresses working in cinema today, Alison Lohman, who was later so spectacular in 'Where the Truth Lies'. I would recommend that this film be shown in all schools, as you will never see a better on this subject. Alison Lohman is absolutely outstanding, and one marvels at her ability to convey the anguish of a girl suffering from this compulsive disorder. If barometers tell us the air pressure, Alison Lohman tells us the emotional pressure with the same degree of accuracy. Her emotional range is so precise, each scene could be measured microscopically for its gradations of trauma, on a scale of rising hysteria and desperation which reaches unbearable intensity. Mare Winningham is the perfect choice to play her mother, and does so with immense sympathy and a range of emotions just as finely tuned as Lohman's. Together, they make a pair of sensitive emotional oscillators vibrating in resonance with one another. This film is really an astonishing achievement, and director Katt Shea should be proud of it. The only reason for not seeing it is if you are not interested in people. But even if you like nature films best, this is after all animal behaviour at the sharp edge. Bulimia is an extreme version of how a tormented soul can destroy her own body in a frenzy of despair. And if we don't sympathise with people suffering from the depths of despair, then we are dead inside."
0: b'Okay, you have:<br /><br />Penelope Keith as Miss Herringbone-Tweed, B.B.E. (Backbone of England.) She\'s killed off in the first scene - that\'s right, folks; this show has no backbone!<br /><br />Peter O\'Toole as Ol\' Colonel Cricket from The First War and now the emblazered Lord of the Manor.<br /><br />Joanna Lumley as the ensweatered Lady of the Manor, 20 years younger than the colonel and 20 years past her own prime but still glamourous (Brit spelling, not mine) enough to have a toy-boy on the side. It\'s alright, they have Col. Cricket\'s full knowledge and consent (they guy even comes \'round for Christmas!) Still, she\'s considerate of the colonel enough to have said toy-boy her own age (what a gal!)<br /><br />David McCallum as said toy-boy, equally as pointlessly glamourous as his squeeze. Pilcher couldn\'t come up with any cover for him within the story, so she gave him a hush-hush job at the Circus.<br /><br />and finally:<br /><br />Susan Hampshire as Miss Polonia Teacups, Venerable Headmistress of the Venerable Girls\' Boarding-School, serving tea in her office with a dash of deep, poignant advice for life in the outside world just before graduation. Her best bit of advice: "I\'ve only been to Nancherrow (the local Stately Home of England) once. I thought it was very beautiful but, somehow, not part of the real world." Well, we can\'t say they didn\'t warn us.<br /><br />Ah, Susan - time was, your character would have been running the whole show. They don\'t write \'em like that any more. Our loss, not yours.<br /><br />So - with a cast and setting like this, you have the re-makings of "Brideshead Revisited," right?<br /><br />Wrong! They took these 1-dimensional supporting roles because they paid so well. After all, acting is one of the oldest temp-jobs there is (YOU name another!)<br /><br />First warning sign: lots and lots of backlighting. They get around it by shooting outdoors - "hey, it\'s just the sunlight!"<br /><br />Second warning sign: Leading Lady cries a lot. When not crying, her eyes are moist. That\'s the law of romance novels: Leading Lady is "dewy-eyed."<br /><br />Henceforth, Leading Lady shall be known as L.L.<br /><br />Third warning sign: L.L. actually has stars in her eyes when she\'s in love. Still, I\'ll give Emily Mortimer an award just for having to act with that spotlight in her eyes (I wonder . did they use contacts?)<br /><br />And lastly, fourth warning sign: no on-screen female character is "Mrs." She\'s either "Miss" or "Lady."<br /><br />When all was said and done, I still couldn\'t tell you who was pursuing whom and why. I couldn\'t even tell you what was said and done.<br /><br />To sum up: they all live through World War II without anything happening to them at all.<br /><br />OK, at the end, L.L. finds she\'s lost her parents to the Japanese prison camps and baby sis comes home catatonic. Meanwhile (there\'s always a "meanwhile,") some young guy L.L. had a crush on (when, I don\'t know) comes home from some wartime tough spot and is found living on the street by Lady of the Manor (must be some street if SHE\'s going to find him there.) Both war casualties are whisked away to recover at Nancherrow (SOMEBODY has to be "whisked away" SOMEWHERE in these romance stories!)<br /><br />Great drama.'
0: b'The film is based on a genuine 1950s novel.<br /><br />Journalist Colin McInnes wrote a set of three "London novels": "Absolute Beginners", "City of Spades" and "Mr Love and Justice". I have read all three. The first two are excellent. The last, perhaps an experiment that did not come off. But McInnes\'s work is highly acclaimed; and rightly so. This musical is the novelist\'s ultimate nightmare - to see the fruits of one\'s mind being turned into a glitzy, badly-acted, soporific one-dimensional apology of a film that says it captures the spirit of 1950s London, and does nothing of the sort.<br /><br />Thank goodness Colin McInnes wasn\'t alive to witness it.'
0: b'I really love the sexy action and sci-fi films of the sixties and its because of the actress\'s that appeared in them. They found the sexiest women to be in these films and it didn\'t matter if they could act (Remember "Candy"?). The reason I was disappointed by this film was because it wasn\'t nostalgic enough. The story here has a European sci-fi film called "Dragonfly" being made and the director is fired. So the producers decide to let a young aspiring filmmaker (Jeremy Davies) to complete the picture. They\'re is one real beautiful woman in the film who plays Dragonfly but she\'s barely in it. Film is written and directed by Roman Coppola who uses some of his fathers exploits from his early days and puts it into the script. I wish the film could have been an homage to those early films. They could have lots of cameos by actors who appeared in them. There is one actor in this film who was popular from the sixties and its John Phillip Law (Barbarella). Gerard Depardieu, Giancarlo Giannini and Dean Stockwell appear as well. I guess I\'m going to have to continue waiting for a director to make a good homage to the films of the sixties. If any are reading this, "Make it as sexy as you can"! I\'ll be waiting!'
0: b'Sure, this one isn\'t really a blockbuster, nor does it target such a position. "Dieter" is the first name of a quite popular German musician, who is either loved or hated for his kind of acting and thats exactly what this movie is about. It is based on the autobiography "Dieter Bohlen" wrote a few years ago but isn\'t meant to be accurate on that. The movie is filled with some sexual offensive content (at least for American standard) which is either amusing (not for the other "actors" of course) or dumb - it depends on your individual kind of humor or on you being a "Bohlen"-Fan or not. Technically speaking there isn\'t much to criticize. Speaking of me I find this movie to be an OK-movie.'

0がネガティブなレビュー、1がポジティブなレビューです。

3.モデルの作成

①今回は一層目のレイヤーにTensorflowHubの学習済みテキスト埋め込みモデル(https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1) を使用します。これにより、テキストをベクトルとして扱えるようになります。まず、データのダウンロードです。

code
model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], 
                           dtype=tf.string, trainable=True)
hub_layer(train_examples[:3])
result
<tf.Tensor: shape=(3, 20), dtype=float32, numpy=
array([[ 1.765786  , -3.882232  ,  3.9134233 , -1.5557289 , -3.3362343 ,
        -1.7357955 , -1.9954445 ,  1.2989551 ,  5.081598  , -1.1041286 ,
        -2.0503852 , -0.72675157, -0.65675956,  0.24436149, -3.7208383 ,
         2.0954835 ,  2.2969332 , -2.0689783 , -2.9489717 , -1.1315987 ],
       [ 1.8804485 , -2.5852382 ,  3.4066997 ,  1.0982676 , -4.056685  ,
        -4.891284  , -2.785554  ,  1.3874227 ,  3.8476458 , -0.9256538 ,
        -1.896706  ,  1.2113281 ,  0.11474707,  0.76209456, -4.8791065 ,
         2.906149  ,  4.7087674 , -2.3652055 , -3.5015898 , -1.6390051 ],
       [ 0.71152234, -0.6353217 ,  1.7385626 , -1.1168286 , -0.5451594 ,
        -1.1808156 ,  0.09504455,  1.4653089 ,  0.66059524,  0.79308075,
        -2.2268345 ,  0.07446612, -1.4075904 , -0.70645386, -1.907037  ,
         1.4419787 ,  1.9551861 , -0.42660055, -2.8022065 ,  0.43727064]],
      dtype=float32)>

②それではモデルを作成します。

code
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

model.summary()

モデルの構造は、[入力]>>[学習済みテキスト埋め込み層]>>[全結合層]>>[Relu]>>[全結合層]>>[出力] といった形ですね。

result
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 20)                400020    
_________________________________________________________________
dense (Dense)                (None, 16)                336       
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 17        
=================================================================
Total params: 400,373
Trainable params: 400,373
Non-trainable params: 0
_________________________________________________________________

4. モデルの学習

①まず、モデルのコンパイルを行います。

code
model.compile(optimizer='adam',
              loss=tf.losses.BinaryCrossentropy(from_logits=True),
              metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])

今回は2クラス分類なので、binary-crossentropy誤差をつかいます。

②次に検証データを作成します。

code
x_val = train_examples[:10000]
partial_x_train = train_examples[10000:]

y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]

③そして訓練データを使って学習します。

code
history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
result
Epoch 1/40
30/30 [==============================] - 2s 74ms/step - loss: 1.2141 - accuracy: 0.4967 - val_loss: 0.7402 - val_accuracy: 0.4946
Epoch 2/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7026 - accuracy: 0.5345 - val_loss: 0.6801 - val_accuracy: 0.5754

                                       省略
                      
Epoch 39/40
30/30 [==============================] - 2s 62ms/step - loss: 0.0750 - accuracy: 0.9826 - val_loss: 0.3420 - val_accuracy: 0.8738
Epoch 40/40
30/30 [==============================] - 2s 63ms/step - loss: 0.0710 - accuracy: 0.9836 - val_loss: 0.3470 - val_accuracy: 0.8729

5. モデルの評価

①最後に作成したモデルの評価をします。横軸Epoch数、縦軸Lossのグラフを書きます。

code
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

epochs = range(1, len(acc) + 1)

# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

映画レビュー.png

②今度は縦軸Accuracyのグラフを書きます。

code
plt.clf()   # clear figure

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()

plt.show()

映画レビューAcc.png

この2つのグラフを見ると、トレーニングデータは改善されているのに対して、検証データは20Epochあたりから、一向に改善されてないことがわかります。つまり、20Epoch移行は無駄な学習をしているということです。それだけ、過学習するリスクも高まります。

6. 最後に

Colaboratoryを使うと、とてもスピーディーに機械学習が行えることがわかりました。次回は、検証データの改善が見られない場合、トレーニングを停止するコールバックを実装します。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ColaboratoryでTensorFlowのチュートリアル~映画レビューによるテキスト分類~

初めに

映画レビューによるテキスト分類をやります。映画レビューをポジティブまたはネガティブに分類します。これは、2クラス分類の例で、基本的で重要な機械学習問題らしいです。Colaboratoryの使い方は【秒速で無料GPUを使う】深層学習実践Tips on Colaboratoryなどを見るといいです。

1. セットアップ

https://colab.research.google.com/notebooks/welcome.ipynb?hl=ja#scrollTo=GJBs_flRovLc にアクセスし、[ファイル]>>[ノートブックの新規作成]を選択します。

② ハードウェアアクセラレータをGPUにしてください。詳しいやり方はこちら

③ 以下のコードを実行します。

code
import numpy as np

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

import matplotlib.pyplot as plt

print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

このように表示されればOKです。

result
Version:  2.3.0
Eager mode:  True
Hub version:  0.8.0
GPU is available

2. IMDBデータをダウンロードする

① IMDBデータはhttps://github.com/tensorflow/datasets/tree/master/tensorflow_datasets の中にあります。以下のコードでColaboratoryランタイムにダウンロードできます。

code
train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"], 
                                  batch_size=-1, as_supervised=True)

train_examples, train_labels = tfds.as_numpy(train_data)
test_examples, test_labels = tfds.as_numpy(test_data)

②データをいくつか表示させてみます。

code
for i in range(10):
  print('{}: {}'.format(train_labels[i], train_examples[i]))
result
0: b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it."
0: b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.'
0: b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.'
1: b'This is the kind of film for a snowy Sunday afternoon when the rest of the world can go ahead with its own business as you descend into a big arm-chair and mellow for a couple of hours. Wonderful performances from Cher and Nicolas Cage (as always) gently row the plot along. There are no rapids to cross, no dangerous waters, just a warm and witty paddle through New York life at its best. A family film in every sense and one that deserves the praise it received.'
1: b'As others have mentioned, all the women that go nude in this film are mostly absolutely gorgeous. The plot very ably shows the hypocrisy of the female libido. When men are around they want to be pursued, but when no "men" are around, they become the pursuers of a 14 year old boy. And the boy becomes a man really fast (we should all be so lucky at this age!). He then gets up the courage to pursue his true love.'
1: b"This is a film which should be seen by anybody interested in, effected by, or suffering from an eating disorder. It is an amazingly accurate and sensitive portrayal of bulimia in a teenage girl, its causes and its symptoms. The girl is played by one of the most brilliant young actresses working in cinema today, Alison Lohman, who was later so spectacular in 'Where the Truth Lies'. I would recommend that this film be shown in all schools, as you will never see a better on this subject. Alison Lohman is absolutely outstanding, and one marvels at her ability to convey the anguish of a girl suffering from this compulsive disorder. If barometers tell us the air pressure, Alison Lohman tells us the emotional pressure with the same degree of accuracy. Her emotional range is so precise, each scene could be measured microscopically for its gradations of trauma, on a scale of rising hysteria and desperation which reaches unbearable intensity. Mare Winningham is the perfect choice to play her mother, and does so with immense sympathy and a range of emotions just as finely tuned as Lohman's. Together, they make a pair of sensitive emotional oscillators vibrating in resonance with one another. This film is really an astonishing achievement, and director Katt Shea should be proud of it. The only reason for not seeing it is if you are not interested in people. But even if you like nature films best, this is after all animal behaviour at the sharp edge. Bulimia is an extreme version of how a tormented soul can destroy her own body in a frenzy of despair. And if we don't sympathise with people suffering from the depths of despair, then we are dead inside."
0: b'Okay, you have:<br /><br />Penelope Keith as Miss Herringbone-Tweed, B.B.E. (Backbone of England.) She\'s killed off in the first scene - that\'s right, folks; this show has no backbone!<br /><br />Peter O\'Toole as Ol\' Colonel Cricket from The First War and now the emblazered Lord of the Manor.<br /><br />Joanna Lumley as the ensweatered Lady of the Manor, 20 years younger than the colonel and 20 years past her own prime but still glamourous (Brit spelling, not mine) enough to have a toy-boy on the side. It\'s alright, they have Col. Cricket\'s full knowledge and consent (they guy even comes \'round for Christmas!) Still, she\'s considerate of the colonel enough to have said toy-boy her own age (what a gal!)<br /><br />David McCallum as said toy-boy, equally as pointlessly glamourous as his squeeze. Pilcher couldn\'t come up with any cover for him within the story, so she gave him a hush-hush job at the Circus.<br /><br />and finally:<br /><br />Susan Hampshire as Miss Polonia Teacups, Venerable Headmistress of the Venerable Girls\' Boarding-School, serving tea in her office with a dash of deep, poignant advice for life in the outside world just before graduation. Her best bit of advice: "I\'ve only been to Nancherrow (the local Stately Home of England) once. I thought it was very beautiful but, somehow, not part of the real world." Well, we can\'t say they didn\'t warn us.<br /><br />Ah, Susan - time was, your character would have been running the whole show. They don\'t write \'em like that any more. Our loss, not yours.<br /><br />So - with a cast and setting like this, you have the re-makings of "Brideshead Revisited," right?<br /><br />Wrong! They took these 1-dimensional supporting roles because they paid so well. After all, acting is one of the oldest temp-jobs there is (YOU name another!)<br /><br />First warning sign: lots and lots of backlighting. They get around it by shooting outdoors - "hey, it\'s just the sunlight!"<br /><br />Second warning sign: Leading Lady cries a lot. When not crying, her eyes are moist. That\'s the law of romance novels: Leading Lady is "dewy-eyed."<br /><br />Henceforth, Leading Lady shall be known as L.L.<br /><br />Third warning sign: L.L. actually has stars in her eyes when she\'s in love. Still, I\'ll give Emily Mortimer an award just for having to act with that spotlight in her eyes (I wonder . did they use contacts?)<br /><br />And lastly, fourth warning sign: no on-screen female character is "Mrs." She\'s either "Miss" or "Lady."<br /><br />When all was said and done, I still couldn\'t tell you who was pursuing whom and why. I couldn\'t even tell you what was said and done.<br /><br />To sum up: they all live through World War II without anything happening to them at all.<br /><br />OK, at the end, L.L. finds she\'s lost her parents to the Japanese prison camps and baby sis comes home catatonic. Meanwhile (there\'s always a "meanwhile,") some young guy L.L. had a crush on (when, I don\'t know) comes home from some wartime tough spot and is found living on the street by Lady of the Manor (must be some street if SHE\'s going to find him there.) Both war casualties are whisked away to recover at Nancherrow (SOMEBODY has to be "whisked away" SOMEWHERE in these romance stories!)<br /><br />Great drama.'
0: b'The film is based on a genuine 1950s novel.<br /><br />Journalist Colin McInnes wrote a set of three "London novels": "Absolute Beginners", "City of Spades" and "Mr Love and Justice". I have read all three. The first two are excellent. The last, perhaps an experiment that did not come off. But McInnes\'s work is highly acclaimed; and rightly so. This musical is the novelist\'s ultimate nightmare - to see the fruits of one\'s mind being turned into a glitzy, badly-acted, soporific one-dimensional apology of a film that says it captures the spirit of 1950s London, and does nothing of the sort.<br /><br />Thank goodness Colin McInnes wasn\'t alive to witness it.'
0: b'I really love the sexy action and sci-fi films of the sixties and its because of the actress\'s that appeared in them. They found the sexiest women to be in these films and it didn\'t matter if they could act (Remember "Candy"?). The reason I was disappointed by this film was because it wasn\'t nostalgic enough. The story here has a European sci-fi film called "Dragonfly" being made and the director is fired. So the producers decide to let a young aspiring filmmaker (Jeremy Davies) to complete the picture. They\'re is one real beautiful woman in the film who plays Dragonfly but she\'s barely in it. Film is written and directed by Roman Coppola who uses some of his fathers exploits from his early days and puts it into the script. I wish the film could have been an homage to those early films. They could have lots of cameos by actors who appeared in them. There is one actor in this film who was popular from the sixties and its John Phillip Law (Barbarella). Gerard Depardieu, Giancarlo Giannini and Dean Stockwell appear as well. I guess I\'m going to have to continue waiting for a director to make a good homage to the films of the sixties. If any are reading this, "Make it as sexy as you can"! I\'ll be waiting!'
0: b'Sure, this one isn\'t really a blockbuster, nor does it target such a position. "Dieter" is the first name of a quite popular German musician, who is either loved or hated for his kind of acting and thats exactly what this movie is about. It is based on the autobiography "Dieter Bohlen" wrote a few years ago but isn\'t meant to be accurate on that. The movie is filled with some sexual offensive content (at least for American standard) which is either amusing (not for the other "actors" of course) or dumb - it depends on your individual kind of humor or on you being a "Bohlen"-Fan or not. Technically speaking there isn\'t much to criticize. Speaking of me I find this movie to be an OK-movie.'

0がネガティブなレビュー、1がポジティブなレビューです。

3.モデルの作成

①今回は一層目のレイヤーにTensorflowHubの学習済みテキスト埋め込みモデル(https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1) を使用します。これにより、テキストをベクトルとして扱えるようになります。まず、データのダウンロードです。

code
model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], 
                           dtype=tf.string, trainable=True)
hub_layer(train_examples[:3])
result
<tf.Tensor: shape=(3, 20), dtype=float32, numpy=
array([[ 1.765786  , -3.882232  ,  3.9134233 , -1.5557289 , -3.3362343 ,
        -1.7357955 , -1.9954445 ,  1.2989551 ,  5.081598  , -1.1041286 ,
        -2.0503852 , -0.72675157, -0.65675956,  0.24436149, -3.7208383 ,
         2.0954835 ,  2.2969332 , -2.0689783 , -2.9489717 , -1.1315987 ],
       [ 1.8804485 , -2.5852382 ,  3.4066997 ,  1.0982676 , -4.056685  ,
        -4.891284  , -2.785554  ,  1.3874227 ,  3.8476458 , -0.9256538 ,
        -1.896706  ,  1.2113281 ,  0.11474707,  0.76209456, -4.8791065 ,
         2.906149  ,  4.7087674 , -2.3652055 , -3.5015898 , -1.6390051 ],
       [ 0.71152234, -0.6353217 ,  1.7385626 , -1.1168286 , -0.5451594 ,
        -1.1808156 ,  0.09504455,  1.4653089 ,  0.66059524,  0.79308075,
        -2.2268345 ,  0.07446612, -1.4075904 , -0.70645386, -1.907037  ,
         1.4419787 ,  1.9551861 , -0.42660055, -2.8022065 ,  0.43727064]],
      dtype=float32)>

②それではモデルを作成します。

code
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

model.summary()

モデルの構造は、[入力]>>[学習済みテキスト埋め込み層]>>[全結合層]>>[Relu]>>[全結合層]>>[出力] といった形ですね。

result
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 20)                400020    
_________________________________________________________________
dense (Dense)                (None, 16)                336       
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 17        
=================================================================
Total params: 400,373
Trainable params: 400,373
Non-trainable params: 0
_________________________________________________________________

4. モデルの学習

①まず、モデルのコンパイルを行います。

code
model.compile(optimizer='adam',
              loss=tf.losses.BinaryCrossentropy(from_logits=True),
              metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])

今回は2クラス分類なので、binary-crossentropy誤差をつかいます。

②次に検証データを作成します。

code
x_val = train_examples[:10000]
partial_x_train = train_examples[10000:]

y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]

③そして訓練データを使って学習します。

code
history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
result
Epoch 1/40
30/30 [==============================] - 2s 74ms/step - loss: 1.2141 - accuracy: 0.4967 - val_loss: 0.7402 - val_accuracy: 0.4946
Epoch 2/40
30/30 [==============================] - 2s 67ms/step - loss: 0.7026 - accuracy: 0.5345 - val_loss: 0.6801 - val_accuracy: 0.5754

                                       省略
                      
Epoch 39/40
30/30 [==============================] - 2s 62ms/step - loss: 0.0750 - accuracy: 0.9826 - val_loss: 0.3420 - val_accuracy: 0.8738
Epoch 40/40
30/30 [==============================] - 2s 63ms/step - loss: 0.0710 - accuracy: 0.9836 - val_loss: 0.3470 - val_accuracy: 0.8729

5. モデルの評価

①最後に作成したモデルの評価をします。横軸Epoch数、縦軸Lossのグラフを書きます。

code
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

epochs = range(1, len(acc) + 1)

# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

映画レビュー.png

②今度は縦軸Accuracyのグラフを書きます。

code
plt.clf()   # clear figure

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()

plt.show()

映画レビューAcc.png

この2つのグラフを見ると、トレーニングデータは改善されているのに対して、検証データは20Epochあたりから、一向に改善されてないことがわかります。つまり、20Epoch移行は無駄な学習をしているということです。それだけ、過学習するリスクも高まります。

6. 最後に

Colaboratoryを使うと、とてもスピーディーに機械学習が行えることがわかりました。次回は、検証データの改善が見られない場合、トレーニングを停止するコールバックを実装します。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む