ValueError:检查目标时出错:预期dense_6的形状为(46,),但数组的形状为(1,)
Posted
技术标签:
【中文标题】ValueError:检查目标时出错:预期dense_6的形状为(46,),但数组的形状为(1,)【英文标题】:ValueError: Error when checking target: expected dense_6 to have shape (46,) but got array with shape (1,) 【发布时间】:2019-03-05 18:01:58 【问题描述】:这是印地语 OCR 的代码,图像有 1024 维,程序尝试分类为 46 类。到目前为止,我正在使用带有 Tensorflow 后端的 Keras,没有任何隐藏层。代码如下:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
dataset = pd.read_csv('data.csv')
print(dataset.head())
x = dataset.iloc[:,:-1]
y = dataset.iloc[:,-1]
print(y[0:5])
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y.values)
y = y.T
print(x.shape)
x_train,x_test,y_train,y_test = train_test_split(x.values,y)
print(y.shape)
print(np.unique(y))
from keras import Sequential
from keras.layers import Dense, Dropout
model = Sequential()
model.add(Dense(1024, activation='relu', input_dim=1024))
model.add(Dense(46, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test)
这是错误回溯:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-10-52e9b7f77a5d> in <module>()
2 model.fit(x_train, y_train,
3 epochs=20,
----> 4 batch_size=128)
5 score = model.evaluate(x_test, y_test)
~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
948 sample_weight=sample_weight,
949 class_weight=class_weight,
--> 950 batch_size=batch_size)
951 # Prepare validation data.
952 do_validation = False
~\Anaconda3\lib\site-packages\keras\engine\training.py in
_standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
785 feed_output_shapes,
786 check_batch_axis=False, # Don't enforce the batch size.
--> 787 exception_prefix='target')
788
789 # Generate sample-wise weight values given the `sample_weight` and
~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
135 ': expected ' + names[i] + ' to have shape ' +
136 str(shape) + ' but got array with shape ' +
--> 137 str(data_shape))
138 return data
139
ValueError: Error when checking target: expected dense_6 to have shape (46,) but got array with shape (1,)
【问题讨论】:
如果答案解决了您的问题,请接受点击答案旁边的复选标记将其标记为“已回答” - 请参阅What should I do when someone answers my question? 【参考方案1】:您需要使用keras.utils.to_categorical()
对标签(即y
)进行一次热编码,或者您可以使用'sparse_categorical_crossentropy'
作为损失函数以使其适用于稀疏标签。
【讨论】:
以上是关于ValueError:检查目标时出错:预期dense_6的形状为(46,),但数组的形状为(1,)的主要内容,如果未能解决你的问题,请参考以下文章
ValueError:检查目标时出错:预期activation_6 的形状为(70,)但得到的数组形状为(71,)
ValueError:检查目标时出错:预期dense_4的形状为(4,)但得到的数组形状为(1,)
ValueError:检查目标时出错:预期dense_3的形状为(1,)但得到的数组形状为(2,)
ValueError:检查目标时出错:预期activation_6具有形状(无,2)但得到的数组具有形状(5760,1)
ValueError:检查目标时出错:预期 activation_17 具有 2 维,但得到的数组形状为 (1, 256, 256, 3)
ValueError:检查目标时出错:预期 main_prediction 有 3 个维度,但得到了形状为 (1128, 1) 的数组