github在这里
另一方面,创建名为tensorflow的虚拟环境的conda create-ntensorflowpython=3.7我将其命名为tensorflow。 python版本为3.7,numpy版本为1.16
(通常下载的tensorflow是2.2或更高版本。)
【注】安装1.14版的tensorflow。 csdn的参考在这里。
导入tensorflow库并创建1 .新的py文件以下载和准备cifar数据
2 .在py文件的开头添加版权
# @ titlelicensedundertheapachelicense,版本2.0 (the ' license ); # youmaynotusethisfileexceptincompliancewiththelicense.# youmayobtainacopyofthelicenseat # # https://www.Apache.org/licenense unlessrequiredbyapplicablelaworagreedtoinwriting,软件# distributedunderthelicenseisdistributedonan ' # withoutwararantied eitherexpressorimplied.# seethelicenseforthespecificlanguagegoverningpermissionsand # limitationsunderthelicense.3 .部署ten specificlaguage
下载importtensorflowastffromtensorflow.kerasimportdatasets,layers,modelsimportmatplotlib.pyplotasplt4. cifa r10数据集
(train_images,train_labels (,test_images,test_labels )=datasets.cifar10.load_data ) # normaliz ATA ta test_images/255.0三.可视化前25张图像,数据集class_names=['airplane ',' automobile 'frog ',' horse ',' ship ',] 10 ) ) forIinrange ) 25 ) :PLT.subplot ) 5 i 1) PLT.xticks((PLT.yticks ) ) PLT.grid (false ) PLT.imshow ) tticks cmap=PLT.cm.bow # whichiswhyyouneedtheextraindexplt.xlabel (class _ names [ train _ labels [ I ] [0] ) ) plt.show
四.卷积基础model=models.sequential (model.add ) layers.conv2d ) 32,) 3,3 ),activation='relu ',input_shape
model.summary (四.所有连接层model.add ) layers.flatten ) (model.add ) layers.dense ) 64,activation='relu ' )
model.summary (四.培训模型model.compile ) optimizer='Adam ', loss=TF.keras.losses.sparsecategoricalcrossentropy metrics=[ ' accuracy ' ] (history=model.fit (train _ images ) test_labels ) )五.测试模型,测试PLT.plot (history.history [ ' accuracy ' ],label='accuracy ' ) PLT.plot ) history
结果
五、保存模型数据,重装模型保存keras模型
重新实例化model.save (/users/liuyi/desktop/cifa r10/cifa r10 _ data/my _ test _ model.ckpt ' )模型
# keras.models.load _ model (文件路径) )。
#or h5结构
from keras.modelsimportload _ model model.save (my _ model.H5 ) # createsahdf 5文件' my _ model.H5 ' del model # retur identicaltothepreviousonemodel=load _ model (my _ model.H5 )五.单张图像的预测I=3class_names='bird '、' cat '、' deer '途径' ] from keras.preprocessingimportimageimg=test _ images [ I ] x=image.img_to_array(img ) x=NP.Exppray axis=0) images=NP.vstack(x ) classes=model.predict(images )