基于Keras的imdb数据集的情感二分类

简单的代码,后注上解析

from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense,Embedding
from keras.layers import LSTM
from keras.datasets import imdb

max_features = 20000
maxlen = 80
batch_size = 32

print('Loading data...')
(x_train,y_train),(x_test,y_test) = imdb.load_data(num_words= max_features )
print(len(x_train),'train sequences')
print(len(x_test),'test sequences')
print('Pad sequences(samples x time)')
x_train = sequence .pad_sequences(x_train ,maxlen= maxlen )
x_test = sequence .pad_sequences(x_test ,maxlen= maxlen )

print('x_train shape:',x_train .shape )
print('x_test shape:',x_test .shape )

print('Build model...')
model = Sequential()
model.add(Embedding (max_features ,128))#嵌入层将正整数下标转换为固定大小的向量。只能作为模型的第一层
model.add(LSTM (128,dropout= 0.2,recurrent_dropout= 0.2))
model.add(Dense(1,activation= 'sigmoid'))
model.compile(loss= 'binary_crossentropy',optimizer= 'adam',metrics= ['accuracy'])

print('Train...')

model.fit(x_train ,y_train ,batch_size= batch_size ,epochs= 5,validation_data= (x_test ,y_test ))

score,acc = model.evaluate(x_test ,y_test ,batch_size= batch_size )
print('Test score:',score)
print('Test accuracy:', acc)

嵌入层Embedding
嵌入层是将正整数的下标转换为就有固定大小的向量,而且只能作为模型的第一层。
其中、常用的参数:
input_dim:字典长度,即输入数据最大下标+1。
output_dim : 全连接嵌入的维度。
input_length:当输入序列的长度固定时,该值为其长度。如果要在该层后接Flatten层,然后接Dense层,则必须指定该参数,否则Dense层的输出维度无法自动推断。

你可能感兴趣的:(keras,情感)