ValueError:检查目标时出错:预期fc1000的形状为(30,),但数组的形状为(1,)

时间:2018-07-23 14:06:24

标签: python-3.x keras deep-learning conv-neural-network

我正尝试重新训练ResNet50模型,以将给定的动物图像分类为30个不同的类别。为此,我制作了一个包含给定尺寸的图像数组的列表(在扩展尺寸并对其进行预处理之后):-(1、224、224、3),因此给定列表的形状(将其转换为numpy数组后)为(300、1、224、224、3),因为最初我只拍摄了300张图像。对于Ytrain,I Label对类进行编码,然后对它们进行热编码。对于30个课程,我有一个numpy维度数组(300,30)。然后我将DataGenerator用于model.fit_generator,传递了形状为(1,2,224,224,3)的Xtrain和形状为(30,)的Ytrain,但是得到了错误:-

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

这是我的代码:-

inputShape = (224, 224)
preprocess = imagenet_utils.preprocess_input

df = pd.read_csv('DLBeginner/meta-data/train.csv')
df = df.head(300)
imagesData, target = [], []
c = 0

for images in df['Image_id']:
filename = args["target"] + '/' + images
image = load_img(filename, target_size = inputShape)
image = img_to_array(image)
image = np.expand_dims(image, axis = 0)
image = preprocess(image)
imagesData.append(image)
c += 1
print('Count = {}, Image > {} '.format(c, images))

imagesData = np.array(imagesData)
labelEncoder = LabelEncoder()
series = df['Animal'][0:300]
integerEncoded = labelEncoder.fit_transform(series)
Hot = OneHotEncoder(sparse = False)
integerEncoded = integerEncoded.reshape(len(integerEncoded), 1)
oneHot = Hot.fit_transform(integerEncoded)

model = ResNet50(include_top = True, classes = 30, weights = None)

model.compile(optimizer = 'Adam', loss='categorical_crossentropy', metrics = ['accuracy'])

l = len(imagesData)
def DataGenerator(Xtrain, Ytrain):
while(True):
    for i in range(l):
        arr1 = Xtrain[i]
        arr2 = Ytrain[i]
        print("arr1.shape : {}".format(arr1.shape))
        print("arr2.shape : {}".format(arr2.shape))
        yield(arr1, arr2)

这是“配件”

generator = DataGenerator(imagesData, oneHot)

model.fit_generator(generator = generator, epochs = 5, steps_per_epoch=l)

我要去哪里错了? 预先感谢。

2 个答案:

答案 0 :(得分:1)

'categorical_crossentropy'切换为'sparse_categorical_crossentropy'可以为我解决。

答案 1 :(得分:0)

只想添加更多细节。

当您遇到多类分类问题并且 (1)如果您的目标是一次热编码,则使用categorical_crossentropy (2)如果目标是整数,如MNIST示例所示,请使用sparse_categorical_crossentropy。当您在后台使用Tensorflow时,它将把数据转换为一键编码并对其进行分类。

希望有帮助。谢谢!