在上一篇博客中,已经完成了tf.record数据集的制作,接下来开始训练。可以选择重头开始训练,也可以加载预训练模型再继续训练。大部分情况下,使用预训练模型会比直接重头训练效果要好。直接上代码~
import tensorflow as tf
import numpy as np
import pdb
import os
from datetime import datetime
import resnet_v2 as resnet_v2
from create_records import *
import tensorflow.contrib.slim as slim
from tensorflow.python import pywrap_tensorflow
#print("Tensorflow version:{}".format(tf.__version__))
labels_nums = 3 # 类别个数
batch_size = 16 #
resize_height = 224 # 指定存储图片高度,原先是299
resize_width = 224 # 指定存储图片宽度
depths = 3
data_shape = [batch_size, resize_height, resize_width, depths]
input_images = tf.placeholder(dtype=tf.float32, shape=[None, resize_height, resize_width, depths], name='input')
input_labels = tf.placeholder(dtype=tf.int32, shape=[None, labels_nums], name='label')
keep_prob = tf.placeholder(tf.float32,name='keep_prob')
is_training = tf.placeholder(tf.bool, name='is_training')
def net_evaluation(sess,loss,accuracy,val_images_batch,val_labels_batch,val_nums):
val_max_steps = int(val_nums / batch_size)
val_losses = []
val_accs = []
for _ in range(val_max_steps):
val_x, val_y = sess.run([val_images_batch, val_labels_batch])
val_loss,val_acc = sess.run([loss,accuracy], feed_dict={input_images: val_x, input_labels: val_y, keep_prob:1.0, is_training: False})
val_losses.append(val_loss)
val_accs.append(val_acc)
mean_loss = np.array(val_losses, dtype=np.float32).mean()
mean_acc = np.array(val_accs, dtype=np.float32).mean()
return mean_loss, mean_acc
def step_train(train_op,loss,accuracy,train_images_batch,train_labels_batch,