【问题标题】:ValueError: Error when checking input: expected dense_input to have shape (213,) but got array with shape (210,)ValueError:检查输入时出错:预期的dense_input具有形状(213,)但得到的数组具有形状(210,)
【发布时间】:2020-12-05 14:28:57
【问题描述】:

输入数组似乎不适合输入形状,但我不知道如何修复它。

这是我构建模型的方式:

model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))

# Compile the model
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

#Training and saving the model

hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('buy_model_08152020th.h5', hist)
#print("model is created")

这里是预测类函​​数:

def predict_class(sentence):
    global custom_prompt
    # filter below threshold predictions
    p = bag_of_words(sentence, words, show_details=False)
    res = model.predict(np.array([p]))[0]
    error_threshold = 0.90
    results = [[i, r] for i,r in enumerate(res) if r > error_threshold]
    # Sort strength probability
    results.sort(key=lambda x: x[1], reverse=True)
    return_list = [{"intent": "message classification failed"}]
    for r in results:
        return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
    if len(return_list) > 1:      
        result = return_list[1]["intent"]
    if len(return_list) == 1:
        result = return_list[0]["intent"]               
    return result

还有bag_of_words_function:

def bag_of_words(sentence, words, show_details=True):
    sentence_words = clean_up_sentence(sentence)
    #bag of words - vocabulary matrix
    bag = [0] * len(words)
    for s in sentence_words:
        for i,word in enumerate(words):
            if word == s:
                bag[i] = 1
                if show_details:
                    print('found in bag: %s' %word)
    return(np.array(bag))

错误信息:

ValueError:检查输入时出错:预期的 dense_input 有 形状 (213,) 但得到了形状 (210,) 的数组

【问题讨论】:

  • 您能否提供bag_of_words函数的详细信息?
  • 刚刚将 bag_of_words 函数添加到问题中。
  • @LucasJacaruso,你必须pad你的序列,这样所有的句子都会有相同的单词数。如果这不能解决您的问题,请分享完整的代码,以便我们最终重现它。谢谢!

标签: python tensorflow keras neural-network nlp


【解决方案1】:

正如错误消息所暗示的,input_shape=(len(train_x[0]),) 在训练模型时是 213,但您在进行预测时使用的是 210 的输入 p。建议您打印模型输入的lenprint len(train_x[0]))和预测输入的lenprint len(p))。它们都应该相同,否则会引发此错误。

如果错误仍未修复,请分享可重现的代码或带有所需输入详细信息的完整代码。

【讨论】:

    猜你喜欢
    • 2021-06-08
    • 2021-02-26
    • 2022-11-03
    • 2019-08-21
    • 2020-04-05
    • 2020-09-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多