IMDB影评分类

IMDB影评分类

输入数据要求

  • 分类问题

输入数据是向量,标签是标量[0/1]代表差/好评

数据导入

from keras.datasets import imdb

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(
    num_words=10000)
### 数据观测
#输入数据是数字的数组,数字映射英文单词
#eg:[1,14,22,48,6489,9999,...,598]
#word_index是  英文字母:数字  的映射字典
word_index = imdb.get_word_index()
#键值反转, 数字:英文字母
reverse_word_index = dict(
    (value, key) for (key, value) in word_index.items())
#显示第一条影评
decode_review = ' '.join(
    [reverse_word_index.get(i - 3, '?') for i in train_data[0]])
### 数据处理
#目的是吧输入数据处理成显示词频的向量,有该单词则向量对应位置置1
import numpy as np

def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences),dimension))
    for i, sequence in enumerate(sequences):
        #print(sepuence)
        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=['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=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))

#使用512个样本的小批量,将模型训练20轮次,监控validation_data(留出的10000个样本——验证数据)

模型评估

# 画损失率和正确率的变化图
history_dict = history.history
print(history_dict.keys())
#dict_keys(['val_loss', 'val_acc', 'loss', 'acc'])
# 损失率
import matplotlib.pyplot as plt

acc = history.history['acc']
val_acc = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

epoch = range(1, len(acc) +1)

plt.plot(epoch,loss,'bo', label='Training Loss')

plt.plot(epoch,val_loss,'b',label='Validation Loss')

plt.title('Training and validation')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()
# 正确率
plt.clf()

plt.plot(epoch,acc,'bo',label='Training acc')
plt.plot(epoch,val_acc,'b',label='Validation acc')
plt.title('Training and Validation accuracy')
plt.xlabel('Epoch')
plt.ylabel('accuracy')
plt.legend()

plt.show()
### 模型优化 >画图得知模型在4轮后过拟合了,所以4轮时停止 >这里我改了一改模型··请忽略 :P
model = models.Sequential()
model.add(layers.Dense(16, activation='relu',input_shape=(10000,)))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(64, 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)
result = model.evaluate(x_test, y_test)
#result
#[0.31514283887386324, 0.88116]

### 模型使用 >model.predict(x_test)#估计是好评的概率
array([[0.20031697],
       [0.99983263],
       [0.9702985 ],
       ...,
       [0.12498155],
       [0.05971182],
       [0.7418488 ]], dtype=float32)