import keras
from keras.layers import dense
from keras import models
from keras import optimizers
from keras.datasets import imdb
from keras import losses
import numpy as np
import matplotlib.pyplot as plt
def fig_loss(history):
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, 'b-.', label='training loss')
plt.plot(epochs, val_loss_values, 'r--', label='validation loss')
plt.title('training and validation loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.grid()
plt.show()
def fig_acc(history):
history_dict = history.history
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'g:', label='training acc')
plt.plot(epochs, val_acc, 'r-', label='validation acc')
plt.title('training and validation accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.grid()
plt.show()
def to_array(a, col):
for i in range(len(a)):
a[i] = keras.utils.to_categorical(np.array(a[i]), num_classes=col)
a[i] = np.sum(a[i], axis=0)
return np.array(a.tolist())
if __name__ == "__main__":
size = 10000
model = models.sequential()
model.add(dense(64, activation='relu', input_shape=(size,)))
model.add(dense(32, activation='relu'))
model.add(dense(1, activation='sigmoid'))
model.compile(optimizer=optimizers.rmsprop(lr=0.001),
loss=losses.binary_crossentropy,
metrics=['accuracy'])
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=size)
y_train = np.asarray(train_labels).astype('float32')
x_test = to_array(test_data, size)
test_labels = np.asarray(test_labels).astype('float32')
x_train = to_array(train_data, size)
x = x_train[:size]
x_val = x_train[size:]
y = train_labels[:size]
y_val = train_labels[size:]
history = model.fit(x, y, epochs=8, validation_data=(x_val, y_val))
results = model.evaluate(x_test, test_labels)
print('訓練結束,評估模型->')
print('損失:')
print(results[0])
print('精度:')
print(results[1])
# 繪製訓練損失和驗證損失
fig_loss(history)
# 繪製訓練精度和驗證精度
fig_acc(history)
輸出:
訓練結束,評估模型->
損失:1.0794099688053131
精度:0.8561199903488159
訓練損失和驗證損失:
訓練精度和驗證精度:
附:《ai:普通列表陣列轉化為one-hot編碼的numpy陣列矩陣》
基於Keras的imdb資料集電影評論情感二分類
載入資料集 from keras.datasets import imdb train data,train labels test data,test labels imdb.load data num words 10000 train data 0 1,14,22,16,178,32 trai...
電影評論二分類問題
jyupter notebook上編寫 from tensorflow.python.keras.datasets import imdb import numpy as np train data,train labels test data,test labels imdb.load data ...
模糊神經網路 第41期 AI演算法 模糊神經網路
關注人工智慧教師,拓展人工智慧教育新認知 演算法在人工智慧 ai 領域非常重要,我們需要把實際問題抽象成數學問題,再讓機器對數學問題進行求解。而演算法的選擇直接導致了能否解決問題,以及以多少成本解決問題。第01期 什麼是人工智慧 第3期 圖靈測試 第5期 神經網路 第8期 機器學習 第10期 大資料...