有一段时间了,因为我做了任何神经网络。我正在编写一个简单的示例作为热身,并对为什么我的张量没有正确成形感到困惑。我认为模型是预期的(样本,高度,宽度,通道)。
当我打电话
X_train.shape
我得到(784,100,100,3)
但是我得到一个错误:ValueError:检查目标时出错:预期density_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
i然后重塑为:
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
答案 0 :(得分:1)
我的猜测是批量大小冲突。就您共享的代码片段而言,它应该可以正常工作。
但是X_train.shape
给我们的输出元组为(784,100,100,3)。在这种情况下,我会将输入初始化为类似这样的内容:
model_input = Input(shape=(X_train.shape[0], img_rows, img_cols,img_channels))
注意:如果要进行可变批处理大小,请使用无初始化初始化输入,并在训练时动态设置值。干杯!
答案 1 :(得分:0)
y_train=np_utils.to_categorical(y_train, n_class)
y_test=np_utils.to_categorical(y_test, n_class)