【发布时间】: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