#!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf FLAGS = None def main(_): # 主函數 # 讀取訓練測試數據 mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) # 建立模型 x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, W) + b y_ = tf.placeholder(tf.float32, [None, 10]) # 損失函數 cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y) ) # 訓練方法 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 開啓會話 # 初始化 sess = tf.InteractiveSession() tf.global_variables_initializer().run() # 訓練 for _ in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 測試 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) # python文件入口 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data', help='Directory for storing input data') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
1.python導入模塊的方式python
相對導入:在以當前路徑爲參照的相對路徑下搜索要導入的模塊,如:from . import xxxgit
絕對導入:在sys.path中搜索要導入的模塊app
在3.0之前的版本中導入新特性,使用from __future__ import xxx函數
2.argparse模塊測試
argparse是python用於解析命令行參數和選項的標準模塊,用於代替已通過時的optparse模塊。argparse模塊的做用是用於解析命令行參數,例如python parseTest.py input.txt output.txt --user=name --port=8080。spa
parser = argparse.ArgumentParser() # 建立一個解析對象 parser.add_argument() #向該對象中添加你要關注的命令行參數和選項,一次添加一個 parser.parse_args() #解析
上述例子中命令行
print(FLAGS) print(unparsed) print(FLAGS.data_dir) print([sys.argv[0]]) print([sys.argv[0]] + unparsed) #輸出以下 Namespace(data_dir='/tmp/tensorflow/mnist/input_data') [] /tmp/tensorflow/mnist/input_data ['C:/Users/Administrator/PycharmProjects/tensorflow/src/main.py'] ['C:/Users/Administrator/PycharmProjects/tensorflow/src/main.py']