我第一次使用卷积神经网络进行车辆识别。目前,我只参加2个课程(自行车和汽车)。训练集:420张汽车图像和825张自行车图像。测试集:44张汽车图像和110张自行车图像汽车和自行车图像的格式不同(bmp,jpg)。在单一预测中,我总是会遇到“自行车”。我尝试在输出层中使用Sigmoid函数。然后我只得到“汽车”。我的代码如下:``
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense,Dropout
classifier = Sequential()
classifier.add(Conv2D(32, (3, 3), input_shape = (128, 128, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (3, 3)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (3, 3)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dropout(0.3))
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
rotation_range= 3,
fill_mode = 'nearest',
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
rotation_range= 3,
fill_mode = 'nearest',
horizontal_flip = True)
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size = (128, 128),
batch_size = 10,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size = (128, 128),
batch_size = 10,
class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 1092//10,
epochs = 3,
validation_data = test_set,
validation_steps = 20)
classifier.save("car_bike.h5")
我想测试一个图像,如下所示:
test_image = image.load_img('dataset/single_prediction/download (3).jpg', target_size = (128, 128))
test_image = image.img_to_array(test_image)
test_image *= (1/255.0)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
if result[0][0] == 1:
prediction = 'bike'
else:
prediction = 'car'
print(" {}".format(prediction))
答案 0 :(得分:0)
如果打印result
矩阵,您会发现它不仅只有1和0,而且在这些数字之间浮动。您可以选择一个阈值并将超出该阈值的值设置为1,其他所有值都设置为0。