我总是收到这个错误。有什么想法吗?我已经添加了所有需要的库。tensorflow有什么问题吗?我不能理解它。尝试创建一个聊天机器人。json文件是可以的。我检查了一些视频,我想我必须改变train_x和train_y数据。
import random
import numpy as np
import pandas
import nltk
import pickle
from nltk.stem import WordNetLemmatizer
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
lm = WordNetLemmatizer()
intents = json.loads(open('intents.json').read())
words = []
classes = []
documents = []
ignore = ['?', '!', '.', ',']
for intent in intents['intents']:
for pattern in intent['patterns']:
word_list = nltk.word_tokenize(pattern)
words.extend(word_list)
documents.append((word_list, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])
words =[lm.lemmatize(word) for word in words if word not in ignore]
words = sorted(set(words))
classes = sorted(set(classes))
pickle.dump(words, open('words.pkl','wb'))
pickle.dump(words, open('classes.pkl','wb'))
training = []
output = [0] * len(classes)
for document in documents:
area = []
word_pattern = document[0]
word_pattern = [lm.lemmatize(word.lower()) for word in word_pattern]
for word in words:
if word in word_pattern:
area.append(1) if word in word_pattern else area.append(0)
output_rw = list(output)
output_rw[classes.index(document[1])] = 1
training.append([area,output_rw])
random.shuffle(training)
training= np.array(training)
train_x = list(training[:, 0])
train_y = list(training[:, 1])
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'))
sgd = SGD(lr=0.01, decay=0.000001, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',optimizer=sgd, metrics=['accuracy'])
model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('chatbot model.model')
print("Done")
1条答案
按热度按时间whlutmcx1#
由于代码中的
if
条件存在错误,因此只有1被追加到该区域,从而导致train_x的每行中的元素数可变。由于数组的所有行中的元素数必须相同,因此列表不会转换为np.array
。请按如下所示更改代码。请查找工作代码here。谢谢!