猫狗训练图片各1000张,验证图片各500张,测试图片各500张。
快速开发基准模型:面对一个任务,通常需要快速验证想法,并不断迭代。因此开发基准模型通常需要快速,模型能跑起来。
model.summary()输出模型各层的参数状况
训练结果如下图所示,很明显模型上来就过拟合了,主要原因是数据不够,或者说相对于数据量,模型过复杂(训练损失在第30个epoch就降为0了)。
为了解决过拟合问题,可以减小模型复杂度,也可以用一系列手段去对冲,比如增加数据(图像增强、人工合成或者多搜集真实数据)、L1/L2正则化、dropout正则化等。这里主要介绍CV中最常用的图像增强。
datagen=ImageDataGenerator(rotation_range=40,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')#Thisismodulewithimagepreprocessingutilitiesfromkeras.preprocessingimportimagefnames=[os.path.join(train_cats_dir,fname)forfnameinos.listdir(train_cats_dir)]#Wepickoneimageto"augment"img_path=fnames[3]#Readtheimageandresizeitimg=image.load_img(img_path,target_size=(150,150))#ConvertittoaNumpyarraywithshape(150,150,3)x=image.img_to_array(img)#Reshapeitto(1,150,150,3)x=x.reshape((1,)+x.shape)#The.flow()commandbelowgeneratesbatchesofrandomlytransformedimages.#Itwillloopindefinitely,soweneedto`break`theloopatsomepoint!i=0forbatchindatagen.flow(x,batch_size=1):plt.figure(i)imgplot=plt.imshow(image.array_to_img(batch[0]))i+=1ifi%4==0:breakplt.show()3.2模型调整
img_path='D:/python_project/kaggle_Dog&Cat/find_cats_and_dogs/test/cats/cat.1502.jpg'#Wepreprocesstheimageintoa4Dtensorfromkeras.preprocessingimportimageimportnumpyasnpimg=image.load_img(img_path,target_size=(150,150))img_tensor=image.img_to_array(img)img_tensor=np.expand_dims(img_tensor,axis=0)#Rememberthatthemodelwastrainedoninputs#thatwerepreprocessedinthefollowingway:img_tensor/=255.#Itsshapeis(1,150,150,3)print(img_tensor.shape)输入一张不属于网络的猫的图像
importmatplotlib.pyplotaspltplt.imshow(img_tensor[0])plt.show()为了提取想要查看的特征图,我们需要创建一个Keras模型,以图像批量作为输入,并输出所有卷积层和池化层的激活。为此,我们需要使用Keras的Model类。模型实例化需要两个参数:一个输入张量(或输入张量的列表)和一个输出张量(或输出张量的列表)。