创建CNN模型的卷积层时发生错误。 我不知道错误的原因以及如何处理。我正在使用keras和cifar10实施CNN以便通过Python 3.5进行机器学习。
在学习阶段出现以下错误:
检查目标时出错:预期density_46的形状为(10,),但数组的形状为(1,)
在重塑标签数组(y_train)时效果不佳。
#import
import tensorflow as tf
import keras
import numpy as np
import matplotlib.pyplot as plt
#get data
from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
#Image normalization
x_train = x_train / 255.0
x_test = x_test / 255.0
#Build a CNN mode
def CNN_model():
model = keras.models.Sequential()
#1st convolutional layer
model.add(keras.layers.Conv2D(96, 11, strides=(4, 4), padding='valid', data_format='channels_last', activation='relu', bias_initializer='ones', input_shape=(32,32,3)))
model.add(keras.layers.normalization.BatchNormalization(axis=1))
model.add(keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='valid', data_format='channels_last'))
#2nd convolutional layer
model.add(keras.layers.Conv2D(256, 2, strides=(4, 4), padding='valid', data_format='channels_last', activation='relu', bias_initializer='zeros'))
model.add(keras.layers.normalization.BatchNormalization(axis=1))
model.add(keras.layers.MaxPooling2D(pool_size=(1, 1), strides=(2, 2), padding='valid', data_format='channels_last'))
#3rd layer
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(4096))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Dense(4096))
model.add(keras.layers.Dropout(0.5))
#4th Softmax layer
model.add(keras.layers.Dense(10, activation='softmax'))
#compile
model.compile(optimizer=keras.optimizers.SGD(lr=0.01), loss='categorical_crossentropy', metrics=['accuracy'])
return model
#Summary
model = CNN_model()
model.summary()
#Fitting
early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, verbose=1, mode='auto')
history = model.fit(x_train, y_train, epochs=15, batch_size=128, shuffle=True, validation_split=0.25, callbacks=[early_stopping])
答案 0 :(得分:0)
问题出在你的目标y_train
。您的向量可能是一个1 x n_samples长的向量,其中包含10个不同的标签。Keras所需的方式是以“一键编码”方式进行的。您可以通过以下方式做到这一点:
y_train = to_categorical(y_train)
希望有帮助!