【问题标题】:expected dense to have shape but got array with shape预计稠密具有形状但得到具有形状的阵列
【发布时间】:2018-12-27 13:07:01
【问题描述】:

在 keras 中运行文本分类模型时调用 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)

我无法弄清楚问题出在哪里以及如何解决它。

【问题讨论】:

  • x_data 的形状是什么?
  • @lordingtar 15,100

标签: python keras shape text-classification


【解决方案1】:

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])

【讨论】:

  • 完全不相关的问题。您是如何将他的文本数据转换为 csv 或 dataframe 的?
  • @krishna 我使用pandas.read_table(filename, sep="\s{2,}") - 甚至io.StringIO(text) 在内存中创建文件,而不是在磁盘上。
  • 非常感谢...?
【解决方案2】:

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

您的 NN 中的输入层有 100 个神经元,但您的输入似乎只有 (1,) 的形状,因此您需要更改输入形状

【讨论】:

  • didbt work it says Error when checks input: expected dense_19_input to have shape (1,) but got array with shape (100,)
  • @BhaveshLaddagiri 我更新了我的答案。我希望它有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多