我一直在尝试用python制作一个简单的聊天机器人,但我的输入形状有问题我的NN如下:
from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(8,activation='relu', input_shape=(46,)))
model.add(layers.Dense(8,activation='relu'))
model.add(layers.Dense(len(output[0]), activation = 'softmax'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(training,output,epochs = 200, batch_size=8)
我的数据的输入形状是(26,46),以一袋单词的形式当我尝试与模型聊天时,此错误显示
Error when checking input: expected dense_141_input to have shape (46,) but got array with shape (1,)
和我的聊天方式
def chat():
print("Chat with the bot type quit to end ")
while True:
inp = input("You: ")
if inp.lower() == "quit":
break
results = model.predict([bag_of_words(inp, words)])
results_index = numpy.argmax(results)
tag = labels[results_index]
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
print(random.choice(responses))
事实证明,在预测方法中,我必须使用[[]],因为我没有出现错误,所以聊天方法的固定代码看起来像这样
def chat():
print("Chat with the bot type quit to end ")
while True:
inp = input("You: ")
if inp.lower() == "quit":
break
results = model.predict([[bag_of_words(inp, words)]])
results_index = numpy.argmax(results)
tag = labels[results_index]
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
print(random.choice(responses))
希望这对遇到类似问题的人有所帮助