著者:石井 一夫
今回は、機械学習による2値分類の方法を紹介します。映画評論のテキストを好評価な内容か悪い評価の 内容かに分類するという例題のTensorFlowのチュートリアルマニュアルに沿って、2値分類のモデリングの定番である「ロジスティック回帰分析」について解説します。
シェルスクリプトマガジン Vol.58は以下のリンク先でご購入できます。![]()
import tensorflow as tf
from tensorflow import keras
import numpy as np
imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
print(train_labels[0])
print(train_data[0])
# 整数の索引に単語を割り当てる辞書を検索する関数
word_index = imdb.get_word_index()
# 最初の索引で変換
word_index = {k:(v+3) for k,v in word_index.items()}
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2 # 不明
word_index["<UNUSED>"] = 3
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
def decode_review(text):
return ' '.join([reverse_word_index.get(i, '?') for i in text])
train_data = keras.preprocessing.sequence.pad_sequences(
train_data, value=word_index["<PAD>"],
padding='post', maxlen=256)
test_data = keras.preprocessing.sequence.pad_sequences(
test_data, value=word_index["<PAD>"],
padding='post', maxlen=256)
# 入力データの指定形式は、映画評論に用いられた単語数(10,000 単語)をとる
vocab_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16)) # 入力層
model.add(keras.layers.GlobalAveragePooling1D()) # 中間層I
model.add(keras.layers.Dense(16, activation=tf.nn.relu)) # 中間層II
model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid)) # 出力層
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='binary_crossentropy',
metrics=['accuracy'])
x_val = train_data[:10000]
partial_x_train = train_data[10000:]
y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]
history = model.fit(partial_x_train,
partial_y_train,
epochs=40,
batch_size=512,
validation_data=(x_val, y_val),
verbose=1)
results = model.evaluate(test_data, test_labels)
print(results)
%matplotlib inline
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
# 青点グラフ
plt.plot(epochs, loss, 'bo', label='Training loss')
# 青線グラフ
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()
plt.clf() # 図を初期化
acc_values = history_dict['acc']
val_acc_values = history_dict['val_acc']
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()