首页 > 解决方案 > 模型不适合 numpy 数组说“Int 不是可迭代对象”

问题描述

我正在使用我在 Kaggle 上找到的 intent.json 文件在 Python 中创建一个聊天机器人。整个程序运行良好,但模型拟合器抛出一个错误,即 int 不是可迭代对象,即使我只是使用 Numpy 将它转换为数组。任何建议将不胜感激。


lemmatizer = WordNetLemmatizer()
intents = json.loads(open('Intent.json').read())

words=[]
classes=[]
documents=[]
ignore_letters = ['?', '!', ',', '.']

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 = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]
words = sorted(list(set(words)))

classes = sorted(list(set(classes)))

pickle.dump(words, open('words.pkl','wb'))
pickle.dump(classes, open('classes.pkl','wb'))

training = []
output_empty = [0]*len(classes)

for document in documents:
    bag =[]
    word_patterns = document[0]
    word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]

    for word in words:
        bag.append(1) if word in word_patterns else bag.append(0)

    output_row = list(output_empty)
    output_row[classes.index(document[1])] = 1
    training.append((bag, output_row))

random.shuffle(training)
training = np.array(training, dtype=object)

#Spliting dataset
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(learning_rate=0.01, decay=1e-6, momentum=0.9, nesterov=True)

model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
model.fit( np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1) #ERROR

我的数据样本如下所示:

{"intents": [
      {"tag": "greeting",
        "patterns": ["Hi", "How are you", "Is anyone there?", "Hello", "Good day", "Whats up", "Hey", "greetings"],
        "responses": ["Hello!", "Good to see you again!", "Hi there, how can I help?"],
        "context_set": ""
      },
      {"tag": "goodbye",
        "patterns": ["cya", "See you later", "Goodbye", "I am Leaving", "Have a Good day", "bye", "cao", "see ya"],
        "responses": ["Thanks for dropping by!", "Talk to you later", "Goodbye!"],
        "context_set": ""
      },
      {"tag": "weightquery",
        "patterns": ["How much weight can it hold?", "Is there a limit to weight?", "Can it hold 10kg?", "How many pounds can it hold?", "How many kgs can it hold?"],
        "responses": ["15Kg or 33 pounds"],
        "context_set": ""
      }
    ]
    }

标签: pythonarraysnumpytensorflow

解决方案


推荐阅读