老司机怎么能不会立FLAG呢·
- 如何利用FLAG设置参数(包括超参数和一些路径设置),详细语法介绍见代码注释
- 利用name_scope管理变量
** 1. 方便查看tensorboard,比上一讲的清晰多啦
**
** 2.方便。。
**
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 3 19:15:24 2017
@author: Jhy_BUPT
README:
REF:
"""
import tensorflow as tf
# 载入数据
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("C:\\tmp\\data", one_hot=True)
# 老司机立下FLAGS
FLAGS = tf.app.flags.FLAGS
# 根据参数类型不同,可以定义字符串DEFINE_string,可以定义整数DEFINE_integer
#DEFINE_integer('参数名称', 参数值, '参数的解释')
tf.app.flags.DEFINE_integer('batch_size', 100, 'batch size')
tf.app.flags.DEFINE_float('learning_rate', 0.1, 'l;earning rate')
tf.app.flags.DEFINE_integer('epoch', 1000, 'how many epoch tf will run')
tf.app.flags.DEFINE_string('ckp_dir', 'C:\\tmp\\d44', 'where to save tensorboard')
with tf.name_scope('input'):
x = tf.placeholder(tf.float32, [None, 784], name='x_input')
y_ = tf.placeholder(tf.float32, [None, 10], name='y_input')
with tf.name_scope('nn'):
with tf.name_scope('weight'):
W = tf.Variable(tf.zeros([784, 10]))
with tf.name_scope('bias'):
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
with tf.name_scope('loss'):
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
with tf.name_scope('trian'):
train_step = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cross_entropy)
# 开启会话
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for _ in range(FLAGS.epoch):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)
fd = {x: batch_xs, y_: batch_ys}
sess.run(train_step, feed_dict=fd)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
fd2 = {x: mnist.test.images, y_: mnist.test.labels}
print(sess.run(accuracy, feed_dict=fd2))
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.ckp_dir, sess.graph)