1. 程式人生 > >tensorflow 基礎學習八:重構MNIST神經網絡

tensorflow 基礎學習八:重構MNIST神經網絡

sta pen 正則化 gpo 第一次 one spl post sse

  使用前面介紹的技術,實踐一個神經網絡模型。將訓練和測試分成兩個獨立的程序,訓練網絡的程序可以持續輸出訓練好的模型,測試程序可以每隔一段時間檢驗最新模型的正確率。

技術分享圖片
# -*- coding:utf-8 -*-
import tensorflow as tf

# 定義神經網絡結構相關的參數
INPUT_NODE=784
OUTPUT_NODE=10
LAYER1_NODE=500

# 通過tf.get_variable函數來獲取變量。在訓練神經網絡時會創建這些變量;在測試時會通過
# 保存的模型加載這些變量的取值。而且更加靈活的是,因為可以在變量加載時將滑動平均變量
# 重命名,所以可以直接通過同樣的名字在訓練時使用變量自身,而在測試時使用變量的滑動
# 平均值。在這個函數中也會將變量的正則化損失加入損失集合。 def get_weight_variable(shape,regularizer): weights=tf.get_variable(weights,shape,initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.add_to_collection(losses,regularizer(weights)) return weights # 定義神經網絡的前向傳播過程
def inference(input_tensor,regularizer): # 如果在同一個程序中多次調用,在第一次調用之後需要將參數reuse設置為True with tf.variable_scope(layer1): weights=get_weight_variable([INPUT_NODE,LAYER1_NODE],regularizer) biases=tf.get_variable(biases,[LAYER1_NODE],initializer=tf.constant_initializer(0.0)) layer1
=tf.nn.relu(tf.matmul(input_tensor,weights)+biases) with tf.variable_scope(layer2): weights=get_weight_variable([LAYER1_NODE,OUTPUT_NODE],regularizer) biases=tf.get_variable(biases,[OUTPUT_NODE],initializer=tf.constant_initializer(0.0)) layer2=tf.matmul(layer1,weights)+biases return layer2
mnist_inference.py

tensorflow 基礎學習八:重構MNIST神經網絡