ValueError:检查目标时出错:期望dense_20有2个维度

时间:2018-02-14 20:08:59

标签: python tensorflow keras

我想在Keras中运行以下代码。它使用TensorFlow作为后端测试文件将图像分为7个类。测试文件有7个jpg图像,训练文件有21个图像。每张图像为227 X 227 X 3.模型给出了下面列出的错误。

任何人都可以建议如何解决这个问题?

X_train=X_train
y_train= y_train

(x_train, y_train)=(X_train, y_train)
(x_test, y_test)=(iX_test, iY_test) 

print('x_train shape:', X_train.shape)
#print(x_train.shape[0], 'train samples')
print( X_train.shape[0], 'test samples')


X_train = X_train.astype('float32')
X_test = iX_test.astype('float32')
X_train = X_train / 255.0
X_test = iX_test / 255.0


y_train=np.array(y_train)
y_test=np.array(y_test)

y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
y_train=np.array(y_train)
y_test=np.array(y_test)


**model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(227, 227, 3), padding='same', activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Conv2D(32, (3, 3), activation='relu', padding='same', kernel_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
print(model.summary())


model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=21)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))**

错误:

ValueError: Error when checking target: expected dense_20 to have 2 dimensions, but got array with shape (21, 7, 2, 2, 2, 2, 2, 2)

1 个答案:

答案 0 :(得分:0)

你应该检查y_train的形状。显然它有太多的维度。请说明您如何获取数据以获得进一步的帮助。