Press "Enter" to skip to content

基于MNIST数据集实现2层神经网络案例实战-大数据ML样本集案例实战

本站内容均来自兴趣收集,如不慎侵害的您的相关权益,请留言告知,我们将尽快删除.谢谢.

版权声明:本套技术专栏是作者(秦凯新)平时工作的总结和升华,通过从真实商业环境抽取案例进行总结和分享,并给出商业应用的调优建议和集群环境容量规划等内容,请持续关注本套博客。QQ邮箱地址:[email protected],如有任何学术交流,可随时联系。

 

1 神经网络基本结构定义

28*28=784个像素点,第一层神经元256,第二层神经元128

2 神经网络构建

 

变量初始化

import numpy as np
  import tensorflow as tf
  import matplotlib.pyplot as plt
  import input_data
  mnist = input_data.read_data_sets('data/', one_hot=True)
  Extracting data/train-images-idx3-ubyte.gz
  Extracting data/train-labels-idx1-ubyte.gz
  Extracting data/t10k-images-idx3-ubyte.gz
  Extracting data/t10k-labels-idx1-ubyte.gz
  # NETWORK TOPOLOGIES
  #第一层神经元
  n_hidden_1 = 256 
  #第二层神经元
  n_hidden_2 = 128
  #28*28 784像素点
  n_input    = 784 
  # 类别10
  n_classes  = 10  
  # INPUTS AND OUTPUTS
  x = tf.placeholder("float", [None, n_input])
  y = tf.placeholder("float", [None, n_classes])
      
  # NETWORK PARAMETERS
  stddev = 0.1
  #初始化
  weights = {
      'w1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),
      'w2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),
      'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev))
  }
  #初始化
  biases = {
      'b1': tf.Variable(tf.random_normal([n_hidden_1])),
      'b2': tf.Variable(tf.random_normal([n_hidden_2])),
      'out': tf.Variable(tf.random_normal([n_classes]))
  }
  print ("NETWORK READY")

 

前向传播(每一层增加激活函数sigmoid,最后一层不加sigmoid)

def multilayer_perceptron(_X, _weights, _biases):
      layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1'])) 
      layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2']))
      return (tf.matmul(layer_2, _weights['out']) + _biases['out'])

 

损失变量和优化器定义

 

softmax_cross_entropy_with_logits交叉熵损失函数(参数pred预测值),reduce_mean除以样本总数。

 

GradientDescentOptimizer采用梯度下降优化求解

# PREDICTION
  pred = multilayer_perceptron(x, weights, biases)
  # LOSS AND OPTIMIZER
  cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) 
  optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost) 
  #准确率求解
  corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))    
  accr = tf.reduce_mean(tf.cast(corr, "float"))
  # INITIALIZER
  init = tf.global_variables_initializer()
  print ("FUNCTIONS READY")

 

按照Batch迭代

training_epochs = 20
  batch_size      = 100
  display_step    = 4
  # LAUNCH THE GRAPH
  sess = tf.Session()
  sess.run(init)
  # OPTIMIZE
  for epoch in range(training_epochs):
      avg_cost = 0.
      total_batch = int(mnist.train.num_examples/batch_size)
      
      # ITERATION(按照Batch迭代,每一次迭代100)
      for i in range(total_batch):
          batch_xs, batch_ys = mnist.train.next_batch(batch_size)
          #填充值
          feeds = {x: batch_xs, y: batch_ys}
          #sess.run(模型训练)
          sess.run(optm, feed_dict=feeds)
          avg_cost += sess.run(cost, feed_dict=feeds)
      avg_cost = avg_cost / total_batch
      # DISPLAY
      if (epoch+1) % display_step == 0:
          print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
          feeds = {x: batch_xs, y: batch_ys}
          
          #sess.run(准确率求解)
          train_acc = sess.run(accr, feed_dict=feeds)
          print ("TRAIN ACCURACY: %.3f" % (train_acc))
          feeds = {x: mnist.test.images, y: mnist.test.labels}
          test_acc = sess.run(accr, feed_dict=feeds)
          print ("TEST ACCURACY: %.3f" % (test_acc))
  print ("OPTIMIZATION FINISHED")

 

3 总结

 

基本的神经网络案例,在于真正的入门神经网络的构建。

 

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注