深度學習之電影二分類的情感問題

無風聽海發表於2021-04-13

二分類問題可能是應用最廣泛的機器學習問題。今天我們將學習根據電影評論的文字內容將其劃分為正面或負面。

一、資料集來源

我們使用的是IMDB資料集,它包含來自網際網路電影資料庫(IMDB)的50000條嚴重兩極分化的評論。為了避免模型過擬合只記住訓練資料,我們將資料集分為用於訓練的25000條評論與用於測試的25000條評論,訓練集和測試集都包含50%的正面評論和50%的負面評論。

與MNIST資料集一樣,IMDB資料集也內建於Keras庫。它已經過預處理:評論(單詞序列)已經被轉換為整數序列,其中每個整數代表字典中的某個單詞。

通過以下程式碼載入資料集並限制每條評論最多取前一萬個常用的word,以便於我們進行向量處理。

import tensorflow as tf

imdb = tf.keras.datasets.imdb
(train_data, train_labels),(test_data, test_labels) = imdb.load_data(num_words=10000)
print(train_data[0])
print(train_labels[0])

通過輸出可以看到,train_data和test_data是評論記錄的集合,每條評論記錄又是由眾多的單詞索引組成的集合。
train_labels和test_labels是針對評論的分類的集合,其中0表示負面評論,1表示正面評論。

[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 2, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 2, 8, 4, 107, 117, 5952, 15, 256, 4, 2, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 2, 1029, 13, 104, 88, 4, 381, 15, 297, 98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32]
1

我們可以通過word與編號的對映關係將評論的內容轉化為具體的文字

def get_text(comment_num):
    """將數字形式的評論轉化為文字"""
    # word_index = tf.keras.datasets.imdb.get_word_index()
    word_index = imdb.get_word_index()
    reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
    text = ' '.join([reverse_word_index.get(i - 3, '?') for i in comment_num])
    return text

comment = get_text(train_data[0])
print(comment)

第一條電影評論的內容

? 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 actor and now the same being director ?

二、格式化輸入資料

由於我們無法直接將整數序列輸入神經網路,所以需要將其轉換為張量。可以通過以下兩種方式進行轉化

  • 填充列表,使其具有相同的長度,然後將列表轉化為(samples, word_index)的2D形狀的整數張量。
  • 對列表進行one-hot編碼,將其轉化為0和1組成的向量。

這裡我們採用one-hot進行編碼處理

def vectorize_sequences(sequences, diamension = 10000):
    results = np.zeros((len(sequences), diamension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1

    return results


x_train = vectorize_sequences(train_data)
print(x_train[0])
print(len(x_train[0]))
x_test = vectorize_sequences(test_data)
print(x_test[0])
print(len(x_test[0]))

轉化完成的輸入結果

[0. 1. 1. ... 0. 0. 0.]
10000
[0. 1. 1. ... 0. 0. 0.]
10000

將標籤進行向量化處理

y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

三、構建神經網路

針對這裡二分類單標籤,我們可以直接使用帶有relu啟用函式的全連線層的簡單堆疊。
我們使用了兩個具有16個隱藏單元的中間層和具有一個隱藏單元的層。中間層使用的relu啟用函式負責將所有的負值歸零,最後一層使用sigmoid函式將任意值壓縮到[0,1]之間並作為預測結果的概率。

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

這裡的Dense層實現瞭如下的張量計算,傳入Dense層的引數16表示隱藏單元的個數,同時也表示這個層輸出的資料的維度數量。隱藏單元越多,網路越能夠學習到更加複雜的表示,但是網路計算的代價就越高。

output = relu(dot(W, input) + b)

我們使用rmsprop優化器和binary_crossentropy損失函式來配置模型。

model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

四、訓練模型

將訓練資料分出一小部分作為校驗資料,同時將512個樣本作為一批量處理,並進行20輪的訓練,同時出入validation_data來監控校驗樣本上的損失和計算精度。

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

呼叫fit()返回的history物件包含訓練過程的所有資料

history_dict = history.history
print(history_dict.keys())

字典中包含4個條目,對應訓練過程和校驗過程的指標,其中loss是訓練過程中損失指標,accuracy是訓練過程的準確性指標,而val_loss是校驗過程的損失指標,val_accuracy是校驗過程的準確性指標。

dict_keys(['loss', 'accuracy', 'val_loss', 'val_accuracy'])

我們使用Matplotlib畫出訓練損失和校驗損失的情況

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

從圖中可以看到整個訓練過程,損失函式值一直在不斷的變小,但是校驗過程的損失函式值卻先變小後變大,在2.5-5之間的某個點達到最小值。

我們使用Matplotlib畫出訓練精度和校驗精度的情況

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

從圖中可以看到整個訓練過程,準確度值一直在不斷的升高,但是校驗過程的精度數值卻在不斷的進行波動,在2.5-5之間的某個點達到最大值。

通過對訓練和校驗指標的分析,可以看到訓練的損失每輪都在降低,訓練的精度每輪都在提升。但是校驗損失和校驗精度基本上在第4輪左右達到最佳值。為了防止這種過擬合的情況,我們可以在第四輪完成之後直接停止訓練。

history = model.fit(partial_x_train, partial_y_train, epochs= 4, batch_size=512, validation_data=(x_val, y_val))
results = model.evaluate(x_test, y_test)
print(results)

重新執行可以看到模型的精度可以達到87%

782/782 [==============================] - 1s 876us/step - loss: 0.3137 - accuracy: 0.8729
[0.3137112557888031, 0.8728799819946289]

五、使用測試資料預測結果

使用訓練的模型對test資料集進行預測

result = model.predict(x_test)
print(result)
[[0.31683978]
 [0.9997941 ]
 [0.9842608 ]
 ...
 [0.18170357]
 [0.23360077]
 [0.6573206 ]]

六、小結

  • 需要對原始資料進行預處理並轉化為符合要求的張量。
  • 對於二分類問題,最後一層使用sigmoid作為啟用函式,並輸出0-1的標量來表示結果出現的概率。
  • 對於二分類問題的sigmoid標量輸出,應該使用binary_crossentropy損失函式。
  • 隨著訓練過程的進行,很容易出現過擬合現象,我們需要時刻監控模型在非訓練資料集的表現。

完整程式碼下載

相關文章