參考文獻 強烈推薦Tensorflow實戰Google深度學習框架 實驗平臺: Tensorflow1.4.0 python3.5.0node
import tensorflow as tf # 不一樣的命名空間 with tf.variable_scope("foo"): # 在命名空間foo下獲取變量"bar",因而獲得的變量名稱爲"foo/bar" a = tf.get_variable("bar", [1]) print(a.name) # foo/bar:0 with tf.variable_scope("bar"): # 在命名空間bar下獲取變量"bar",因而獲得的變量名稱爲"bar/bar".此時變量在"bar/bar"和變量"foo/bar"並不衝突,因而能夠正常運行 b = tf.get_variable("bar", [1]) print(b.name) # bar/bar:0 # tf.Variable和tf.get_variable的區別。 with tf.name_scope("a"): # 使用tf.Variable函數生成變量時會受到tf.name_scope影響,因而這個變量的名稱爲"a/Variable" a = tf.Variable([1]) print(a.name) # a/Variable: 0 # tf.get_variable函數不受頭tf.name_scope函數的影響,因而變量並不在a這個命名空間中 a = tf.get_variable("b", [1]) print(a.name) # b:0 # with tf.name_scope("b"): # 由於tf.get_variable不受tf.name_scope影響,因此這裏將試圖獲取名稱爲"a"的變量。然而這個變量已經被聲明瞭,因而這裏會報重複聲明的錯誤。 # tf.get_variable("b",[1])
import tensorflow as tf with tf.name_scope("input1"): input1 = tf.constant([1.0, 2.0, 3.0], name="input2") with tf.name_scope("input2"): input2 = tf.Variable(tf.random_uniform([3]), name="input2") output = tf.add_n([input1, input2], name="add") writer = tf.summary.FileWriter("log/simple_example.log", tf.get_default_graph()) writer.close()
MNIST基本程序python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # mnist_inference中定義的常量和前向傳播的函數不須要改變,由於前向傳播已經經過 # tf.variable_scope實現了計算節點按照網絡結構的劃分 import mnist_inference # #### 1. 定義神經網絡的參數。 BATCH_SIZE = 100 LEARNING_RATE_BASE = 0.8 LEARNING_RATE_DECAY = 0.99 REGULARIZATION_RATE = 0.0001 TRAINING_STEPS = 3000 MOVING_AVERAGE_DECAY = 0.99 # #### 2. 定義訓練的過程並保存TensorBoard的log文件。 def train(mnist): # 將處理輸入數據的計算都放在名字爲"input"的命名空間中 with tf.name_scope('input'): x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input') y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input') regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE) y = mnist_inference.inference(x, regularizer) global_step = tf.Variable(0, trainable=False) # 將處理滑動平均相關的計算都放在名爲moving average 的命名空間下。 with tf.name_scope("moving_average"): variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) # 對可訓練變量集合使用滑動平均 # 將計算損失函數相關的計算都放在名爲loss function 的命名空間下。 with tf.name_scope("loss_function"): cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1)) cross_entropy_mean = tf.reduce_mean(cross_entropy) # 將交叉熵加上權值的正則化 loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses')) # 將定義學習率、優化方法以及每一輪訓練須要執行的操做都放在名字爲"train_step"的命名空間下。 with tf.name_scope("train_step"): learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, mnist.train.num_examples/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step) # 在反向傳播的過程當中更新變量的滑動平均值 with tf.control_dependencies([train_step, variables_averages_op]): train_op = tf.no_op(name='train') # 將結果記錄進log文件夾中 writer = tf.summary.FileWriter("log", tf.get_default_graph()) # 訓練模型。 with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(TRAINING_STEPS): xs, ys = mnist.train.next_batch(BATCH_SIZE) if i%1000 == 0: # 配置運行時須要記錄的信息。 run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) # 運行時記錄運行信息的proto。 run_metadata = tf.RunMetadata() # 將配置信息和記錄運行信息的proto傳入運行的過程,從而記錄運行時每個節點的時間空間開銷信息 _, loss_value, step = sess.run( [train_op, loss, global_step], feed_dict={x: xs, y_: ys}, options=run_options, run_metadata=run_metadata) writer.add_run_metadata(run_metadata=run_metadata, tag=("tag%d"%i), global_step=i) print("After %d training step(s), loss on training batch is %g."%(step, loss_value)) else: _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys}) writer.close() # #### 3. 主函數。 def main(argv=None): mnist = input_data.read_data_sets("../../datasets/MNIST_data", one_hot=True) train(mnist) if __name__ == '__main__': main()