深度学习实践系列(2)- 搭建notMNIST的深度神经网络

如果你希望系统性的了解神经网络,请参考零基础入门深度学习系列,下面我会粗略的介绍一下本文中实现神经网络需要了解的知识。

什么是深度神经网络?

神经网络包含三层:输入层(X)、隐藏层和输出层:f(x)

每层之间每个节点都是完全连接的,其中包含权重(W)。每层都存在一个偏移值(b)。

每一层节点的计算方式如下:

其中g()代表激活函数,o()代表softmax输出函数。

使用Flow Graph的方式来表达如何正向推导神经网络,可以表达如下:

x: 输入值

a(x):表示每个隐藏层的pre-activation的数据,由前一个隐藏层数据(h)、权重(w)和偏移值(b)计算而来

h(x):表示每个隐藏层的数据

f(x):表示输出层数据

激活函数ReLUs

激活函数有很多种类,例如sigmoid、tanh、ReLUs,对于深度神经网络而言,目前最流行的是ReLUs。

关于几种激活函数的对比可以参见:常用激活函数的总结与比较

ReLUs函数如下:

反向传播

现在,我们需要知道一个神经网络的每个连接上的权值是如何得到的。我们可以说神经网络是一个模型,那么这些权值就是模型的参数,也就是模型要学习的东西。然而,一个神经网络的连接方式、网络的层数、每层的节点数这些参数,则不是学习出来的,而是人为事先设置的。对于这些人为设置的参数,我们称之为超参数(Hyper-Parameters)。

接下来,我们将要介绍神经网络的训练算法:反向传播算法。

具体内容请参考:零基础入门深度学习(3) - 神经网络和反向传播算法

SGD

梯度下降算法是一种不断调整参数值从而达到减少Loss function的方法,通过不断迭代而获得最佳的权重值。梯度下降传统上是每次迭代都使用全部训练数据来进行参数调整,随机梯度下降则是使用少量训练数据来进行调整。

关于GD和SGD的区别可以参考:GD(梯度下降)和SGD(随机梯度下降)

正则化和Dropout

正则化和Dropout都是一些防止过度拟合的方法,详细介绍可以参考:正则化方法:L1和L2 regularization、数据集扩增、dropout

正则化:通过在Loss function中加入对权重(w)的惩罚,可以限制权重值变得非常大

Dropout: 通过随机抛弃一些节点,使得神经网络更加多样性,然后组合起来获得的结果更加通用。

好吧,基本的概念大概介绍了一遍,开始撸代码啦。

请先参考深度学习实践系列(1)- 从零搭建notMNIST逻辑回归模型,获得notMNIST.pickle的训练数据。

1. 引用第三方库

# These are all the modules we‘ll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range

2. 读取数据

pickle_file = ‘notMNIST.pickle‘

with open(pickle_file, ‘rb‘) as f:
  save = pickle.load(f)
  train_dataset = save[‘train_dataset‘]
  train_labels = save[‘train_labels‘]
  valid_dataset = save[‘valid_dataset‘]
  valid_labels = save[‘valid_labels‘]
  test_dataset = save[‘test_dataset‘]
  test_labels = save[‘test_labels‘]
  del save  # hint to help gc free up memory
  print(‘Training set‘, train_dataset.shape, train_labels.shape)
  print(‘Validation set‘, valid_dataset.shape, valid_labels.shape)
  print(‘Test set‘, test_dataset.shape, test_labels.shape)
Training set (200000, 28, 28) (200000,)
Validation set (10000, 28, 28) (10000,)
Test set (10000, 28, 28) (10000,)

3. 调整数据格式以便后续训练

image_size = 28
num_labels = 10

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
  # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
  return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print(‘Training set‘, train_dataset.shape, train_labels.shape)
print(‘Validation set‘, valid_dataset.shape, valid_labels.shape)
print(‘Test set‘, test_dataset.shape, test_labels.shape)
Training set (200000, 784) (200000, 10)
Validation set (10000, 784) (10000, 10)
Test set (10000, 784) (10000, 10)

4. 定义神经网络

# With gradient descent training, even this much data is prohibitive.
# Subset the training data for faster turnaround.
train_subset = 10000

graph = tf.Graph()
with graph.as_default():

  # Input data.
  # Load the training, validation and test data into constants that are
  # attached to the graph.
  tf_train_dataset = tf.constant(train_dataset[:train_subset, :])
  tf_train_labels = tf.constant(train_labels[:train_subset])
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  # These are the parameters that we are going to be training. The weight
  # matrix will be initialized using random values following a (truncated)
  # normal distribution. The biases get initialized to zero.
  weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]))
  biases = tf.Variable(tf.zeros([num_labels]))

  # Training computation.
  # We multiply the inputs with the weight matrix, and add biases. We compute
  # the softmax and cross-entropy (it‘s one operation in TensorFlow, because
  # it‘s very common, and it can be optimized). We take the average of this
  # cross-entropy across all training examples: that‘s our loss.
  logits = tf.matmul(tf_train_dataset, weights) + biases
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

  # Optimizer.
  # We are going to find the minimum of this loss using gradient descent.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  # These are not part of training, but merely here so that we can report
  # accuracy figures as we train.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)
  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

5. 使用梯度下降(GD)训练神经网络

num_steps = 801

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

with tf.Session(graph=graph) as session:
  # This is a one-time operation which ensures the parameters get initialized as
  # we described in the graph: random weights for the matrix, zeros for the
  # biases.
  tf.global_variables_initializer().run()
  print(‘Initialized‘)
  for step in range(num_steps):
    # Run the computations. We tell .run() that we want to run the optimizer,
    # and get the loss value and the training predictions returned as numpy
    # arrays.
    _, l, predictions = session.run([optimizer, loss, train_prediction])
    if (step % 100 == 0):
      print(‘Loss at step %d: %f‘ % (step, l))
      print(‘Training accuracy: %.1f%%‘ % accuracy(
        predictions, train_labels[:train_subset, :]))
      # Calling .eval() on valid_prediction is basically like calling run(), but
      # just to get that one numpy array. Note that it recomputes all its graph
      # dependencies.
      print(‘Validation accuracy: %.1f%%‘ % accuracy(
        valid_prediction.eval(), valid_labels))
  print(‘Test accuracy: %.1f%%‘ % accuracy(test_prediction.eval(), test_labels))
Initialized
Loss at step 0: 16.516306
Training accuracy: 11.4%
Validation accuracy: 11.7%
Loss at step 100: 2.269041
Training accuracy: 71.8%
Validation accuracy: 70.2%
Loss at step 200: 1.816886
Training accuracy: 74.8%
Validation accuracy: 72.6%
Loss at step 300: 1.574824
Training accuracy: 76.0%
Validation accuracy: 73.6%
Loss at step 400: 1.415523
Training accuracy: 77.1%
Validation accuracy: 73.9%
Loss at step 500: 1.299691
Training accuracy: 78.0%
Validation accuracy: 74.4%
Loss at step 600: 1.209450
Training accuracy: 78.6%
Validation accuracy: 74.6%
Loss at step 700: 1.135888
Training accuracy: 79.0%
Validation accuracy: 74.9%
Loss at step 800: 1.074228
Training accuracy: 79.5%
Validation accuracy: 75.0%
Test accuracy: 82.3%

6. 使用随机梯度下降(SGD)算法

batch_size = 128

graph = tf.Graph()
with graph.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]))
  biases = tf.Variable(tf.zeros([num_labels]))

  # Training computation.
  logits = tf.matmul(tf_train_dataset, weights) + biases
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)
  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

num_steps = 3001

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
Initialized
Minibatch loss at step 0: 18.121506
Minibatch accuracy: 11.7%
Validation accuracy: 15.0%
Minibatch loss at step 500: 1.192153
Minibatch accuracy: 80.5%
Validation accuracy: 76.1%
Minibatch loss at step 1000: 1.309419
Minibatch accuracy: 75.8%
Validation accuracy: 76.8%
Minibatch loss at step 1500: 0.739157
Minibatch accuracy: 83.6%
Validation accuracy: 77.3%
Minibatch loss at step 2000: 0.854160
Minibatch accuracy: 85.2%
Validation accuracy: 77.5%
Minibatch loss at step 2500: 1.045702
Minibatch accuracy: 76.6%
Validation accuracy: 78.8%
Minibatch loss at step 3000: 0.940078
Minibatch accuracy: 79.7%
Validation accuracy: 78.8%
Test accuracy: 85.8%

7. 使用ReLUs激活函数

batch_size = 128
hidden_layer_size = 1024

graph = tf.Graph()
with graph.as_default():

    # Input data. For the training data, we use a placeholder that will be fed
    # at run time with a training minibatch.
    tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)

    # Variables.

    # Hidden layer (RELU magic)

    weights_hidden = tf.Variable(
        tf.truncated_normal([image_size * image_size, hidden_layer_size]))
    biases_hidden = tf.Variable(tf.zeros([hidden_layer_size]))
    hidden = tf.nn.relu(tf.matmul(tf_train_dataset, weights_hidden) + biases_hidden)

    # Output layer

    weights_output = tf.Variable(
        tf.truncated_normal([hidden_layer_size, num_labels]))
    biases_output = tf.Variable(tf.zeros([num_labels]))

    # Training computation.

    logits = tf.matmul(hidden, weights_output) + biases_output

    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

    # Optimizer.

    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.

    # Creation of hidden layer of RELU for the validation and testing process

    train_prediction = tf.nn.softmax(logits)

    hidden_validation = tf.nn.relu(tf.matmul(tf_valid_dataset, weights_hidden) + biases_hidden)
    valid_prediction = tf.nn.softmax(
    tf.matmul(hidden_validation, weights_output) + biases_output)

    hidden_prediction = tf.nn.relu(tf.matmul(tf_test_dataset, weights_hidden) + biases_hidden)
    test_prediction = tf.nn.softmax(tf.matmul(hidden_prediction, weights_output) + biases_output)

num_steps = 3001

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
Initialized
Minibatch loss at step 0: 282.291931
Minibatch accuracy: 14.1%
Validation accuracy: 32.1%
Minibatch loss at step 500: 18.090569
Minibatch accuracy: 82.0%
Validation accuracy: 79.7%
Minibatch loss at step 1000: 15.504422
Minibatch accuracy: 75.0%
Validation accuracy: 80.8%
Minibatch loss at step 1500: 5.314545
Minibatch accuracy: 87.5%
Validation accuracy: 80.6%
Minibatch loss at step 2000: 3.442260
Minibatch accuracy: 86.7%
Validation accuracy: 81.5%
Minibatch loss at step 2500: 2.226066
Minibatch accuracy: 83.6%
Validation accuracy: 82.6%
Minibatch loss at step 3000: 2.228517
Minibatch accuracy: 83.6%
Validation accuracy: 82.5%
Test accuracy: 89.6%

8. 正则化

import math
batch_size = 128
hidden_layer_size = 1024 # Doubled because half of the results are discarded
regularization_beta = 5e-4

graph = tf.Graph()
with graph.as_default():

    # Input data. For the training data, we use a placeholder that will be fed
    # at run time with a training minibatch.
    tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)

    # Variables.

    # Hidden layer (RELU magic)

    weights_hidden_1 = tf.Variable(
        tf.truncated_normal([image_size * image_size, hidden_layer_size],
                           stddev=1 / math.sqrt(float(image_size * image_size))))
    biases_hidden_1 = tf.Variable(tf.zeros([hidden_layer_size]))
    hidden_1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights_hidden_1) + biases_hidden_1)

    weights_hidden_2 = tf.Variable(tf.truncated_normal([hidden_layer_size, hidden_layer_size],
                                                      stddev=1 / math.sqrt(float(image_size * image_size))))
    biases_hidden_2 = tf.Variable(tf.zeros([hidden_layer_size]))
    hidden_2 = tf.nn.relu(tf.matmul(hidden_1, weights_hidden_2) + biases_hidden_2)

    # Output layer

    weights_output = tf.Variable(
        tf.truncated_normal([hidden_layer_size, num_labels],
                           stddev=1 / math.sqrt(float(image_size * image_size))))
    biases_output = tf.Variable(tf.zeros([num_labels]))

    # Training computation.

    logits = tf.matmul(hidden_2, weights_output) + biases_output

    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

    # L2 regularization on hidden and output weights and biases

    regularizers = (tf.nn.l2_loss(weights_hidden_1) + tf.nn.l2_loss(biases_hidden_1) +
                    tf.nn.l2_loss(weights_hidden_2) + tf.nn.l2_loss(biases_hidden_2) +
                    tf.nn.l2_loss(weights_output) + tf.nn.l2_loss(biases_output))

    loss = loss + regularization_beta * regularizers

    # Optimizer.

    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.

    # Creation of hidden layer of RELU for the validation and testing process

    train_prediction = tf.nn.softmax(logits)

    hidden_validation_1 = tf.nn.relu(tf.matmul(tf_valid_dataset, weights_hidden_1) + biases_hidden_1)
    hidden_validation_2 = tf.nn.relu(tf.matmul(hidden_validation_1, weights_hidden_2) + biases_hidden_2)
    valid_prediction = tf.nn.softmax(
    tf.matmul(hidden_validation_2, weights_output) + biases_output)

    hidden_prediction_1 = tf.nn.relu(tf.matmul(tf_test_dataset, weights_hidden_1) + biases_hidden_1)
    hidden_prediction_2 = tf.nn.relu(tf.matmul(hidden_prediction_1, weights_hidden_2) + biases_hidden_2)
    test_prediction = tf.nn.softmax(tf.matmul(hidden_prediction_2, weights_output) + biases_output)

num_steps = 3001

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
Initialized
Minibatch loss at step 0: 2.769384
Minibatch accuracy: 8.6%
Validation accuracy: 34.8%
Minibatch loss at step 500: 0.735681
Minibatch accuracy: 89.1%
Validation accuracy: 86.2%
Minibatch loss at step 1000: 0.791112
Minibatch accuracy: 85.9%
Validation accuracy: 86.9%
Minibatch loss at step 1500: 0.523572
Minibatch accuracy: 93.0%
Validation accuracy: 88.1%
Minibatch loss at step 2000: 0.487140
Minibatch accuracy: 95.3%
Validation accuracy: 88.5%
Minibatch loss at step 2500: 0.529468
Minibatch accuracy: 89.8%
Validation accuracy: 88.4%
Minibatch loss at step 3000: 0.531258
Minibatch accuracy: 86.7%
Validation accuracy: 88.9%
Test accuracy: 94.7%

9. Dropout

import math
batch_size = 128
hidden_layer_size = 2048 # Doubled because half of the results are discarded
regularization_beta = 5e-4

graph = tf.Graph()
with graph.as_default():

    # Input data. For the training data, we use a placeholder that will be fed
    # at run time with a training minibatch.
    tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)

    # Variables.

    # Hidden layer (RELU magic)

    weights_hidden_1 = tf.Variable(
        tf.truncated_normal([image_size * image_size, hidden_layer_size],
                           stddev=1 / math.sqrt(float(image_size * image_size))))
    biases_hidden_1 = tf.Variable(tf.zeros([hidden_layer_size]))
    hidden_1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights_hidden_1) + biases_hidden_1)

    weights_hidden_2 = tf.Variable(tf.truncated_normal([hidden_layer_size, hidden_layer_size],
                                                      stddev=1 / math.sqrt(float(image_size * image_size))))
    biases_hidden_2 = tf.Variable(tf.zeros([hidden_layer_size]))
    hidden_2 = tf.nn.relu(tf.matmul(tf.nn.dropout(hidden_1, 0.5), weights_hidden_2) + biases_hidden_2)

    # Output layer

    weights_output = tf.Variable(
        tf.truncated_normal([hidden_layer_size, num_labels],
                           stddev=1 / math.sqrt(float(image_size * image_size))))
    biases_output = tf.Variable(tf.zeros([num_labels]))

    # Training computation.

    logits = tf.matmul(tf.nn.dropout(hidden_2, 0.5), weights_output) + biases_output

    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

    # L2 regularization on hidden and output weights and biases

    regularizers = (tf.nn.l2_loss(weights_hidden_1) + tf.nn.l2_loss(biases_hidden_1) +
                    tf.nn.l2_loss(weights_hidden_2) + tf.nn.l2_loss(biases_hidden_2) +
                    tf.nn.l2_loss(weights_output) + tf.nn.l2_loss(biases_output))

    loss = loss + regularization_beta * regularizers

    # Optimizer.

    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.

    # Creation of hidden layer of RELU for the validation and testing process

    train_prediction = tf.nn.softmax(logits)

    hidden_validation_1 = tf.nn.relu(tf.matmul(tf_valid_dataset, weights_hidden_1) + biases_hidden_1)
    hidden_validation_2 = tf.nn.relu(tf.matmul(hidden_validation_1, weights_hidden_2) + biases_hidden_2)
    valid_prediction = tf.nn.softmax(
    tf.matmul(hidden_validation_2, weights_output) + biases_output)

    hidden_prediction_1 = tf.nn.relu(tf.matmul(tf_test_dataset, weights_hidden_1) + biases_hidden_1)
    hidden_prediction_2 = tf.nn.relu(tf.matmul(hidden_prediction_1, weights_hidden_2) + biases_hidden_2)
    test_prediction = tf.nn.softmax(tf.matmul(hidden_prediction_2, weights_output) + biases_output)

num_steps = 5001

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
WARNING:tensorflow:From <ipython-input-12-3684c7218154>:8: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Initialized
Minibatch loss at step 0: 4.059163
Minibatch accuracy: 7.8%
Validation accuracy: 31.5%
Minibatch loss at step 500: 1.626858
Minibatch accuracy: 86.7%
Validation accuracy: 84.8%
Minibatch loss at step 1000: 1.492026
Minibatch accuracy: 82.0%
Validation accuracy: 85.8%
Minibatch loss at step 1500: 1.139689
Minibatch accuracy: 92.2%
Validation accuracy: 87.1%
Minibatch loss at step 2000: 0.970064
Minibatch accuracy: 93.0%
Validation accuracy: 87.1%
Minibatch loss at step 2500: 0.963178
Minibatch accuracy: 87.5%
Validation accuracy: 87.6%
Minibatch loss at step 3000: 0.870884
Minibatch accuracy: 87.5%
Validation accuracy: 87.6%
Minibatch loss at step 3500: 0.898399
Minibatch accuracy: 85.2%
Validation accuracy: 87.7%
Minibatch loss at step 4000: 0.737084
Minibatch accuracy: 91.4%
Validation accuracy: 88.0%
Minibatch loss at step 4500: 0.646125
Minibatch accuracy: 88.3%
Validation accuracy: 87.7%
Minibatch loss at step 5000: 0.685591
Minibatch accuracy: 88.3%
Validation accuracy: 88.6%
Test accuracy: 94.4%

最后总结一下各种算法的训练表现,可以看出使用正则化和Dropout后训练效果明显变好,最后趋近于95%的准确率了。

时间: 2024-11-05 01:59:22

深度学习实践系列(2)- 搭建notMNIST的深度神经网络的相关文章

深度学习实践系列之--身份证上汉字及数字识别系统的实现(上)

前言: 本文章将记录我利用深度学习方法实现身份证图像的信息识别系统的实现过程,及学习到的心得与体会.本次实践是我投身AI的初次系统化的付诸实践,意义重大,让自己成长许多.终于有空闲的时间,将其记录,只为更好的分享与学习. 目录: 1.本人的主要工作 2.关键技术 3.模型训练 4.系统设计及实现 5.总结 正文: 一.本人的主要工作 深度学习技术与传统模式识别技术相比,免去人工提取特征,识别率更高.我基于深度学习的技术背景,主要的研究内容如下: 1)身份证图像涉及个人隐私,很难获取其数据训练集.

分享《自然语言处理理论与实战》PDF及代码+唐聃+《深入浅出Python机器学习》PDF及代码+段小手+《深度学习实践:计算机视觉》PDF+缪鹏+《最优化理论与算法第2版》高清PDF+习题解答PDF+《推荐系统与深度学习》PDF及代码学习

<自然语言处理理论与实战>高清PDF,362页,带书签目录,文字可以复制:配套源代码.唐聃等著. <大数据智能互联网时代的机器学习和自然语言处理技术>PDF,293页,带书签目录,文字可以复制,彩色配图.刘知远等著.  下载: https://pan.baidu.com/s/1waP6C086-32_Lv0Du3BbNw 提取码: 1ctr <自然语言处理理论与实战>讲述自然语言处理相关学科知识和理论基础,并介绍使用这些知识的应用和工具,以及如何在实际环境中使用它们.由

学习《深度学习实践:计算机视觉》PDF+缪鹏

<深度学习实践:计算机视觉>主要介绍了深度学习在计算机视觉方面的应用及工程实践,以Python 3为 开发语言,并结合当前主流的深度学习框架进行实例展示.主要内容包括:OpenCV入门.深度学习框架 介绍.图像分类.目标检测与识别.图像分割.图像搜索以及图像生成等,涉及到的深度学习框架包括 PyTorch.TensorFlow.Keras.Chainer.MXNet等.通过本书,读者能够了解深度学习在计算机视觉各个 方向的应用以及新进展. <深度学习实践:计算机视觉>主要关注计算机

Nagios学习实践系列——基本安装篇

开篇介绍 最近由于工作需要,学习研究了一下Nagios的安装.配置.使用,关于Nagios的介绍,可以参考我上篇随笔Nagios学习实践系列--产品介绍篇 实验环境 操作系统:Red Hat Enterprise Linux Server release 6.0 (Santiago)   64 bit. 注意,Nagios只能安装在Linux或Unix平台,不支持Windows平台,当然,它可以监控Windows平台. 环境准备 Apache 和PHP 不是安装Nagios所必须的,其实也可以说

Nagios学习实践系列

其实上篇Nagios学习实践系列--基本安装篇只是安装了Nagios基本组件,虽然能够打开主页,但是如果不配置相关配置文件文件,那么左边菜单很多页面都打不开,相当于只是一个空壳子.接下来,我们来学习研究一下Nagios的配置,了解一下基本的配置和了解各类配置文件. Nagios配置目录 Nagios的配置文件位于etc目录下(/usr/local/nagios/etc)如下图所示: 配置文件简介 配置文件名 功能描述 cgi.cfg 控制CGI访问的配置文件 nagios.cfg 主配置文件:主

CV学习资料《卷积神经网络与视觉计算》+《深度学习实践计算机视觉》+《视觉SLAM十四讲从理论到实践》电子资料代码分析

视觉和图形学真是一家,基础都一样! 如果学习图像识别,计算机视觉,推荐电子书<视觉SLAM十四讲:从理论到实践>,系统介绍了视觉SLAM(同时定位与地图构建)所需的基本知识与核心算法,既包括数学理论基础,如三维空间的刚体运动.非线性优化,又包括计算机视觉的算法实现,例如多视图几何.回环检测等. 一个周读完了,代码很清晰!Particle Filtering,KF,EKF, Batch Optimization, Lie Group,ICP,LK光流... 尤其惊喜的是文末作者看好的IMU-SL

深度学习框架keras平台搭建(关键字:windows、非GPU、离线安装)

当下,人工智能越来越受到人们的关注,而这很大程度上都归功于深度学习的迅猛发展.人工智能和不同产业之间的成功跨界对传统产业产生着深刻的影响. 最近,我也开始不断接触深度学习,之前也看了很多文章介绍,对深度学习的历史发展以及相关理论知识也有大致了解. 但常言道:纸上得来终觉浅,绝知此事要躬行:与其临渊羡鱼,不如退而结网.因此决定自己动手玩一玩. 对比了当下众多流行框架的优缺点,以及结合自身硬件条件,最后选定keras框架作为入手点. 作为大多数人都习惯于Windows系统,此外由于GPU比较昂贵,本

《神经网络和深度学习》系列文章十六:反向传播算法代码

出处: Michael Nielsen的<Neural Network and Deep Learning>,点击末尾“阅读原文”即可查看英文原文. 本节译者:哈工大SCIR硕士生 李盛秋 声明:如需转载请联系[email protected],未经授权不得转载. 使用神经网络识别手写数字 反向传播算法是如何工作的 热身:一个基于矩阵的快速计算神经网络输出的方法 关于损失函数的两个假设 Hadamard积 反向传播背后的四个基本等式 四个基本等式的证明(选读) 反向传播算法 反向传播算法代码

《神经网络和深度学习》系列文章三:sigmoid神经元

出处: Michael Nielsen的<Neural Network and Deep Leraning>,点击末尾“阅读原文”即可查看英文原文. 本节译者:哈工大SCIR硕士生 徐伟 (https://github.com/memeda) 声明:我们将在每周一,周四,周日定期连载该书的中文翻译,如需转载请联系[email protected],未经授权不得转载. “本文转载自[哈工大SCIR]微信公众号,转载已征得同意.” 使用神经网络识别手写数字 感知机 sigmoid神经元 神经网络的