任务:为图像分类创建一个cnn。 我正在为图像分类创建一个cnn。我想对我的硬币图像数据进行5类学习。
classifier = Sequential()
classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Convolution2D(32, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 5, activation = 'softmax'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
training_set = train_datagen.flow_from_directory('5 class/training',
target_size = (64, 64),
batch_size = 1,
class_mode = 'categorical')
test_set = test_datagen.flow_from_directory('5 class/test',
target_size = (64, 64),
batch_size = 1,
class_mode = 'categorical')
classifier.fit_generator(training_set,
samples_per_epoch = 8000,
nb_epoch = 1,
validation_data = test_set,
nb_val_samples = 2000)
我认为代码的这一部分没有错误,但是我认为应该将此代码放在这里。
import numpy as np
import pandas as pd
test_set.reset()
pred=classifier.predict_generator(test_set,verbose=1)
#pred = list(map(round,pred))
pred[pred > .5] = 1
pred[pred <= .5] = 0
test_labels = []
for i in range(0,int(203)):
test_labels.extend(np.array(test_set[i][1]))
print('test_labels')
print(test_labels)
file_names = test_set.filenames
result = pd.DataFrame()
result['file_names']= file_names
result['predictions'] = pred
result['test'] = test_labels
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(test_labels, pred)
print (cm)
运行上述代码时,出现类似“通过的项目数错误5,展示位置为1”之类的错误