python - 如何使用 Keras imdb 数据集预测情绪分析?

标签 python machine-learning keras deep-learning

我正在使用 keras 来实现情绪分析模型。我已经创建了模型并对其进行了训练。但现在我不确定如何预测新数据,因为 imdb 数据集已经在向量中([22,33,4, etc...])。

那么我如何对新句子进行预测,例如:“我喜欢这部电影”?

from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM, Convolution1D, Flatten, Dropout
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
from keras.callbacks import TensorBoard

# Using keras to load the dataset with the top_words
top_words = 10000
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)

# Pad the sequence to the same length
max_review_length = 1600
X_train = sequence.pad_sequences(X_train, maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test, maxlen=max_review_length)

# Using embedding from Keras
embedding_vecor_length = 300
model = Sequential()
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))

# Convolutional model (3x conv, flatten, 2x dense)
model.add(Convolution1D(64, 3, padding='same'))
model.add(Convolution1D(32, 3, padding='same'))
model.add(Convolution1D(16, 3, padding='same'))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(180,activation='sigmoid'))
model.add(Dropout(0.2))
model.add(Dense(1,activation='sigmoid'))

# Log to tensorboard
tensorBoardCallback = TensorBoard(log_dir='./logs', write_graph=True)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=3, callbacks=[tensorBoardCallback], batch_size=64)

# Evaluation on the test set
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

model.save("trained_demo.h5")

最佳答案

你必须得到单词、索引对的字典。使用它,您可以将单词转换为索引,最后填充它。

from nltk import word_tokenize
from keras.preprocessing import sequence
word2index = imdb.get_word_index()
test=[]
for word in word_tokenize( "i love this movie"):
     test.append(word2index[word])

test=sequence.pad_sequences([test],maxlen=max_review_length)
model.predict(test)

关于python - 如何使用 Keras imdb 数据集预测情绪分析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363709/

相关文章:

java - 在 Weka 中创建兼容的训练和测试实例

python - scikit-learn 中带有 BaseEstimator 的 GradientBoostingClassifier?

python - 使用 ctypes 拉取返回参数

python - Matplotlib 面向对象的代码在笔记本中内联显示

python - 如何使用 DFS 了解节点执行(调用前、调用中、调用后)

python - TensorFlow:Compat 弃用警告

python - 如何访问张量的单个特征图到keras层

python - 卡住模型并训练它

python - Tensorflow:更新不可训练模型层的权重

python - 如何在 OpenCV 中绘制一组闭合的多边形曲线,将每个段表示为不同的颜色(即在彩虹色空间中)?