输入数组似乎不适合输入形状,但我不知道如何解决。
这是我建立模型的方式:
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:检查输入时出错:预期density_input具有 形状(213,),但数组的形状为(210,)
答案 0 :(得分:0)
正如错误消息所暗示的,训练模型时input_shape=(len(train_x[0]),)
是213
,但是您在进行预测时正在使用p
的输入210
。建议您将输入模型的输入len
(print len(train_x[0])
)和预测输入的len
(print len(p)
)打印出来。它们应该相同,否则会引发此错误。
如果错误仍未解决,请与可重复的代码或完整的代码共享所需的输入详细信息。