前面是训练的代码,先在我们来看评估的代码,代码在cifar10_eval.py文件下:
首先:
if __name__ == '__main__':
tf.app.run()
是吧,就是进入main函数
然后,我们看main函数
def main(argv=None): # pylint: disable=unused-argument
cifar10.maybe_download_and_extract() #判断数据是否下载的
if tf.gfile.Exists(FLAGS.eval_dir): #评估的文件夹是否在哈
tf.gfile.DeleteRecursively(FLAGS.eval_dir)
tf.gfile.MakeDirs(FLAGS.eval_dir)
evaluate()
然后重点看 evaluate()
def evaluate():
"""Eval CIFAR-10 for a number of steps."""
with tf.Graph().as_default() as g: #创建一个g图(也是空白图)
# Get images and labels for CIFAR-10.
eval_data = FLAGS.eval_data == 'test'
images, labels = cifar10.inputs(eval_data=eval_data) #加载测试图像
# Build a Graph that computes the logits predictions from the
# inference model. 创建图和模型,并计算logits 预测
logits = cifar10.inference(images)
# Calculate predictions.
top_k_op = tf.nn.in_top_k(logits, labels, 1) #计算预测,返回的是0和1,0代表预测错误,1代表预测正确
# Restore the moving average version of the learned variables for eval.
variable_averages = tf.train.ExponentialMovingAverage(
cifar10.MOVING_AVERAGE_DECAY)
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
# Build the summary operation based on the TF collection of Summaries.
summary_op = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter(FLAGS.eval_dir, g)
while True:
eval_once(saver, summary_writer, top_k_op, summary_op)
if FLAGS.run_once:
break
time.sleep(FLAGS.eval_interval_secs)
附录:关于batch size 的理解:
参考:https://blog.csdn.net/ycheng_sjtu/article/details/49804041
在合理范围内,增大 Batch_Size 有何好处?
- 内存利用率提高了,大矩阵乘法的并行化效率提高。
- 跑完一次 epoch(全数据集)所需的迭代次数减少,对于相同数据量的处理速度进一步加快。
- 在一定范围内,一般来说 Batch_Size 越大,其确定的下降方向越准,引起训练震荡越小。
盲目增大 Batch_Size 有何坏处?
- 内存利用率提高了,但是内存容量可能撑不住了。
- 跑完一次 epoch(全数据集)所需的迭代次数减少,要想达到相同的精度,其所花费的时间大大增加了,从而对参数的修正也就显得更加缓慢。
- Batch_Size 增大到一定程度,其确定的下降方向已经基本不再变化。//加如使用极端,Batch_Size设置使用全部图像,那就梯度下降的方向永远不会变化,导致模型一只往一个方向走,容易陷入局部极值,本来我们训练的数据不一定全部够非常“干净”,或者数据量不一定能cover整个需要学习到的模式,如果使用适当较小的batch size,可以使得梯度还有多样化,比如数据不“干净”,但是干净的数据占大多数,走10步,1步后退,9步向前,整体向前。就像直线上开车,但路上有小石头,需要走在小石头的路上微调,曲线前进。但是如果,一开始将所有微调步骤和在一起,中间不再调整,得到一个最终的方向可以靠近终点,但是一般走不到终点的。