我对CNN完全陌生,我创建了用于图像识别的CNN。我正在尝试根据我的锻炼适应猫对狗的结构,但是弹出了一个错误,而且我不知道如何解决它:
这是我的代码:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
img_width, img_height = 64, 64
img_rows, img_cols = 64, 64
# Prepare data to feed the NN
num_classes = 2
# Ask keras which format to use depending on used backend and arrange data as expected
if K.image_data_format() == 'channels_first':
X_train = x_train.reshape(X_train.shape[0], 3, img_rows, img_cols)
X_test = x_test.reshape(X_test.shape[0], 3, img_rows, img_cols)
input_shape = (3, img_width, img_height)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 3)
input_shape = (img_width, img_height, 3)
# Incoming data is in uint8. Cast the input data images to be floats in range [0.0-1.0]
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255
print('x_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
img_width, img_height = 64, 64
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
batch_size = 100
epochs = 10
model.fit(X_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(X_test, y_test))
错误:
ValueError:登录件和标签必须具有相同的形状((无,1)与(无,2,2))
非常感谢您:)
答案 0 :(得分:0)
您应该删除对标签一键编码的行。
在此行:
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
您已经对值进行了一次热编码,使其形状变为(batch_size, 2, 2)
,但是最后一层(密集)输出一个数字,即形状为(batch_size, 1)
。此外,binary_crossentropy
将Logit形状的损失计算为(batch_size, 1)
,标签的损失计算为(batch_size, 1)
(对于数据集)。