Tensorflow實(shí)現(xiàn)兩個(gè)隱藏層全連接網(wǎng)絡(luò)(改進(jìn)版)

mnist.py文件

# coding=utf-8
'''
Created on Feb 11, 2019

@author: zhongzhu
'''
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Builds the MNIST network.

Implements the inference/loss/training pattern for model building.

1. inference() - Builds the model as far as required for running the network
forward to make predictions.
2. loss() - Adds to the inference model the layers required to generate loss.
3. training() - Adds to the loss model the Ops required to generate and
apply gradients.

This file is used by the various "fully_connected_*.py" files and not meant to
be run.
"""

import math

import tensorflow as tf

# The MNIST dataset has 10 classes, representing the digits 0 through 9.
NUM_CLASSES = 10

# The MNIST images are always 28x28 pixels.
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE


def inference(images, hidden1_units, hidden2_units):
  """Build the MNIST model up to where it may be used for inference.

  Args:
    images: Images placeholder, from inputs().
    hidden1_units: Size of the first hidden layer.
    hidden2_units: Size of the second hidden layer.

  Returns:
    softmax_linear: Output tensor with the computed logits.
  """
  # Hidden 1
  with tf.name_scope('hidden1'):
    weights = tf.Variable(
        tf.truncated_normal([IMAGE_PIXELS, hidden1_units],
                            stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))),
        name='weights')
    biases = tf.Variable(tf.zeros([hidden1_units]),
                         name='biases')
    hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)
  # Hidden 2
  with tf.name_scope('hidden2'):
    weights = tf.Variable(
        tf.truncated_normal([hidden1_units, hidden2_units],
                            stddev=1.0 / math.sqrt(float(hidden1_units))),
        name='weights')
    biases = tf.Variable(tf.zeros([hidden2_units]),
                         name='biases')
    hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)
  # Linear
  with tf.name_scope('softmax_linear'):
    weights = tf.Variable(
        tf.truncated_normal([hidden2_units, NUM_CLASSES],
                            stddev=1.0 / math.sqrt(float(hidden2_units))),
        name='weights')
    biases = tf.Variable(tf.zeros([NUM_CLASSES]),
                         name='biases')
    logits = tf.matmul(hidden2, weights) + biases
  return logits


def loss(logits, labels):
  """Calculates the loss from the logits and the labels.

  Args:
    logits: Logits tensor, float - [batch_size, NUM_CLASSES].
    labels: Labels tensor, int32 - [batch_size].

  Returns:
    loss: Loss tensor of type float.
  """
  labels = tf.to_int64(labels)
  return tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)


def training(loss, learning_rate):
  """Sets up the training Ops.

  Creates a summarizer to track the loss over time in TensorBoard.

  Creates an optimizer and applies the gradients to all trainable variables.

  The Op returned by this function is what must be passed to the
  `sess.run()` call to cause the model to train.

  Args:
    loss: Loss tensor, from loss().
    learning_rate: The learning rate to use for gradient descent.

  Returns:
    train_op: The Op for training.
  """
  
  with tf.name_scope('scalar_summaries'):
      # Add a scalar summary for the snapshot loss.
      tf.summary.scalar('loss', loss)
      tf.summary.scalar('learning_rate', learning_rate)

  # Create the gradient descent optimizer with the given learning rate.
  optimizer = tf.train.GradientDescentOptimizer(learning_rate)
  # Create a variable to track the global step.
  global_step = tf.Variable(0, name='global_step', trainable=False)
  # Use the optimizer to apply the gradients that minimize the loss
  # (and also increment the global step counter) as a single training step.
 
  train_op = optimizer.minimize(loss, global_step=global_step)
  return train_op


def evaluation(logits, labels):
  """Evaluate the quality of the logits at predicting the label.

  Args:
    logits: Logits tensor, float - [batch_size, NUM_CLASSES].
    labels: Labels tensor, int32 - [batch_size], with values in the
      range [0, NUM_CLASSES).

  Returns:
    A scalar int32 tensor with the number of examples (out of batch_size)
    that were predicted correctly.
  """
  # For a classifier model, we can use the in_top_k Op.
  # It returns a bool tensor with shape [batch_size] that is true for
  # the examples where the label is in the top k (here k=1)
  # of all logits for that example.
  correct = tf.nn.in_top_k(logits, labels, 1)
  # Return the number of true entries.
  return tf.reduce_sum(tf.cast(correct, tf.int32))

fully_connected_toturol.py文件

# coding=utf-8
'''
Created on Feb 11, 2019

@author: zhongzhu
'''
import argparse
import os.path
import sys
import time
import os
from six.moves import xrange
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
# from tensorflow.examples.tutorials.mnist import mnist
import mnist
#過濾警告信息
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 全局變量恒削,用來存放基本的模型(超)參數(shù).
FLAGS = None


#產(chǎn)生 placeholder variables來表達(dá)輸入張量
def placeholder_inputs(batch_size):
    images_placeholder = tf.placeholder(tf.float32, shape=(batch_size, mnist.IMAGE_PIXELS))
    labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))
    return images_placeholder, labels_placeholder

def fill_feed_dict(data_set, images_pl, labels_pl):
    images_feed, labels_feed = data_set.next_batch(FLAGS.batch_size, FLAGS.fake_data)
    feed_dict = {images_pl: images_feed, labels_pl: labels_feed}
    return feed_dict

#在給定的數(shù)據(jù)集上執(zhí)行一次評(píng)估操作
def do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_set):
    true_count = 0
    steps_per_epoch = data_set.num_examples // FLAGS.batch_size
    num_examples = steps_per_epoch * FLAGS.batch_size
    
    for step in xrange(steps_per_epoch):
        feed_dict = fill_feed_dict(data_set, images_placeholder, labels_placeholder)
        true_count += sess.run(eval_correct, feed_dict = feed_dict)
    
    precision = float(true_count) / num_examples
    print('  Num examples: %d  Num correct: %d  Precision @ 1: %0.04f' %
        (num_examples, true_count, precision))


# 啟動(dòng)訓(xùn)練過程
def run_training():
    data_sets = input_data.read_data_sets(FLAGS.input_data_dir, FLAGS.fake_data)
    
    # 告訴Tensorflow模型將會(huì)被構(gòu)建在默認(rèn)的Graph上
    with tf.Graph().as_default():
        images_placeholder, labels_placeholder = placeholder_inputs(FLAGS.batch_size)
        #從前向推斷模型中構(gòu)建用于預(yù)測的計(jì)算圖
        logits = mnist.inference(images_placeholder, FLAGS.hidden1, FLAGS.hidden2)
        #為計(jì)算圖添加計(jì)算損失的節(jié)點(diǎn)
        loss = mnist.loss(logits, labels_placeholder)
        #為計(jì)算圖添加計(jì)算和應(yīng)用梯度的節(jié)點(diǎn)
        train_op = mnist.training(loss, FLAGS.learning_rate)
        # 添加評(píng)估節(jié)點(diǎn)
        eval_correct = mnist.evaluation(logits, labels_placeholder)
        
        init = tf.global_variables_initializer()
        
        merged_summaries = tf.summary.merge_all()
        
        
        saver = tf.train.Saver()
        # 創(chuàng)建一個(gè)會(huì)話用來運(yùn)行計(jì)算圖中的節(jié)點(diǎn)
        sess = tf.Session()
        
         # 實(shí)例化一個(gè) SummaryWriter 輸出 summaries 和 Graph.
        summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)
        summary_writer.flush()
        
        sess.run(init)
        
        for step in xrange(FLAGS.max_steps):
            start_time = time.time()
            feed_dict = fill_feed_dict(data_sets.train, images_placeholder, labels_placeholder)
            _, loss_value = sess.run([train_op, loss],feed_dict = feed_dict)
            duration = time.time() - start_time
            
            if step % 100 == 0:
                print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration))
                summary_str = sess.run(merged_summaries,feed_dict=feed_dict)
                summary_writer.add_summary(summary_str, step)
                summary_writer.flush()
            
            
            if (step + 1) % 1000 == 0  or (step + 1) == FLAGS.max_steps:
                
                checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')
                saver.save(sess, checkpoint_file, global_step=step)
                print('Training data eval')
                do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.train)
                print('Validation data eval')
                do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.validation)
                print('Test data eval')
                do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.test)

#創(chuàng)建日志文件夾,啟動(dòng)訓(xùn)練過程
def main(_):
#     if tf.gfile.Exists(FLAGS.log_dir):
#         tf.gfile.DeleteRecursively(FLAGS.log_dir)
#     tf.gfile.MakeDirs(FLAGS.log_dir)
    #啟動(dòng)訓(xùn)練過程
    run_training()

#用ArgumentParser類把模型的(超)參數(shù)全部解析到全局變量FLAGS里面
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
      '--learning_rate',
      type=float,
      default=0.01,
      help='Initial learning rate.'
      )
    parser.add_argument(
      '--max_steps',
      type=int,
      default=2000,
      help='Number of steps to run trainer.'
      )
    parser.add_argument(
      '--hidden1',
      type=int,
      default=128,
      help='Number of units in hidden layer 1.'
      )
    parser.add_argument(
      '--hidden2',
      type=int,
      default=32,
      help='Number of units in hidden layer 2.'
      )
    parser.add_argument(
      '--batch_size',
      type=int,
      default=100,
      help='Batch size.  Must divide evenly into the dataset sizes.'
      )
    parser.add_argument(
      '--input_data_dir',
      type=str,
      default='MNIST_data/',
      help='Directory to put the input data.'
      )
    parser.add_argument(
      '--log_dir',
      type=str,
      default='logs/Fully_Connected_Feed',
      help='Directory to put the log data.'
      )
    parser.add_argument(
      '--fake_data',
      default=False,
      help='If true, uses fake data for unit testing.',
      action='store_true'
      )
  #把模型的(超)參數(shù)全部解析到全局變量FLAGS里面
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

程序運(yùn)行結(jié)果池颈,

Scalar標(biāo)量圖尾序,


image.png

hidden1/weights 圖,

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末躯砰,一起剝皮案震驚了整個(gè)濱河市每币,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌琢歇,老刑警劉巖兰怠,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異李茫,居然都是意外死亡揭保,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門魄宏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來秸侣,“玉大人,你說我怎么就攤上這事宠互∥堕唬” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵予跌,是天一觀的道長搏色。 經(jīng)常有香客問我,道長券册,這世上最難降的妖魔是什么频轿? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮烁焙,結(jié)果婚禮上略吨,老公的妹妹穿的比我還像新娘。我一直安慰自己考阱,他們只是感情好翠忠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著乞榨,像睡著了一般秽之。 火紅的嫁衣襯著肌膚如雪当娱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天考榨,我揣著相機(jī)與錄音跨细,去河邊找鬼。 笑死河质,一個(gè)胖子當(dāng)著我的面吹牛冀惭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播掀鹅,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼散休,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤困鸥,失蹤者是張志新(化名)和其女友劉穎创肥,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了胁勺。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡独旷,死狀恐怖署穗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情势告,我是刑警寧澤蛇捌,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站咱台,受9級(jí)特大地震影響络拌,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜回溺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一春贸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧遗遵,春花似錦萍恕、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春类垫,著一層夾襖步出監(jiān)牢的瞬間司光,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來泰國打工悉患, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留残家,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓售躁,卻偏偏與公主長得像坞淮,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子陪捷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容