1)K-hot编码
# 文本向量化
import numpy as np
def k_hot(seqs, dim=10000):
result = np.zeros((len(seqs), dim))
for i,seq in enumerate(seqs):
result[i, seq] = 1
return result
即其思想是将每条评论都转换为10000长度的列表,单词出现的地方置为1,没有出现的地方置为0
譬如,[1, 1, 1, 0, 0 , ·····,0,1] 代表某个评论,其长度为10000
打印经过K-hot编码后的数据信息
x_train = k_hot(x_train)
x_train.shape
x_train[0].shape
y_train
发现是有0,1两种情况,所以他是一个二分类问题,
对于二分类问类,是使用sigmoid激活函数
2)建立模型
model = keras.Sequential()
model.add(layers.Dense(32, input_dim=10000, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.summary()
模型各层详情
3)编译模型
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['acc'])
4)训练模型
history = model.fit(x_train,y_train, epochs=15,batch_size=256,
validation_data=(x_test,y_test))
5)图形化展示效果
plt.plot(history.epoch, history.history.get('loss'), c='r', label='loss')
plt.plot(history.epoch, history.history.get('val_loss'), c='b', label='val_loss')
plt.legend()
发现经过一个Epoch后就发现对于测试集上的loss在增大了,出现了过拟合
plt.plot(history.epoch, history.history.get('acc'), c='r', label='acc')
plt.plot(history.epoch, history.history.get('val_acc'), c='b', label='val_acc')
plt.legend()
6)优化
1、适当减小网络规模
2、引入DorpOut层