卷积神经网络CNN-猫狗预测

卷积:轮廓特征
池化:保留核心信息,实现降维缩减

from keras.preprocessing.image import ImageDataGenerator

#加载数据
train_datagen = ImageDataGenerator(rescale=1./255)
trainning_set = train_datagen.flow_from_directory("datas/dataset/training_set", target_size=(50, 50), 
                                                 batch_size=32, class_mode="binary")

from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense

#建立cnn模型
model = Sequential()
#卷积
model.add(Conv2D(32, (3, 3), input_shape=(50, 50, 3), activation="relu"))
#池化
model.add(MaxPool2D(pool_size=(2, 2)))
#卷积
model.add(Conv2D(32, (3, 3), activation="relu"))
#池化
model.add(MaxPool2D(pool_size=(2, 2)))
#展开
model.add(Flatten())
#全连接层
model.add(Dense(units=128, activation="relu"))
model.add(Dense(units=1, activation="sigmoid"))

#配置模型
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

#模型训练
model.fit_generator(trainning_set, epochs=25)

# 训练数据准确率
model.evaluate_generator(trainning_set)    #1.0

#测试数据准确率
test_set = train_datagen.flow_from_directory("datas/dataset/test_set", target_size=(50, 50), 
                                                 batch_size=32, class_mode="binary")
model.evaluate_generator(test_set)    #0.7620000243186951

#预测下载的图片
from keras.utils import load_img, img_to_array
pic_dog = load_img("datas/gg.jpg", target_size=(50, 50))
pic_dog = img_to_array(pic_dog)
pic_dog = pic_dog/255
pic_dog = pic_dog.reshape(1, 50, 50, 3)
model.predict(pic_dog)  #array([[1.]], dtype=float32)

trainning_set.class_indices  # {'cats': 0, 'dogs': 1}

你可能感兴趣的:(卷积神经网络CNN-猫狗预测)