美文网首页
tf.app.flags

tf.app.flags

作者: yalesaleng | 来源:发表于2018-07-16 16:03 被阅读4次
    import tensorflow as tf
    from tensroflow.examples.tutorials.mnist import input_data
    
    mnist = input_data.read_data_sets('./MNIST_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_integer('epoch',20000,'how many epoch tf will run')
    tf.app.flags.DEFINE_float('learning_rate',0.1,'learning rate')
    tf.app.flags.DEFINE_string('log_dir','./path/log/','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('biases'):
              b = tf.Variable(tf.zeros([10]))
    
    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('train'):
         train_step = tf.train.GradientDescentOpitimizer(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_batcj(FLAGS.batch_size)
            fd = {x:batch_xs, y_:batch_ys}
            sess.run(train_step, feed_dict = tf)
    
    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.log_dir, sess.graph)
    
    输出:
        0.9221
    

    并且,注意在定义了FLAGS后,
    在任意地方都可以调用FLAGS里定义的变量,
    只需import FLAGS定义所在文件即可。

    相关文章

      网友评论

          本文标题:tf.app.flags

          本文链接:https://www.haomeiwen.com/subject/ckybpftx.html