python - Keras + LSTM/RNN : trouble with dimensionality of `X` 's for new predictions

标签 python keras lstm dimensions recurrent-neural-network

摘要

在正确生成模型后,我无法为预测提供输入数据的正确维度。

我收到以下错误:

ValueError: Error when checking : expected lstm_13_input to have shape (None, 40, 39) but got array with shape (1, 39, 39)

背景

  • 使用 Anaconda 作为我的虚拟环境
  • Keras 版本 2.0.6
  • TensorFlow 版本 1.1.0

我正在创建一个非常接近 this tutorial 的示例.

代码

以下是相关代码片段:

from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.layers import LSTM,TimeDistributed,SimpleRNN
from keras.utils.data_utils import get_file
import numpy as np
from time import sleep
import random
import sys

...

X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sentences),maxlen, len(chars)), dtype=np.bool) # y is also a sequence , or  a seq of 1 hot vectors
for i, sentence in enumerate(sentences):
    for t, char in enumerate(sentence):
        X[i, t, char_indices[char]] = 1

for i, sentence in enumerate(next_chars):
    for t, char in enumerate(sentence):
        y[i, t, char_indices[char]] = 1

...

model = Sequential()
model.add(LSTM(512, return_sequences=True, input_shape=(maxlen, len(chars))))  # original one
model.add(LSTM(512, return_sequences=True)) #- original
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(len(chars))))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

...

history=model.fit(X, y, batch_size=128, nb_epoch=1,verbose=0)

...

seed_string="brutus:\nbeing so moved, he will not spare"
x=np.zeros((1, len(seed_string), len(chars)))
for t, char in enumerate(seed_string):
    x[0, t, char_indices[char]] = 1.
preds = model.predict(x, verbose=0)[0]

错误

在最后一行,它出错了,并出现以下错误:

ValueError: Error when checking : expected lstm_13_input to have shape (None, 40, 39) but got array with shape (1, 39, 39)

努力解决

我已经玩过seed_string维度和由它生成的x,但无论我如何尝试调整它们,我有某种不匹配,总是由于 None 的要求(我认为)。需要明确的是,我在种子字符串中添加或删除了字符,因此它是 40 个字符。但是,当我将其设置为 40 时,错误表明我实际上有 41,而当我将其设置为 39 时,它说我有39,如上所示。这里还发生了其他事情 - 我不明白。

我查看了Reshape's code和一个example of how to use it ,但由于 Keras 的 Reshape 适用于模型层,我什至不明白如何使用它来 reshape 输入预测,并且 Numpy 无法 reshape 创建 None 维度(至少据我所知)。

最佳答案

seed_string 的长度需要与 maxlen 匹配。您可以使用 pad_sequences 处理字符串短于或长于 maxlen 的情况。 。在你的情况下,你的字符串太长。

from keras.preprocessing.sequence import pad_sequences

seed_string = "brutus:\nbeing so moved, he will not spare"

x = np.zeros((1, len(seed_string), len(chars)))

for t, char in enumerate(seed_string):
    x[0, t, char_indices[char]] = 1.

x = pad_sequences(x, maxlen=maxlen)

preds = model.predict(x, verbose=0)[0]

关于python - Keras + LSTM/RNN : trouble with dimensionality of `X` 's for new predictions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45392218/

相关文章:

python - 如何遍历字符串中的所有字符,然后检查是否有字符包含小写、大写、数字和标点符号并返回 True

python - 使用 class_weight 来不平衡数据-.fit_generator()

python - anaconda安装keras时报错./p KERAS_BACKEND= 0<temp.txt

deep-learning - 使用 pytorch 创建 LSTM 模型

keras - 如何设置 Keras LSTM 进行时间序列预测?

machine-learning - LSTM 的输入到底是什么?

python - 如何阻止我的蛇向自身移动(python,pygame)

Python 范围函数本身

python - 用 Pandas .replace 替换列数据不起作用

python - 使用 BatchNorm 层和 tensorflow 训练 Keras 模型