其他分享
首页 > 其他分享> > 训练LSTM模型进行情感分类在IMDB数据集上,使用Keras API(Trains an LSTM model on the IMDB sentiment classification)

训练LSTM模型进行情感分类在IMDB数据集上,使用Keras API(Trains an LSTM model on the IMDB sentiment classification)

作者:互联网

from keras.preprocessing import sequencefrom keras.models import Sequentialfrom keras.layers import Dense, Embeddingfrom keras.layers import LSTMfrom keras.datasets import imdb

max_features = 20000maxlen = 80  # cut texts after this number of words (among top max_features most common words)batch_size = 32print('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'))# try using different optimizers and different optimizer configsmodel.compile(loss='binary_crossentropy',              optimizer='adam',              metrics=['accuracy'])print('Train...')
model.fit(x_train, y_train,          batch_size=batch_size,          epochs=15,          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)
              

标签:keras,print,train,IMDB,test,import,LSTM,model
来源: https://blog.51cto.com/u_14540820/2759254