使用Keras做猫狗二分类

使用Keras做猫狗二分类

训练模型:

import tensorflow as tf
import keras
from keras import layers
import sys
from matplotlib import pyplot
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D,Conv1D
from keras.layers import MaxPool2D
from keras.layers import  Dense
from keras.layers import Flatten
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import plot_model
from keras.models import load_model

tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

#建立一个CNN模型
def define_cnn_model():
    #使用序列模型
    model=Sequential()
    #卷积层
    model.add(Conv2D(32,(3,3),activation='relu',padding='same',input_shape=(200,200,3)))

    #最大池化层
    model.add(MaxPool2D((2,2)))
    #Flatten层
    model.add(Flatten())
    #全连接层
    model.add(Dense(128,activation='relu'))
    model.add(Dense(1,activation='sigmoid'))

    #编译模型
    opt=SGD(lr=0.001,momentum=0.9)
    model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['accuracy'])

    return model

'''model=define_cnn_model()
plot_model(model,
           to_file='cnn_model.png',
           dpi=100,
           show_shapes=True,
           show_layer_names=True
           )
'''
def train_cnn_model():
    #实例化模型
    model=define_cnn_model()
    datagen=ImageDataGenerator(rescale=1.0/255.0)
    train_it=datagen.flow_from_directory('E:\大三下\dogs-vs-cats\My_train',class_mode='binary',batch_size=64,target_size=(200,200))

    #训练模型
    model.fit(train_it,steps_per_epoch=len(train_it),epochs=1,verbose=1)
    model.save('E:\大三下\dogs-vs-cats\my_model.h5')

if __name__ =="__main__":
    train_cnn_model()
    print("模型训练成功!")

测试模型:

from keras.models import load_model
import os,random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from keras.preprocessing import image



#随机读取测试图片
def read_random_image():
    folder=r"E:\大三下\dogs-vs-cats\My_test\\"
    file_path=folder+random.choice(os.listdir(folder))
    pil_im=Image.open(file_path,'r')
    return pil_im


def get_predict(pil_im,model):
    #对图片进行缩放
    pil_im=pil_im.resize((200,200))
    #将格式转为numpy array 格式
    #array_im=np.asarray(pil_im)
    #对图片进行预测
    pil_im = image.img_to_array(pil_im)
    pil_im = np.expand_dims(pil_im, axis=0)
    result=model.predict(pil_im)
    if result[0][0]>0.5:
        print("预测结果为:狗")
    else:
        print("预测结果为:猫")

if __name__ =="__main__":
    # 载入模型
    model = load_model('E:\大三下\dogs-vs-cats\my_model.h5')
    #随机读取测试图片
    pil_im=read_random_image()
    #显示图片
    plt.imshow(np.asarray(pil_im))
    plt.show()
    #预测图片
    get_predict(pil_im,model)


代码、图片、模型下载

你可能感兴趣的:(人工智能,深度学习,tensorflow)