解讀機器學習入門案例之IMDB數據集電影評論二分類

本文內容源於Python深度學習第三章3.4(基於keras的入門簡單使用)

筆者利用google的colab(都0202年了,colab果真比本地的IDE,jupyter好用多了,速度槓桿的,還有免費的GPU,不過首先需要那個)平臺進行演練後做的個人記錄。

完整代碼見最後,下面利用我個人的實驗截圖簡單分析。
第一步,直接導入數據集,注意函數返回的四個值。num_words是指電影評論內容的單詞設置爲前10000個常用單詞。在這裏插入圖片描述
train_data其實是列表形式的二維數組,內層是由單詞字母數字索引組成的評論,外層是評論的集合,這句話就是先比較內層的最大值,再比較外層的最大值
在這裏插入圖片描述
接下來可以有趣地看看電影評論究竟是啥內容,利用這個imdb_get_word_index()函數,單詞字母–數字索引的字典,然後反轉得到數字索引–單詞字母的reverse_word_index字典,以trani——data[0]爲例輸出。

比如這個,影評是this film was just brilliant casting location scenery story direction everyone’s really suited the part they played and you could just imagine being there robert ? is an amazing…
在這裏插入圖片描述
下面是正式的網絡訓練部分,因爲不能直接將列表數據輸入神經網絡,得先將列表轉化成張量,對列表進行 one-hot 編碼,將其轉換爲 0 和 1 組成的向量,下面是手動實現代碼。
在這裏插入圖片描述
輸入數據準備好了,開始構建、編譯和訓練模型。網絡由三層全連接層Dense構成,傳入 Dense 層的參數(16)是該層隱藏單元的個數。一個隱藏單元(hidden unit)是該層表示空間的一個維度。

對於這種 Dense 層的堆疊,你需要確定以下兩個關鍵架構:
‰網絡有多少層;
‰每層有多少個隱藏單元。

兩個中間層,每層都有 16 個隱藏單元;
第三層輸出一個標量,預測當前評論的情感。
中間層使用 relu 作爲激活函數(函數將所有負值歸零),
最後一層使用 sigmoid 激活以輸出一個 0~1 範圍內的概率值(表示樣本的目標值等於 1 的可能性,即評論爲正面的可能性)

epochss是迭代輪數,batch是每次順利的數據規模大小

在這裏插入圖片描述
在這裏插入圖片描述
上面的文字看起來不直觀,通過model.fit返回值裏面的字典成員利用loss和accuracy可視化模塊顯示出來。

在這裏插入圖片描述
在這裏插入圖片描述
由此可以看出在第四輪epoct附近,驗證數據的accuracy和loss是最好的,書上談到這是過擬合的現象,模型在訓練數據上的表現越來越好,但在前所未見的數據上不一定表現得越來越好,最簡單的方法就是重新訓練,把迭代次數降低到4。

model.evaluate(x_test,y_test)輸入數據和標籤,輸出損失和精確度
model.predict(x_test)輸入數據,輸出預測結果,最後輸出就是表示樣本的目標值等於 1 的可能性。
在這裏插入圖片描述
完整代碼(如果在jupyter Notebook類似平臺分塊運行可能會直觀一些):

from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(
 num_words=10000)

max([max(sequence) for sequence in train_data]) #最大的字母索引

word_index = imdb.get_word_index() 
reverse_word_index = dict(
 [(value, key) for (key, value) in word_index.items()])
decoded_review = ' '.join(
 [reverse_word_index.get(i - 3, '?') for i in train_data[0]])

print(decoded_review)

import numpy as np
def vectorize_sequences(sequences, dimension=10000):
 results = np.zeros((len(sequences), dimension)) 
 for i, sequence in enumerate(sequences):
  # print(i)
  # print(sequence)
  results[i, sequence] = 1. 
 return results
x_train = vectorize_sequences(train_data) 
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
 loss='binary_crossentropy',
 metrics=['acc'])
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
history = model.fit(partial_x_train,
 partial_y_train,
 epochs=20,
 batch_size=512,
 validation_data=(x_val, y_val))

# history_dict=history.history
# history_dict.keys()

import matplotlib.pyplot as plt
history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
epochs = range(1, len(loss_values) + 1)
plt.plot(epochs, loss_values, 'bo', label='Training loss') 
plt.plot(epochs, val_loss_values, 'b', label='Validation loss') 
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

plt.clf() 
acc = history_dict['acc'] 
val_acc = 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()

model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
 loss='binary_crossentropy',
 metrics=['accuracy'])
model.fit(x_train, y_train, epochs=4, batch_size=512)

results = model.evaluate(x_test, y_test)
print(results)
model.predict(x_test)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章