如何解决此错误?我尝试访问所有论坛以寻找答案来纠正此问题。 train_set和test_Set中有5个类。
from keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense
classifier=Sequential()
#1st Convolution Layer
classifier.add(Convolution2D(32, 3, 3, input_shape=(64,64,3),activation="relu"))
#Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Convolution2D(32, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Flattening
classifier.add(Flatten())
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 64, activation = 'relu'))
classifier.add(Dense(output_dim = 1, activation = 'softmax'))
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
print(classifier.summary())
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set= train_datagen.flow_from_directory('flowers/train_set',
target_size=(64,64),
batch_size=32,
class_mode='categorical')
test_set= test_datagen.flow_from_directory('flowers/test_set',
target_size=(64,64),
batch_size=32,
class_mode='categorical')
classifier.fit_generator(training_set,
samples_per_epoch = 3000,
nb_epoch = 25,
validation_data = test_set,
nb_val_samples=1000)
在此附上错误图片以供审核。 error
答案 0 :(得分:5)
在您的代码中,以下行是错误的
classifier.add(Dense(output_dim = 1, activation = 'softmax'))
将其更改为
classifier.add(Dense(output_dim = 5, activation = 'softmax'))
为什么?
这是因为,您的最后一层是5维的。我怎么知道输出尺寸是5?因为您使用了categorical_crossentropy
,而且数据集的标签看起来有5个类别(基于图像输出的第一行)