本程序使用了IMDB数据集,包含来自互联网电影数据库的50000条两极分化严重的评论。
# coding: utf-8
import numpy as np
from keras.datasets import imdb
from keras import models
from keras import layers
import os
from matplotlib import pyplot as plt
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 数据向量化——one-hot编码
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1
return results
def Classification():
# 准备数据
# 保留训练数据常出现的前10000个单词
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
# 数据向量化
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')
# 构建网络
model = models.Sequential()
# 10000个二维向量
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'])
# 训练模型
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=4, batch_size=512, validation_data=(x_val, y_val))
# 模型评估
history_dict = history.history
# print(history_dict.keys())
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
results = model.evaluate(x_test, y_test)
print(results)
# pre = model.predict(x_test)
# print(pre)
epochs = range(1, len(acc) + 1)
# 表示蓝色圆点
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()
if __name__ == '__main__':
Classification()