import tensorflow as tf
import sys
import os,random
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import pyplot
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from keras.optimizers import SGD
from keras.models import load_model
from keras.utils import plot_model
from PIL import Image
from keras.preprocessing.image import ImageDataGenerator
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
#创建一个cnn模型
def cnn_model():
#使用序列模型
model=Sequential()
#卷积层
model.add(Conv2D(32,(3,3),activation="relu",padding="same",input_shape=(200,200,3)))
#最大池化层
model.add(MaxPooling2D((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=cnn_model()
# plot_model(model,to_file='cnn_model.png',dpi=100,show_shapes=True,show_layer_names=True)
def train_cnn_model():
#实例化模型
model=cnn_model()
#创建图片生成器
datagen=ImageDataGenerator(rescale=1.0/255.0)
train_it=datagen.flow_from_directory('./datasets/train1/',class_mode='binary',batch_size=64,target_size=(200,200))
#训练模型
model.fit_generator(train_it,steps_per_epoch=len(train_it),epochs=1,verbose=1)
def predict(pli_im,model):
pli_im=pli_im.resize((200,200))
array_im=np.asarray(pli_im)
array_im = array_im[np.newaxis,:]
result=model.predict([[array_im]])
if result[0][0]>0.5:
print("预测结果是狗")
else:
print("预测结果是猫")
model_path= "./datasets/dogs_cats/model/basic_cnn_model.h5"
model=load_model(model_path)
folder=r"./datasets/dogs_cats/data/test/"
file_path=folder+random.choice(os.listdir(folder))
pli_im=Image.open(file_path,'r')
imshow(np.asarray(pli_im))
predict(pli_im,model)
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/143107.html