1. 程式人生 > >AI-040: Python深度學習3 - 三個Karas例項-2

AI-040: Python深度學習3 - 三個Karas例項-2

例項2:

通過路透社資料集來將文字區分46個不同主題

這裡與上一個例項不同的地方:這是個多元分類問題,因此最終輸出是46維向量

載入資料

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

預處理資料:

將樣本對映到單詞詞典,轉化為相同長度的向量

import numpy as np

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


# Our vectorized training data
x_train = vectorize_sequences(train_data)
# Our vectorized test data
x_test = vectorize_sequences(test_data)

將標籤轉換為one-hot編碼,就是這樣的向量[0,0,0,1,0,0,...],這個例子表示樣本屬於第四類主題。

def to_one_hot(labels, dimension=46):
    results = np.zeros((len(labels), dimension))
    for i, label in enumerate(labels):
        results[i, label] = 1.
    return results


# Our vectorized training labels
one_hot_train_labels = to_one_hot(train_labels)
# Our vectorized test labels
one_hot_test_labels = to_one_hot(test_labels)

構建網路:

這裡因為輸出是46維,為了防止資訊瓶頸,每層的元素要多一些,這裡先選取為64

輸出層的啟用函式選取softmax,這樣可以求取每個取值的概率,這裡一共46個概率且和為1。

from keras import models
from keras import layers

model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))

設定模型的損失函式、優化器、評估標準

由於是多元分類,這裡選取分類交叉熵作為損失函式,他將網路輸出的概率分佈與目標的真實分佈之間的距離最小化。

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

訓練模型

x_val = x_train[:1000]
partial_x_train = x_train[1000:]

y_val = one_hot_train_labels[:1000]
partial_y_train = one_hot_train_labels[1000:]

history = model.fit(partial_x_train,
                    partial_y_train,
                    # epochs=15,
                    epochs=20,  # 從繪製的圖形分析出,8輪次後出現過耦合現象,可以停止
                    batch_size=512,
                    validation_data=(x_val, y_val))

可以通過繪製損失和經度在訓練集、校驗集上的圖形來調整超引數:

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()   # clear figure

acc = history.history['acc']
val_acc = history.history['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('Loss')
plt.legend()

plt.show()

通過圖形可以看到在訓練到第八輪時達到最優,再訓練就過耦合了。可以調整輪次為9。

預測資料:

概率最大的就是最有可能的分類

predictions = model.predict(x_test)
print(predictions[1].shape)
print(np.sum(predictions[1]))
print(predictions[1])
print(np.argmax(predictions[1]))

第二個測試樣本屬於第十一類主題(0是第一類),可能性達到95%