概要
? ? ? ? 主要实现猫狗分类,使用tensorflow框架的keras实现,数据集下载地址:https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip或者百度网盘地址:https://pan.baidu.com/s/1pZarZHAlA57gv8-qK4W9hQ? 提取码:q1ql ,下载好的数据集是一个压缩包,不区分数据集和测试集,在代码中我们进行自定义区分。
代码
1.训练代码
import os
import zipfile
import random
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfile
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
local_zip = 'D:/tensorflowPoj/WEDTf/Q5/Q5inputdata.zip' #自己压缩包放的路径
zip_ref = zipfile.ZipFile(local_zip, 'r') #压缩包解压缩
zip_ref.extractall('D:/tensorflowPoj/WEDTf/Q5/Q5data') #将压缩包的内容全部放到自己指定的文件夹内,注意猫狗图片训练集和测试集没有分开,需要自己分
zip_ref.close()
print(len(os.listdir('D:/tensorflowPoj/WEDTf/Q5/Q5data/PetImages/Cat/'))) #打印猫狗图片张数
print(len(os.listdir('D:/tensorflowPoj/WEDTf/Q5/Q5data/PetImages/Dog/')))
#分别创建猫狗训练集和测试集文件目录,以便接下来训练和测试
try:
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs')
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining')
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing')
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/cats')
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/dogs')
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/cats')
os.mkdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/dogs')
except OSError:
pass
#分割数据集
def split_data(source,trining,testing,split_size):
files=[]
for filename in os.listdir(source): #遍历source路径下的所有文件和文件夹(也就是猫狗图片)
file=source+filename #图片的详细路径(文件夹路径+图片名称)
if os.path.getsize(file) > 0 : #判断该路径下是否存在图片(有的路径下没有图片,就不用添加到训练和测试集中)
files.append(filename)
else :
print(filename+",is zeros length")
trining_length=int(len(files)*split_size) #训练集长度为总长度乘以分割的长度(下面采用split_size=0.9,也就是90%的数据为训练集,10%为测试集)
testing_length=int(len(files)-trining_length) #测试集为10%
shuffled_set=random.sample(files,len(files)) #对files数组打乱顺序
trining_set=shuffled_set[0:trining_length] #训练集图片
testing_set=shuffled_set[-testing_length:] #测试集图片
for filename in trining_set: #把猫狗训练集的数据放到创建的训练集文件夹内
this_flie=source+filename #训练集图片原路径
destination=trining+filename #创建的训练集图片存放的目录
copyfile(this_flie,destination) #将训练集图片复制到创建好的目录下
for filename in testing_set: #把猫狗测试集的数据放到创建的测试集文件夹内
this_flie = source + filename
destination = testing + filename
copyfile(this_flie, destination)
cat_source_dir='D:/tensorflowPoj/WEDTf/Q5/Q5data/PetImages/Cat/' #原所有猫图片路径
trining_cats_dir='D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/cats/' #猫训练集要放的位置
testing_cats_dir='D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/cats/' #猫测试集要放的位置
dog_source_dir='D:/tensorflowPoj/WEDTf/Q5/Q5data/PetImages/Dog/'
trining_dogs_dir='D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/dogs/'
testing_dogs_dir='D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/dogs/'
split_size=0.9
split_data(cat_source_dir,trining_cats_dir,testing_cats_dir,split_size) #分割训练集和测试集
split_data(dog_source_dir,trining_dogs_dir,testing_dogs_dir,split_size)
print(len(os.listdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/cats/')))
print(len(os.listdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/cats/')))
print(len(os.listdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/dogs/')))
print(len(os.listdir('D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/dogs/')))
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(150, 150, 3)), #第一层卷积,卷积核大小(3,3)卷积核个数16,激活函数relu
tf.keras.layers.MaxPooling2D(2, 2), #第一层池化
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc']) #选取优化器和损失函数,显示准确率
TRAINING_DIR ='D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/trining/'
train_datagen =ImageDataGenerator(rescale=1.0/255)
train_generator = train_datagen.flow_from_directory(
TRAINING_DIR,
batch_size=100,
class_mode='binary',
target_size=(150,150)
)
VALIDATION_DIR = 'D:/tensorflowPoj/WEDTf/Q5/cats-v-dogs/testing/'
validation_datagen =ImageDataGenerator(rescale=1.0/255)
validation_generator = train_generator = train_datagen.flow_from_directory(
VALIDATION_DIR,
batch_size=100,
class_mode='binary',
target_size=(150,150)
)
history = model.fit_generator(train_generator,
epochs=15,
verbose=1,
validation_data=validation_generator)
acc=history.history['acc']
val_acc=history.history['val_acc']
loss=history.history['loss']
val_loss=history.history['val_loss']
epochs=range(len(acc)) # Get number of epochs
plt.plot(epochs, acc, 'r', "Training Accuracy")
plt.plot(epochs, val_acc, 'b', "Validation Accuracy")
plt.title('Training and validation accuracy')
plt.figure()
plt.plot(epochs, loss, 'r', "Training Loss")
plt.plot(epochs, val_loss, 'b', "Validation Loss")
plt.title('Training and validation loss')
model.save('Q5model')
2.测试代码(可以自己从网上下载猫狗图片进行测试)
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras.optimizers import RMSprop
import os
import zipfile
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
def image_plot(img): #绘制图片
plt.subplot()
plt.axis('off')
plt.imshow(img)
plt.show()
model=load_model('Q5model')
path = r"D:/tensorflowPoj/WEDTf/Q5/Q5testpictures/"
for im in os.listdir(path):
file=path+im
img = image.load_img(file, target_size=(150,150))
image_plot(img)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict(images, batch_size=10)
print(classes)
if classes>0.5:
print('这是一条狗!')
else :
print('这是一只猫!')
?
|