このページは Cloud Translation API によって翻訳されました。
Switch to English

映画レビューによるテキスト分類

TensorFlow.orgで見る Google Colabで実行 GitHubでソースを表示する ノートブックをダウンロード

このノートブックは、レビューのテキストを使用して、映画レビューをポジティブまたはネガティブに分類します。これは、 バイナリ(または2クラス)分類の例であり、重要かつ広く適用可能な種類の機械学習問題です。

インターネットムービーデータベースからの50,000の映画レビューのテキストを含むIMDBデータセットを使用します。これらは、トレーニング用の25,000レビューとテスト用の25,000レビューに分かれています。トレーニングとテストのセットはバランス取れています。つまり、同数のポジティブレビューとネガティブレビューが含まれています。

このノートブックは、 TensorFlowでモデルを構築およびトレーニングするための高レベルAPIであるtf.kerasと、転移学習用のライブラリおよびプラットフォームであるTensorFlow Hubを使用しています。 tf.kerasを使用したより高度なテキスト分類のチュートリアルについては、 MLCCテキスト分類ガイドを参照してください。

その他のモデル

ここでは、テキストの埋め込みを生成するために使用できる、より表現力豊かなモデルまたはパフォーマンスの高いモデルを見つけることができます。

セットアップ

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")
Version:  2.3.0
Eager mode:  True
Hub version:  0.9.0
GPU is available

IMDBデータセットをダウンロードする

IMDBデータセットはTensorFlowデータセットで利用できます。次のコードは、IMDBデータセットをマシン(またはcolabランタイム)にダウンロードします。

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)
Downloading and preparing dataset imdb_reviews/plain_text/1.0.0 (download: 80.23 MiB, generated: Unknown size, total: 80.23 MiB) to /home/kbuilder/tensorflow_datasets/imdb_reviews/plain_text/1.0.0...
Shuffling and writing examples to /home/kbuilder/tensorflow_datasets/imdb_reviews/plain_text/1.0.0.incompleteX2ZR5W/imdb_reviews-train.tfrecord
Shuffling and writing examples to /home/kbuilder/tensorflow_datasets/imdb_reviews/plain_text/1.0.0.incompleteX2ZR5W/imdb_reviews-test.tfrecord
Shuffling and writing examples to /home/kbuilder/tensorflow_datasets/imdb_reviews/plain_text/1.0.0.incompleteX2ZR5W/imdb_reviews-unsupervised.tfrecord
Dataset imdb_reviews downloaded and prepared to /home/kbuilder/tensorflow_datasets/imdb_reviews/plain_text/1.0.0. Subsequent calls will reuse this data.

データを探索する

データの形式を理解してみましょう。各例は、映画のレビューと対応するラベルを表す文です。文章は前処理されていません。ラベルは0または1の整数値で、0は否定的なレビュー、1は肯定的なレビューです。

print("Training entries: {}, test entries: {}".format(len(train_examples), len(test_examples)))
Training entries: 25000, test entries: 25000

最初の10個の例を印刷してみましょう。

train_examples[:10]
array([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.",
       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.',
       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.',
       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.',
       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.',
       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.",
       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.',
       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.',
       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!',
       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.'],
      dtype=object)

最初の10枚のラベルも印刷してみましょう。

train_labels[:10]
array([0, 0, 0, 1, 1, 1, 0, 0, 0, 0])

モデルを構築する

ニューラルネットワークは、レイヤーの積み重ねによって作成されます。これには、3つの主要なアーキテクチャ上の決定が必要です。

  • テキストをどのように表すか?
  • モデルで使用するレイヤーの数は?
  • 各レイヤーに使用する隠しユニットの数は?

この例では、入力データは文で構成されています。予測するラベルは0または1です。

テキストを表現する1つの方法は、文章を埋め込みベクトルに変換することです。事前トレーニング済みのテキスト埋め込みを最初のレイヤーとして使用できます。これには2つの利点があります。

  • テキストの前処理について心配する必要はありません。
  • 転移学習の恩恵を受けることができます。

この例では、 google / tf2-preview / gnews-swivel-20dim / 1というTensorFlow Hubのモデルを使用します。

このチュートリアルのためにテストする他の3つのモデルがあります。

まず、TensorFlow Hubモデルを使用して文章を埋め込むKerasレイヤーを作成し、いくつかの入力例で試してみましょう。生成された埋め込みの出力形状は(num_examples, embedding_dimension)注意してください。

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])
<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)>

次に、完全なモデルを作成します。

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()
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
_________________________________________________________________

分類子を構築するために、レイヤーは順番に積み重ねられます。

  1. 最初のレイヤはTensorFlow Hubレイヤです。このレイヤーは、事前トレーニングされた保存モデルを使用して、文をその埋め込みベクトルにマッピングします。使用しているモデル( google / tf2-preview / gnews-swivel-20dim / 1 )は、文をトークンに分割し、各トークンを埋め込み、次に埋め込みを結合します。結果のディメンションは(num_examples, embedding_dimension)です。
  2. この固定長の出力ベクトルは、16個の非表示ユニットを持つ完全に接続された( Dense )レイヤーを介してパイプ処理されます。
  3. 最後のレイヤーは単一の出力ノードに密に接続されています。これにより、ロジットが出力されます。モデルによれば、真のクラスの対数オッズです。

隠しユニット

上記のモデルには、入力と出力の間に2つの中間層または「非表示」層があります。出力(ユニット、ノード、またはニューロン)の数は、レイヤーの表現空間の次元です。言い換えると、内部表現を学習するときにネットワークが許可される自由の量です。

モデルに非表示の単位(高次元の表現空間)やレイヤーが多い場合、ネットワークはより複雑な表現を学習できます。ただし、ネットワークの計算コストが高くなり、不要なパターン(トレーニングデータのパフォーマンスは向上するがテストデータのパフォーマンスは向上しないパターン)の学習につながる可能性があります。これはオーバーフィッティングと呼ばれ、後で詳しく説明します。

損失関数とオプティマイザ

モデルには、損失関数とトレーニング用のオプティマイザが必要です。これはバイナリ分類の問題であり、モデルは確率(シグモイドアクティベーションの単一ユニットレイヤー)を出力するため、 binary_crossentropy損失関数を使用します。

これは損失関数の唯一の選択肢ではありません。たとえば、 mean_squared_error選択できます。ただし、一般的に、 binary_crossentropyは確率を処理するのに適しています。 binary_crossentropyは、確率分布間の、またはこの場合はグラウンドトゥルース分布と予測間の「距離」を測定します。

後で、回帰問題(たとえば、家の価格を予測するため)を調査するときに、平均二乗誤差と呼ばれる別の損失関数の使用方法を確認します。

次に、オプティマイザと損失関数を使用するようにモデルを構成します。

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

検証セットを作成する

トレーニングするときは、これまでに見たことのないデータについてモデルの精度をチェックしたいと思います。元のトレーニングデータから10,000の例を分けて、 検証セットを作成します。 (今すぐテストセットを使用しないのはなぜですか?私たちの目標は、トレーニングデータのみを使用してモデルを開発および調整し、テストデータを1回だけ使用して精度を評価することです)。

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

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

モデルをトレーニングする

512サンプルのミニバッチで40エポックのモデルをトレーニングします。これは、内の全サンプルの40回の反復でx_trainy_trainテンソル。トレーニング中に、検証セットからの10,000サンプルに対するモデルの損失と精度を監視します。

history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=40,
                    batch_size=512,
                    validation_data=(x_val, y_val),
                    verbose=1)
Epoch 1/40
30/30 [==============================] - 1s 47ms/step - loss: 0.7642 - accuracy: 0.5281 - val_loss: 0.6873 - val_accuracy: 0.5783
Epoch 2/40
30/30 [==============================] - 1s 41ms/step - loss: 0.6485 - accuracy: 0.6325 - val_loss: 0.6208 - val_accuracy: 0.6560
Epoch 3/40
30/30 [==============================] - 1s 41ms/step - loss: 0.5945 - accuracy: 0.6867 - val_loss: 0.5825 - val_accuracy: 0.6940
Epoch 4/40
30/30 [==============================] - 1s 40ms/step - loss: 0.5537 - accuracy: 0.7245 - val_loss: 0.5483 - val_accuracy: 0.7250
Epoch 5/40
30/30 [==============================] - 1s 41ms/step - loss: 0.5158 - accuracy: 0.7543 - val_loss: 0.5169 - val_accuracy: 0.7517
Epoch 6/40
30/30 [==============================] - 1s 40ms/step - loss: 0.4793 - accuracy: 0.7825 - val_loss: 0.4873 - val_accuracy: 0.7728
Epoch 7/40
30/30 [==============================] - 1s 41ms/step - loss: 0.4431 - accuracy: 0.8062 - val_loss: 0.4588 - val_accuracy: 0.7863
Epoch 8/40
30/30 [==============================] - 1s 41ms/step - loss: 0.4086 - accuracy: 0.8244 - val_loss: 0.4317 - val_accuracy: 0.8038
Epoch 9/40
30/30 [==============================] - 1s 41ms/step - loss: 0.3757 - accuracy: 0.8415 - val_loss: 0.4076 - val_accuracy: 0.8180
Epoch 10/40
30/30 [==============================] - 1s 41ms/step - loss: 0.3471 - accuracy: 0.8571 - val_loss: 0.3905 - val_accuracy: 0.8263
Epoch 11/40
30/30 [==============================] - 1s 41ms/step - loss: 0.3219 - accuracy: 0.8688 - val_loss: 0.3732 - val_accuracy: 0.8359
Epoch 12/40
30/30 [==============================] - 1s 41ms/step - loss: 0.2978 - accuracy: 0.8788 - val_loss: 0.3598 - val_accuracy: 0.8420
Epoch 13/40
30/30 [==============================] - 1s 42ms/step - loss: 0.2772 - accuracy: 0.8903 - val_loss: 0.3485 - val_accuracy: 0.8460
Epoch 14/40
30/30 [==============================] - 1s 43ms/step - loss: 0.2582 - accuracy: 0.8978 - val_loss: 0.3384 - val_accuracy: 0.8527
Epoch 15/40
30/30 [==============================] - 1s 41ms/step - loss: 0.2407 - accuracy: 0.9073 - val_loss: 0.3313 - val_accuracy: 0.8584
Epoch 16/40
30/30 [==============================] - 1s 42ms/step - loss: 0.2251 - accuracy: 0.9153 - val_loss: 0.3253 - val_accuracy: 0.8627
Epoch 17/40
30/30 [==============================] - 1s 41ms/step - loss: 0.2105 - accuracy: 0.9224 - val_loss: 0.3260 - val_accuracy: 0.8627
Epoch 18/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1970 - accuracy: 0.9267 - val_loss: 0.3176 - val_accuracy: 0.8664
Epoch 19/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1841 - accuracy: 0.9337 - val_loss: 0.3169 - val_accuracy: 0.8673
Epoch 20/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1721 - accuracy: 0.9404 - val_loss: 0.3186 - val_accuracy: 0.8674
Epoch 21/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1621 - accuracy: 0.9446 - val_loss: 0.3141 - val_accuracy: 0.8700
Epoch 22/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1513 - accuracy: 0.9495 - val_loss: 0.3150 - val_accuracy: 0.8706
Epoch 23/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1421 - accuracy: 0.9539 - val_loss: 0.3229 - val_accuracy: 0.8688
Epoch 24/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1348 - accuracy: 0.9560 - val_loss: 0.3178 - val_accuracy: 0.8724
Epoch 25/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1246 - accuracy: 0.9621 - val_loss: 0.3204 - val_accuracy: 0.8711
Epoch 26/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1167 - accuracy: 0.9659 - val_loss: 0.3235 - val_accuracy: 0.8705
Epoch 27/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1093 - accuracy: 0.9689 - val_loss: 0.3266 - val_accuracy: 0.8717
Epoch 28/40
30/30 [==============================] - 1s 41ms/step - loss: 0.1027 - accuracy: 0.9707 - val_loss: 0.3331 - val_accuracy: 0.8696
Epoch 29/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0959 - accuracy: 0.9729 - val_loss: 0.3362 - val_accuracy: 0.8706
Epoch 30/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0894 - accuracy: 0.9752 - val_loss: 0.3407 - val_accuracy: 0.8695
Epoch 31/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0837 - accuracy: 0.9775 - val_loss: 0.3463 - val_accuracy: 0.8689
Epoch 32/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0781 - accuracy: 0.9803 - val_loss: 0.3529 - val_accuracy: 0.8684
Epoch 33/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0733 - accuracy: 0.9825 - val_loss: 0.3590 - val_accuracy: 0.8677
Epoch 34/40
30/30 [==============================] - 1s 40ms/step - loss: 0.0680 - accuracy: 0.9841 - val_loss: 0.3635 - val_accuracy: 0.8694
Epoch 35/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0634 - accuracy: 0.9857 - val_loss: 0.3698 - val_accuracy: 0.8696
Epoch 36/40
30/30 [==============================] - 1s 40ms/step - loss: 0.0591 - accuracy: 0.9870 - val_loss: 0.3778 - val_accuracy: 0.8690
Epoch 37/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0553 - accuracy: 0.9885 - val_loss: 0.3847 - val_accuracy: 0.8684
Epoch 38/40
30/30 [==============================] - 1s 42ms/step - loss: 0.0512 - accuracy: 0.9895 - val_loss: 0.3913 - val_accuracy: 0.8685
Epoch 39/40
30/30 [==============================] - 1s 42ms/step - loss: 0.0475 - accuracy: 0.9913 - val_loss: 0.4005 - val_accuracy: 0.8667
Epoch 40/40
30/30 [==============================] - 1s 41ms/step - loss: 0.0442 - accuracy: 0.9922 - val_loss: 0.4085 - val_accuracy: 0.8657

モデルを評価する

そして、モデルのパフォーマンスを見てみましょう。 2つの値が返されます。損失(エラーを表す数値。値が小さいほど優れています)、および精度。

results = model.evaluate(test_data, test_labels)

print(results)
782/782 [==============================] - 3s 4ms/step - loss: 0.4420 - accuracy: 0.8525
[0.4420316517353058, 0.8525199890136719]

このかなり単純なアプローチは、約87%の精度を達成します。より高度なアプローチでは、モデルは95%に近づくはずです。

時間の経過に伴う精度と損失のグラフを作成する

model.fit()は、トレーニング中に発生したすべてを含むディクショナリを含むHistoryオブジェクトを返します。

history_dict = history.history
history_dict.keys()
dict_keys(['loss', 'accuracy', 'val_loss', 'val_accuracy'])

4つのエントリがあります。トレーニングおよび検証中に監視された各メトリックに1つです。これらを使用して、比較のためにトレーニングと検証の損失、およびトレーニングと検証の精度をプロットできます。

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

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()

png

このプロットでは、点はトレーニングの損失と精度を表し、実線は検証の損失と精度です。

訓練損失エポックごとに減少し、訓練精度はエポックごとに増加することに注意してください。これは、勾配降下最適化を使用する場合に予想されます。反復ごとに必要な量を最小限に抑える必要があります。

これは、検証の損失と精度には当てはまりません。約20エポック後にピークに達するようです。これは過剰適合の例です。モデルは、これまでに見たことのないデータよりもトレーニングデータの方が優れています。この後、モデルは、テストデータに一般化されないトレーニングデータに固有の表現を過剰に最適化して学習します。

この特定のケースでは、20程度のエポック後にトレーニングを停止するだけで、過剰適合を防ぐことができます。後で、コールバックを使用してこれを自動的に行う方法を確認します。


#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.