【发布时间】:2019-11-15 19:59:07
【问题描述】:
自从我做任何神经网络以来已经有一段时间了。我正在编写一个简单的示例作为热身,我很困惑为什么我的张量形状不正确。我认为模型是预期的(样本、高度、宽度、通道)。
当我打电话时
X_train.shape
我得到 (784, 100, 100, 3)
但是我得到一个错误:ValueError:检查目标时出错:预期dense_10 的形状为(2,),但得到的数组的形状为(1,)
这是下面的简单模型。我哪里错了?需要转灰度吗?
#THE MODEL#
batch_size = 32
nb_classes = 2
nb_epoch = 2
img_rows =100
img_cols=100
img_channels = 3
model_input=Input(shape=(img_rows, img_cols,img_channels))
x = Convolution2D(32, 3, 3, border_mode='same')(model_input)
x = Activation('relu')(x)
x = Convolution2D(32, 3, 3)(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
conv_out = Flatten()(x)
x1 = Dense(nb_classes, activation='softmax')(conv_out)
lst = [x1]
#model = Model(input=model_input, output=lst)
model = Model(input=model_input, output=lst) #I learned you can't use a sequential model for this type of prediction
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, callbacks=[history],verbose=1)
在运行模型之前,我这样做了:
print('X_train shape:', X_train.shape)
print('y_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
给出这个输出:
X_train shape: (784, 1, 100, 100, 3)
y_train shape: (784, 1, 100, 100, 3)
784 train samples
196 test samples
然后我重新塑造成这样:
X_test = X_test.reshape(X_test.shape[0], 100,100, 3)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255 #normalize our data values to the range [0, 1], 255 is the max value of X_train.max()
X_test /= 255
然后我得到这个 X_train 的形状
(784, 100, 100, 3)
数据是来自 kaggle 的彩色水果图片:https://www.kaggle.com/moltean/fruits
【问题讨论】:
-
我运行该代码就好了,错误一定在其他地方。
-
可以确认这段代码运行正常。
标签: python tensorflow keras reshape