Keras - 使用Tensorflow后端的LSTM

时间:2017-03-27 11:39:34

标签: python tensorflow deep-learning keras

我正在尝试here的示例代码。早些时候我遇到了使用Keras的问题 - Windows上的Theano现在刚刚迁移到Ubuntu上的Keras-Tensorflow。版本是Keras(2.0.2)和TF(0.12.1)。

keras.__version__        # 2.0.2
tensorflow.__version__   # 0.12.1

import numpy
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
# fix random seed for reproducibility
numpy.random.seed(7)
# load the dataset but only keep the top n words, zero the rest
top_words = 5000

(X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=top_words)
# truncate and pad input sequences

max_review_length = 500

X_train = sequence.pad_sequences(X_train, maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test, maxlen=max_review_length)
# create the model

embedding_vecor_length = 32
model = Sequential()
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
model.add(LSTM(100))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())

model.fit(X_train, y_train, nb_epoch=3, batch_size=64)
# Final evaluation of the model

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

错误如下,任何有关解决问题的帮助都将受到高度赞赏

  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework
  /tensor_util.py", line 302, in _AssertCompatible
  (dtype.name, repr(mismatch), type(mismatch).__name__))


**TypeError: Expected int32, got list containing Tensors of type '_Message' instead.**

1 个答案:

答案 0 :(得分:0)

您的代码在较新版本的Tensorflow上运行正常(我在Tensorflow 1.0和Keras 2.0.2上进行了检查)。您使用的是旧版Tensorflow。请更新Tensorflow,它应该完美。目前可用的Tensorflow版本是1.1