ValueError:检查目标时出错:ConvLSTM2D分类

时间:2019-01-28 10:52:03

标签: tensorflow keras deep-learning

我有3通道图像(11 * 11像素),每小时拍摄7个小时,可拍摄99个对象。 对象是(苹果,香蕉或胡萝卜)。 我必须将这99个样本图像分为3类(0,1,2)。

np.random.seed(0)
data = np.random.randint(low=1,high=9,size=(99, 7, 11, 11, 3))
#(samples, timeshifts, heigt, width, nchannels)
print (data.shape)
#(99, 7, 11, 11, 3)

labels = np.random.randint(low=0,high=3,size=(99)) #(samples)
print (labels.shape)
#(99,)

classes = np.unique(labels)
print (classes)
#(0,1,2)


X_train, X_test, Y_train, Y_test = train_test_split(data,labels,test_size=0.30,random_state=0)

print ('X_train', X_train.shape)
print ('X_test', X_test.shape)
print ('Y_train', Y_train.shape)
print ('Y_test', Y_test.shape)


##X_train (69, 7, 11, 11, 3)
##X_test (30, 7, 11, 11, 3)
##Y_train (69,)
##Y_test (30,)


Y_train_ = to_categorical(Y_train) 
print ('Y_train_categorical', Y_train_.shape)

##Y_train_categorical (69, 2)

input_shape = (X_train.shape[1], X_train.shape[2], X_train.shape[3], X_train.shape[4])
print ('input_shape', input_shape)

##input_shape (7, 11, 11, 3)

model = Sequential()
model.add(ConvLSTM2D(16, kernel_size=(3,3), activation='sigmoid',padding='same',input_shape=input_shape,
                     return_sequences=True))
model.add(ConvLSTM2D(16, kernel_size=(3,3), activation='sigmoid',padding='same'))
model.add(Dense(len(classes), activation='softmax'))
model.summary()

model.compile(loss='categorical_crossentropy', optimizer='adam')

model.fit(X_train, Y_train_, epochs=10, verbose=10, batch_size=32)

但是,我遇到了以下错误:

Traceback (most recent call last):
  File "D:\tests\ConvLSTM2D.py", line 60, in <module>
    model.fit(X_train, Y_train_, epochs=10, verbose=10, batch_size=32)
  File "C:\Program Files\Python36\lib\site-packages\keras\engine\training.py", line 952, in fit
    batch_size=batch_size)
  File "C:\Program Files\Python36\lib\site-packages\keras\engine\training.py", line 789, in _standardize_user_data
    exception_prefix='target')
  File "C:\Program Files\Python36\lib\site-packages\keras\engine\training_utils.py", line 128, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking target: expected dense_1 to have 4 dimensions, but got array with shape (69, 2)

请帮助我的朋友...

1 个答案:

答案 0 :(得分:1)

最终Dense层的输出形状为(None, 11, 11, 2),但应为(None, 2)(即(batch_size, n_classes)),以便与标签兼容。一种解决方案是先将第二个ConvLSTM2D层的输出展平,然后再将其传递到最终的Dense层。

model = Sequential()
model.add(ConvLSTM2D(16, kernel_size=(3,3), activation='sigmoid',padding='same',input_shape=input_shape,
                     return_sequences=True))
model.add(ConvLSTM2D(16, kernel_size=(3,3), activation='sigmoid',padding='same'))
model.add(Flatten())
model.add(Dense(len(ctypes), activation='softmax'))
model.summary()

model.compile(loss='categorical_crossentropy', optimizer='adam')

model.fit(X_train, Y_train_, epochs=10, verbose=10, batch_size=32)