ValueError: Error when checking target: expected activation_7 to have shape (2,) but got array with

ValueError: Error when checking target: expected activation_7 to have shape (2,) but got array with shape (1,)

原贴:https://stackoverflow.com/questions/49392972/error-when-checking-target-expected-dense-3-to-have-shape-3-but-got-array-wi

感谢原贴并感谢:https://blog.csdn.net/jacke121/article/details/83039471

没有给类标签进行独热编码吧,哥们?独热一下就好了哦。。。。。。。shape这个东西真是太坑人。。。。

一、如果最终要区分的类只有两种:

# 举个栗子。。。。

from sklearn.preprocessing import LabelBinarizer
from keras.utils import to_categorical

labels = ['hei', 'bai', 'hei']
lb = LabelBinarizer()
labels = lb.fit_transform(labels) # transfer label to binary value
labels = to_categorical(labels) # transfer binary label to one-hot. IMPORTANT
print(labels)
print(labels.shape)

# 输出:
# Using TensorFlow backend.
# [[0. 1.]
#  [1. 0.]
#  [0. 1.]]
# (3, 2)

二、如果最终要区分的类有多种(两种以上):

from sklearn.preprocessing import LabelBinarizer

labels = ['hei', 'bai', 'hei', 'huang', 'lv', 'lan', 'zi']
lb = LabelBinarizer()
labels = lb.fit_transform(labels) # transfer label to binary value
print(labels)
print(labels.shape)

# 输出:
# [[0 1 0 0 0 0]
#  [1 0 0 0 0 0]
#  [0 1 0 0 0 0]
#  [0 0 1 0 0 0]
#  [0 0 0 0 1 0]
#  [0 0 0 1 0 0]
#  [0 0 0 0 0 1]]
# (7, 6)

三、分析原因:

# labels = to_categorical(labels) # transfer binary label to one-hot. IMPORTANT
# 最终要区分的类只有两种的时候,如果不加上面的这行代码,输出会变成下面这种:
# [[1]
# [0]
# [1]]
# (3, 1)

# 即只有一列内容,可能会报错。keras激活层可能需要维度为2

 

你可能感兴趣的:(学习笔记,#,DL-报错,Python)