《Tensorflow20学习(七)-猫狗大战2、训练与保存模型.docx》由会员分享,可在线阅读,更多相关《Tensorflow20学习(七)-猫狗大战2、训练与保存模型.docx(4页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、Tensorflow2.0学习(七):猫狗大战2、训练与保存模型modelpile(optimizertf.keras.optimizers.Adam(lrlearning_rate),losstf.keras.losses.SparseCategoricalCrossentropy(),metricsaccuracy)print(model.summary()model.fit(train_dataset,epochs5,validation_datatest_dataset,shuffleTrue,steps_per_epoch1000,validation_steps1)model.sa
2、ve(./resnet.h5)3.2、利用tf.GradientTape()梯度带,保存模型.版权提示:参考github大神制作,我只是搬运工优点:动态图模型,随时可以保存模型.缺点:训练速度慢,代码复杂.完好代码如下:total_num25000#参数设置learning_rate0.001test_step1000saved_step5000EPOCHS10batch_size16display_step10training_stepint(total_num/batch_size)train_record_path./train.recordtest_record_path./test.
3、record#调用后我们会得到一个Dataset(tf.data.Dataset)字面理解这里面就存放着我们之前写入的所有Example。train_datasettf.data.TFRecordDataset(train_record_path)test_datasettf.data.TFRecordDataset(test_record_path)#定义一个解析函数feature_descriptionimage/filename:tf.io.FixedLenFeature(,tf.string),image/class:tf.io.FixedLenFeature(,tf.int64),i
4、mage/encoded:tf.io.FixedLenFeature(,tf.string)defparese_example(serialized_example):feature_dicttf.io.parse_single_example(serialized_example,feature_description)imagetf.io.decode_jpeg(feature_dictimage/encoded)#解码JPEG图片imagetf.image.resize_with_crop_or_pad(image,224,224)imagetf.reshape(image,224,22
5、4,3)imagetf.cast(image,tf.float32)feature_dictimageimagereturnfeature_dictimage,feature_dictimage/classtrain_datasettrain_dataset.map(parese_example)test_datasettest_dataset.map(parese_example)train_datasettrain_dataset.repeat().shuffle(5000).batch(batch_size).prefetch(3)test_datasettest_dataset.rep
6、eat().shuffle(5000).batch(batch_size,drop_remainderTrue)ResNet50tf.keras.applications.ResNet50(weightsNone,include_topFalse)global_average_layertf.keras.layers.GlobalAveragePooling2D()fctf.keras.layers.Dense(2,activationsoftmax)modeltf.keras.Sequential(ResNet50,global_average_layer,fc)#Chooseanoptim
7、izerandlossfunctionfortrainingloss_objecttf.keras.losses.SparseCategoricalCrossentropy()#Selectmetricstomeasurethelossandtheaccuracyofthemodeltrain_losstf.keras.metrics.Mean(nametrain_loss)train_accuracytf.keras.metrics.SparseCategoricalAccuracy(nametrain_accuracy)test_losstf.keras.metrics.Mean(name
8、test_loss)test_accuracytf.keras.metrics.SparseCategoricalAccuracy(nametest_accuracy)optimizertf.keras.optimizers.Adam(0.001)deftrain_step(images,labels):withtf.GradientTape()astape:predictionsmodel(images,trainingTrue)#print(labelshape:,labels.shape,predshape,predictions.shape)lossloss_object(labels
9、,predictions)gradientstape.gradient(loss,model.trainable_variables)optimizer.apply_gradients(zip(gradients,model.trainable_variables)train_loss(loss)train_accuracy(labels,predictions)print(train.)deftest_step(images,labels):predictionsmodel(images)t_lossloss_object(labels,predictions)test_loss(t_los
10、s)test_accuracy(labels,predictions)forepochinrange(EPOCHS):forstep,(batch_x,batch_y)inenumerate(train_dataset,1):train_step(batch_x,batch_y)if(step%display_step0):templatetrain:step,Loss:.4,Accuracy:.2%print(template.format(step1,train_loss.result(),train_accuracy.result(),forstep,(batch_x,batch_y)i
11、nenumerate(test_dataset,1):test_step(batch_x,batch_y)templateEpoch,TestLoss:.4,TestAccuracy:.2%print(template.format(epoch1,test_loss.result(),test_accuracy.result()roottf.train.Checkpoint(optimizeroptimizer,modelmodel)saved_folder./ckpt2Modelif(notos.path.exists(saved_folder):os.mkdir(saved_folder)checkpoint_prefix(saved_folder/epoch:%i_acc)%(epoch1)root.save(checkpoint_prefix)四、预测一张图像并输出概率值得到模型后那么下一步自然先测一张图像验证一下毕竟这是最直观的感受。#!/usr/bin/envpython3#-*-coding:utf-8-*-*File:DogVsCat/inference_one_img.pyDate:2020/12/4下午6:06Require:Author:hjxu2016s:/
限制150内