期望密集数组的形状为,但得到的数组形状为。

12
我在使用Keras运行文本分类模型时,调用model.predict函数时遇到以下错误。我已经搜索了所有地方,但对我没有帮助。

当运行一个文本分类模型时,在调用model.predict函数时,我遇到了如下的错误。我已经到处搜索过,但是还是没有解决问题。

ValueError: Error when checking input: expected dense_1_input to have shape (100,) but got array with shape (1,)

我的数据有5个类别,仅有15个样本。下面是数据集:

             query        tags
0               hi       intro
1      how are you       wellb
2            hello       intro
3        what's up       wellb
4       how's life       wellb
5              bye          gb
6    see you later          gb
7         good bye          gb
8           thanks   gratitude
9        thank you   gratitude
10  that's helpful   gratitude
11      I am great  revertfine
12            fine  revertfine
13       I am fine  revertfine
14            good  revertfine

这是我的模型代码

from keras.preprocessing.text import Tokenizer
from sklearn.preprocessing import LabelBinarizer
from keras.models import Sequential
import pandas as pd
from keras.layers import Dense, Activation

data = pd.read_csv('text_class.csv')
train_text = data['query']
train_labels = data['tags']

tokenize = Tokenizer(num_words=100)
tokenize.fit_on_texts(train_text)

x_data = tokenize.texts_to_matrix(train_text)

encoder = LabelBinarizer()
encoder.fit(train_labels)
y_data = encoder.transform(train_labels)

model = Sequential()
model.add(Dense(512, input_shape=(100,)))
model.add(Activation('relu'))
model.add(Dense(5))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
model.fit(x_data, y_data, batch_size=8, epochs=10)

predictions = model.predict(x_data[0])
tag_labels = encoder.classes_
predicted_tags = tag_labels[np.argmax(predictions)]
print (predicted_tags)

我无法确定问题出在哪里以及如何修复它。


1
x_data的形状是什么? - lordingtar
@lordingtar 15,100 - Bhavesh Laddagiri
2个回答

15

x_data 是一个形状为 (15, 100) 的二维数组

  print(x_data.shape) 

但是x_data [0]是形状为(100,)的一维数组

  print(x_data[0].shape) 

并且它会导致问题。

使用切片x_data[0:1]将其作为形状为(1, 100)的二维数组获取。

 print(x_data[0:1].shape) 

它会起作用

 predictions = model.predict(x_data[0:1])

1
完全无关的问题。你是如何将他的文本数据转换成csv或dataframe格式的? - Krishna
1
@krishna 我使用了 pandas.read_table(filename, sep="\s{2,}"),甚至使用了 io.StringIO(text) 在内存中创建文件,而不是在磁盘上。 - furas
非常感谢您的支持! - Bhavesh Laddagiri

3

predictions = model.predict(x_data) 改为 predictions = model.predict(x_data[0:1])

你的神经网络输入层有100个神经元,但看起来你的输入形状只有(1,),因此你需要改变输入形状


无法工作,它说检查输入时出错:期望dense_19_input的形状为(1),但得到的数组形状为(100)错误。 - Bhavesh Laddagiri
@BhaveshLaddagiri 我更新了我的答案。希望能有所帮助。 - Rishabh Mandayam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接