首先,将猫狗数据集转化为数组形式 ,使用train_test_split将数据集划分为训练集和数据集,使用fit进行训练
#-*-coding:utf-8-*-
import keras
from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation
import sklearn
# import sklearn.model_selection.train_test_split
from sklearn.model_selection import train_test_split
from PIL import Image
import os
import numpy as np
from VGG16 import VGG16
num_classes = 2
fileName = os.listdir("train")
total_train = []
labels = []
for name in fileName:
image = Image.open(os.path.join("train",name))
image = image.resize((224,224))
image_matrix = np.asarray(image)
# print(image_matrix.shape)
# print(len(total_train))
label = name.split(".")[0]
if label == "dog":
labels.append(0)
elif label == "cat":
labels.append(1)
else:
print("标签解析出错,退出")
break
total_train.append(image_matrix)
total_train = np.array(total_train)
labels = np.array(labels)
print("total_train shape:",total_train.shape)
print("labels shape:",labels.shape)
X_train, X_test, Y_train, Y_test = train_test_split(total_train, labels, test_size=0.30, random_state=42,shuffle=True)
X_train = np.array(X_train)
X_test = np.array(X_test)
X_train = np.array(X_train)
Y_test = np.array(Y_test)
print("X_train=", X_train.shape)
print("X_test=", X_test.shape)
print("Y_train=",Y_train.shape)
print("Y_test=",Y_test.shape)
Y_train = keras.utils.to_categorical(Y_train, num_classes)
Y_test = keras.utils.to_categorical(Y_test, num_classes)
model = VGG16(2)
model.compile(optimizer="Adam",loss="binary_crossentropy",metrics=['accuracy'])
model.fit(X_train,Y_train,epochs=10,batch_size=32)
print("测试结果为:")
score = model.evaluate(X_test,Y_test,batch_size=32)
print("Test loss ",score[0])
print("Test accuracy ",score[1])
这是VGG定义的网络
import tensorflow as tf
from tensorflow import keras
from keras import Model,Sequential
from keras.layers import Flatten, Dense, Conv2D, GlobalAveragePooling2D
from keras.layers import Input, MaxPooling2D, GlobalMaxPooling2D
def VGG16(num_classes):
image_input = Input(shape = (224,224,3))
# 第一个卷积部分
x = Conv2D(64,(3,3),activation = 'relu',padding = 'same',name = 'block1_conv1')(image_input)
x = Conv2D(64,(3,3),activation = 'relu',padding = 'same', name = 'block1_conv2')(x)
x = MaxPooling2D((2,2), strides = (2,2), name = 'block1_pool')(x)
# 第二个卷积部分
x = Conv2D(128,(3,3),activation = 'relu',padding = 'same',name = 'block2_conv1')(x)
x = Conv2D(128,(3,3),activation = 'relu',padding = 'same',name = 'block2_conv2')(x)
x = MaxPooling2D((2,2),strides = (2,2),name = 'block2_pool')(x)
# 第三个卷积部分
x = Conv2D(256,(3,3),activation = 'relu',padding = 'same',name = 'block3_conv1')(x)
x = Conv2D(256,(3,3),activation = 'relu',padding = 'same',name = 'block3_conv2')(x)
x = Conv2D(256,(3,3),activation = 'relu',padding = 'same',name = 'block3_conv3')(x)
x = MaxPooling2D((2,2),strides = (2,2),name = 'block3_pool')(x)
# 第四个卷积部分
x = Conv2D(512,(3,3),activation = 'relu',padding = 'same', name = 'block4_conv1')(x)
x = Conv2D(512,(3,3),activation = 'relu',padding = 'same', name = 'block4_conv2')(x)
x = Conv2D(512,(3,3),activation = 'relu',padding = 'same', name = 'block4_conv3')(x)
x = MaxPooling2D((2,2),strides = (2,2),name = 'block4_pool')(x)
# 第五个卷积部分
x = Conv2D(512,(3,3),activation = 'relu',padding = 'same', name = 'block5_conv1')(x)
x = Conv2D(512,(3,3),activation = 'relu',padding = 'same', name = 'block5_conv2')(x)
x = Conv2D(512,(3,3),activation = 'relu',padding = 'same', name = 'block5_conv3')(x)
x = MaxPooling2D((2,2),strides = (2,2),name = 'block5_pool')(x)
# 分类部分
x = Conv2D(256,(7,7),activation = 'relu',padding = 'valid', name = 'block6_conv4')(x)
x = Flatten(name = 'flatten')(x)
x = Dense(256,activation = 'relu',name = 'fullc1')(x)
x = Dense(256,activation = 'relu',name = 'fullc2')(x)
x = Dense(num_classes,activation = 'softmax',name = 'fullc3')(x)
model = Model(image_input,x,name = 'vgg16')
return model