2017-07-29 127 views
1

摘要`X`的維度,麻煩

我有麻煩能後,我輸入數據提供合適的尺寸爲預測模型已經正確生成。Keras + LSTM/RNN:與新的預測

我收到以下錯誤:

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

背景

  • 使用蟒蛇作爲我的虛擬環境
  • Keras版本2.0.6
  • TensorFlow版本1.1.0

我是cre在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_stringx從它生成,但無論我如何調整它們,我有某種不匹配,總是由於None(我認爲)的這種要求。要清楚,我已經添加或從種子字符串中拿走了字符,因此它是40個字符。但是,當我將它設置爲40時,錯誤說我實際上有41,並且當我將它設置爲39時,它說我有39,如上所示。還有別的 - 我不明白 - 在這裏繼續。

我看着Reshape's codeexample of how to use it,但由於Keras' Reshape是爲模型層,我甚至不知道我怎麼會用它來重塑輸入預測,並NumPy的無方式來重塑創造一個None維度(至少不是我所知)。

回答

1

您的seed_string的長度需要匹配maxlen。您可以同時處理您的字符串的場景短於或長於maxlenpad_sequences。在你的情況下,你的字符串太長。

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] 
+0

嗨@Nicole感謝您的建議,但正如我在原始問題中所說,我已經這樣做了。清楚的是,我*看到* 40''''在尺寸'(None,40,39)'和'(1,39,39)'中不匹配。但是種子的大小並不是問題,儘管看起來是這樣。 (實際上,它會說它是39,或者跳到41,即使我只添加1個字符)。這個問題似乎是另一回事,我不太明白。 –

+0

你真的嘗試過使用pad_sequences嗎,還是隻是嘗試改變字符串的長度? –

+0

我剛剛改變了長度。我不知道[pad_sequence](https://keras.io/preprocessing/sequence/#pad_sequences)。我會嘗試的。但是,我確實已將它們作爲具有適當維數的「numpy」陣列。 (例如,我縮短了字符串的長度,然後***將字符串矢量化爲一個具有適當維數的單編碼'numpy'多維數組。) –