【问题标题】:Keras Error when checking : expected embedding_1_input to have shape (None, 100) but got array with shape (1, 3)检查时出现 Keras 错误:预期 embedding_1_input 的形状为 (None, 100) 但得到的数组形状为 (1, 3)
【发布时间】:2025-12-24 11:50:14
【问题描述】:

我使用 imdb 示例创建了 LSTM 模型,并尝试在我自己的字符串中预测情绪

max_features = 20000
# cut texts after this number of words
# (among top max_features most common words)
maxlen = 100
batch_size = 32


wordsA = "I like this review"

wordIndexes = imdb.get_word_index()

wordArray = wordsA.split()
intArray = []
for word in wordArray:
    if word in wordIndexes:
        intArray.append(wordIndexes[word])

testArray = np.array([intArray])

print('Shape: '+str(testArray.shape)) 

model = load_model('my_model2.h5')

print(str(testArray))

prediction = model.predict(testArray)
print(prediction)        

但是当我尝试进行预测时,我会因跟踪回溯而出错

Traceback(最近一次调用最后一次):

文件“”,第 1 行,在 runfile('C:/Users/Radosław/nauka/python/SentimentAnalysis/sentiment_console.py', wdir='C:/Users/Radosław/nauka/python/SentimentAnalysis')

文件 "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", 第 866 行,在运行文件中 execfile(文件名,命名空间)

文件 "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", 第 102 行,在 execfile 中 exec(编译(f.read(),文件名,'exec'),命名空间)

文件 "C:/Users/Radosław/nauka/python/SentimentAnalysis/sentiment_console.py", 第 47 行,在 预测 = model.predict(testArray)

文件 "C:\ProgramData\Anaconda3\lib\site-packages\keras\models.py", 第 899 行,在预测中 return self.model.predict(x, batch_size=batch_size, verbose=verbose)

文件 "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", 第 1555 行,在预测中 check_batch_axis=False)

文件 "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", 第 133 行,在 _standardize_input_data str(array.shape))

ValueError:检查时出错:预期 embedding_1_input 有 形状 (None, 100) 但得到了形状 (1, 3) 的数组

是否有适当的方法来重塑我的输入数组?

【问题讨论】:

  • 您正在加载的模型是如何定义的?它可能定义了一个长度为 100 个单词的输入形状。处理可变消息/文本长度的方法是填充短的并剪掉长的,这样您的输入始终是 100 字长

标签: python keras imdbpy


【解决方案1】:

您做了所有事情,但忘记了序列填充。在调用 predict 之前添加此行。

testArray = sequence.pad_sequences(testArray, maxlen=maxlen)

【讨论】:

    最近更新 更多