Build the LSTM model for predicting a movie review's emotion polarity using the dataset "keras.datasets.imdb".
时间: 2024-02-13 08:03:09 浏览: 97
Sure, here's an example LSTM model for predicting the polarity of movie reviews using the IMDB dataset in Keras:
```python
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM
# Load the IMDB dataset
max_features = 20000
maxlen = 80
batch_size = 32
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
# Pad sequences to a fixed length
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
# Define the model architecture
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'))
# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, batch_size=batch_size, epochs=5, validation_data=(x_test, y_test))
# Evaluate the model on test data
score, acc = model.evaluate(x_test, y_test, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)
```
Here, we first load the IMDB dataset and pad the sequences to a fixed length of 80. Then, we define an LSTM model with an embedding layer, a LSTM layer with dropout, and a dense output layer with sigmoid activation. We compile the model with binary cross-entropy loss and Adam optimizer, and train it for 5 epochs on the training data. Finally, we evaluate the model on the test data and print the test score and accuracy.
阅读全文