(尤其是训练集验证集的生成)深度学习 tensorflow 实战(2) 实现简单神经网络以及随机梯度下降算法S.G.D

在之前的实战(1) 中,我们将数据清洗整理后,得到了'notMNIST.pickle'数据。

本文将阐述利用tensorflow创建一个简单的神经网络以及随机梯度下降算法

  1. # These are all the modules we'll be using later. Make sure you can import them  
  2. # before proceeding further.  
  3. from __future__ import print_function  
  4. import numpy as np  
  5. import tensorflow as tf  
  6. from six.moves import cPickle as pickle  
  7. from six.moves import range  
首先,载入之前整理好的数据'notMNIST.pickle'。(在实战(1)中得到的)

  1. pickle_file = 'notMNIST.pickle'  
  2.   
  3. with open(pickle_file, 'rb') as f:  
  4.     save = pickle.load(f)  
  5.     train_dataset = save['train_dataset']  
  6.     train_labels = save['train_labels']  
  7.     valid_dataset = save['valid_dataset']  
  8.     valid_labels = save['valid_labels']  
  9.     test_dataset = save['test_dataset']  
  10.     test_labels = save['test_labels']  
  11.   
  12.     del save  # hint to help gc free up memory 帮助回收内存  
  13.       
  14.     print('Training set', train_dataset.shape, train_labels.shape)  
  15.     print('Validation set', valid_dataset.shape, valid_labels.shape)  
  16.     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,)

下一步转换数据格式。


将图像拉成一维数组。


dataset成为二维数组。


label也成为二位数组。


0 对应[1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]


1 对应[0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]

  1. image_size = 28  
  2. num_labels = 10  
  3.   
  4. def reformat(dataset, labels):  
  5.     dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # -1 means unspecified value adaptive   
  6.     # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]  
  7.     labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)  
  8.     return dataset, labels  
  9. train_dataset, train_labels = reformat(train_dataset, train_labels)  
  10. valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)  
  11. test_dataset, test_labels = reformat(test_dataset, test_labels)  
  12. print('Training set', train_dataset.shape, train_labels.shape)  
  13. print('Validation set', valid_dataset.shape, valid_labels.shape)  
  14. 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)


准备好数据后,首先使用简单梯度下降法的训练数据。

tensorflow 这样工作: 首先描述你的输入,变量,以及操作。这些组成了计算图。 之后的操作要在这个block下面进行。

比如:

  1. with graph.as_default():  
  2.     ...  

然后可以用命令session.run()运行你定义的操作。 上下文管理器用来定义session.你所定义的操作也一定要在session的block下面。
  1. with tf.Session(graph=graph) as session:  
  2.     ...  
这时我们可以载入数据进行训练啦。

  1. # With gradient descent training, even this much data is prohibitive.  
  2. # Subset the training data for faster turnaround.  
  3. train_subset = 10000  
  4.   
  5. graph = tf.Graph()  
  6. with graph.as_default():  
  7.     # Input data. 定义输入数据并载入                            -----------------------------------------1  
  8.     # Load the training, validation and test data into constants that are  
  9.     # attached to the graph.  
  10.     tf_train_dataset = tf.constant(train_dataset[:train_subset, :])  
  11.     tf_train_labels = tf.constant(train_labels[:train_subset])  
  12.       
  13.     tf_valid_dataset = tf.constant(valid_dataset)  
  14.     tf_test_dataset = tf.constant(test_dataset)  
  15.     
  16.     # Variables.定义变量 要训练得到的参数weight, bias  ----------------------------------------2  
  17.     # These are the parameters that we are going to be training. The weight  
  18.     # matrix will be initialized using random values following a (truncated)  
  19.     # normal distribution. The biases get initialized to zero.  
  20.     weights = tf.Variable(tf.truncated_normal([image_size * image_size, num_labels])) # changing when training   
  21.     biases = tf.Variable(tf.zeros([num_labels])) # changing when training   
  22.       
  23.     #   tf.truncated_normal  
  24.     #   tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)  
  25.     #   Outputs random values from a truncated normal distribution.  
  26.     #  The generated values follow a normal distribution with specified mean and  
  27.     #  standard deviation, except that values whose magnitude is more than 2 standard  
  28.     #  deviations from the mean are dropped and re-picked.  
  29.       
  30.     # tf.zeros  
  31.     #  tf.zeros([10])      <tf.Tensor 'zeros:0' shape=(10,) dtype=float32>  
  32.   
  33.   
  34.     
  35.     # Training computation. 训练数据                                ----------------------------------------3  
  36.     # We multiply the inputs with the weight matrix, and add biases. We compute  
  37.     # the softmax and cross-entropy (it's one operation in TensorFlow, because  
  38.     # it's very common, and it can be optimized). We take the average of this  
  39.     # cross-entropy across all training examples: that's our loss.  
  40.     logits = tf.matmul(tf_train_dataset, weights) + biases             # tf.matmul          matrix multiply       
  41.       
  42.     loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))  # compute average cross entropy loss  
  43.     #  softmax_cross_entropy_with_logits  
  44.       
  45.     # The activation ops provide different types of nonlinearities for use in neural  
  46.     # networks.  These include smooth nonlinearities (`sigmoid`, `tanh`, `elu`,  
  47.     #   `softplus`, and `softsign`), continuous but not everywhere differentiable  
  48.     # functions (`relu`, `relu6`, and `relu_x`), and random regularization (`dropout`).  
  49.       
  50.       
  51.     #  tf.reduce_mean  
  52.     #    tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)  
  53.     #   Computes the mean of elements across dimensions of a tensor.  
  54.     
  55.     # Optimizer.                                                                    -----------------------------------------4  
  56.     # We are going to find the minimum of this loss using gradient descent.  
  57.     optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)     # 0.5 means learning rate  
  58.     #  tf.train.GradientDescentOptimizer(  
  59.     #  tf.train.GradientDescentOptimizer(self, learning_rate, use_locking=False, name='GradientDescent')  
  60.       
  61.       
  62.       
  63.     
  64.     # Predictions for the training, validation, and test data.---------------------------------------5  
  65.     # These are not part of training, but merely here so that we can report  
  66.     # accuracy figures as we train.  
  67.       
  68.     train_prediction = tf.nn.softmax(logits) # weights  and bias have been changed  
  69.     valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)  
  70.     test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)  
  71.       
  72.     # tf.nn.softmax  
  73.     #  Returns: A `Tensor`. Has the same type as `logits`. Same shape as `logits`.(num, 784) *(784,10)  + = (num, 10)  
下面进行简单的梯度下降,开始迭代。

  1. num_steps = 801  
  2.   
  3. def accuracy(predictions, labels):  
  4.     ''''' predictions = [0.8,0,0,0,0.1,0,0,0.1,0,0] 
  5.         labels = [1,0,0,0,0,0,0,0,0,0] 
  6.     '''  
  7.     return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0])  
  8.   
  9. with tf.Session(graph=graph) as session:  
  10.     # This is a one-time operation which ensures the parameters get initialized as  
  11.     # we described in the graph:   
  12.     #  random weights for the matrix, zeros for the biases.   
  13.     tf.initialize_all_variables().run() # initialize  
  14.     print('Initialized')  
  15.     for step in xrange(num_steps):  
  16.         # Run the computations. We tell .run() that we want to run the optimizer,  
  17.         # and get the loss value and the training predictions returned as numpy  
  18.         # arrays.  
  19.          _, l, predictions = session.run([optimizer, loss, train_prediction]) # using train_prediction to train and return prediction in train data set  
  20.         if (step % 100 == 0):  
  21.             print('Loss at step %d: %f' % (step, l))  
  22.             print('Training accuracy: %.1f%%' % accuracy(  
  23.             predictions, train_labels[:train_subset, :]))  
  24.             # Calling .eval() on valid_prediction is basically like calling run(), but  
  25.             # just to get that one numpy array. Note that it recomputes all its graph  
  26.             # dependencies.  
  27.             print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), valid_labels))  
  28.           
  29.     print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))  

运行结果如下:


Initialized
Loss at step 0: 17.639723
Training accuracy: 8.9%
Validation accuracy: 11.4%
Loss at step 100: 2.268863
Training accuracy: 71.8%
Validation accuracy: 70.8%
Loss at step 200: 1.818829
Training accuracy: 74.9%
Validation accuracy: 73.6%
Loss at step 300: 1.580101
Training accuracy: 76.5%
Validation accuracy: 74.5%
Loss at step 400: 1.419103
Training accuracy: 77.1%
Validation accuracy: 75.1%
Loss at step 500: 1.299344
Training accuracy: 77.7%
Validation accuracy: 75.3%
Loss at step 600: 1.205005
Training accuracy: 78.3%
Validation accuracy: 75.3%
Loss at step 700: 1.127984
Training accuracy: 78.8%
Validation accuracy: 75.5%
Loss at step 800: 1.063572
Training accuracy: 79.3%
Validation accuracy: 75.7%
Test accuracy: 82.6%

之后,我们可以用更快的优化算法,随机梯度算法进行训练。

graph的定义与之前类似,不同的是我们的训练数据是一小批一小批的。

所以要在运行session.run()时并导入小批量数据之前定义占位量(placeholder).。

  1. batch_size = 128  
  2.   
  3. graph = tf.Graph()  
  4. with graph.as_default():  
  5.     # Input data. For the training data, we use a placeholder that will be fed ----------------------------------------1  
  6.     # at run time with a training minibatch.  
  7.     #  相当于开辟空间  
  8.     tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size))  
  9.     tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))  
  10.       
  11.     tf_valid_dataset = tf.constant(valid_dataset)  
  12.     tf_test_dataset = tf.constant(test_dataset)  
  13.     
  14.     # Variables.                                                                                                       ------------------------------------------2  
  15.     weights = tf.Variable(tf.truncated_normal([image_size * image_size, num_labels]))  
  16.     biases = tf.Variable(tf.zeros([num_labels]))  
  17.     
  18.     # Training computation.                                                                                  ------------------------------------------3  
  19.     logits = tf.matmul(tf_train_dataset, weights) + biases  
  20.     loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))  
  21.     
  22.   # Optimizer.                                                                                                       -------------------------------------------4  
  23.     optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)  
  24.     
  25.     # Predictions for the training, validation, and test data.                             --------------------------------------------5  
  26.     train_prediction = tf.nn.softmax(logits)  
  27.     valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)  
  28.     test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)  
下面是对应的训练操作代码:
  1. num_steps = 3001  
  2.   
  3. with tf.Session(graph=graph) as session:  
  4.     tf.initialize_all_variables().run()  
  5.     print("Initialized")  
  6.     for step in range(num_steps):  
  7.     # Pick an offset within the training data, which has been randomized.  
  8.     # Note: we could use better randomization across epochs.  
  9.         offset = (step * batch_size) % (train_labels.shape[0] - batch_size)  
  10.     # Generate a minibatch.  
  11.         batch_data = train_dataset[offset:(offset + batch_size), :]  
  12.         batch_labels = train_labels[offset:(offset + batch_size), :]  
  13.     # Prepare a dictionary telling the session where to feed the minibatch.  
  14.     # The key of the dictionary is the placeholder node of the graph to be fed,  
  15.     # and the value is the numpy array to feed to it.  
  16.         #  传递值到tf的命名空间  
  17.         feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}  
  18.         _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)  
  19.         if (step % 500 == 0):  
  20.             print("Minibatch loss at step %d: %f" % (step, l))  
  21.             print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))  
  22.             print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))  
  23.     print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))  
运行结果如下:
Initialized
Minibatch loss at step 0: 16.076256
Minibatch accuracy: 14.1%
Validation accuracy: 17.9%
Minibatch loss at step 500: 1.690020
Minibatch accuracy: 72.7%
Validation accuracy: 75.1%
Minibatch loss at step 1000: 1.430756
Minibatch accuracy: 77.3%
Validation accuracy: 76.1%
Minibatch loss at step 1500: 1.065795
Minibatch accuracy: 81.2%
Validation accuracy: 77.0%
Minibatch loss at step 2000: 1.248749
Minibatch accuracy: 75.0%
Validation accuracy: 77.3%
Minibatch loss at step 2500: 0.934266
Minibatch accuracy: 81.2%
Validation accuracy: 78.1%
Minibatch loss at step 3000: 1.047278
Minibatch accuracy: 76.6%
Validation accuracy: 78.4%
Test accuracy: 85.4%


现在我们加入一层1024节点的隐含层,并使用rectified linear units神经单元,随后利用S.G.D进行训练看看效果。

当然结果肯定会有所提升。

  1. batch_size = 128  
  2. hiden_layer_node_num = 1024  
  3.   
  4. graph = tf.Graph()  
  5. with graph.as_default():  
  6.     # input                                                                                                             -----------------------------------------1  
  7.     tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size))  
  8.     tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))  
  9.       
  10.     tf_valid_dataset = tf.constant(valid_dataset)  
  11.     tf_test_dataset = tf.constant(test_dataset)  
  12.     
  13.     # Variables.                                                                                                       ------------------------------------------2  
  14.     weights1 = tf.Variable(tf.truncated_normal([image_size * image_size, hiden_layer_node_num]))  
  15.     biases1 = tf.Variable(tf.zeros([hiden_layer_node_num]))  
  16.       
  17.     # input layer output (batch_size, hiden_layer_node_num)  
  18.     weights2 = tf.Variable(tf.truncated_normal([hiden_layer_node_num, num_labels]))  
  19.     biases2 = tf.Variable(tf.zeros([num_labels]))  
  20.       
  21.     
  22.     # Training computation.                                                                                  ------------------------------------------3  
  23.     logits = tf.matmul(tf.nn.relu(tf.matmul(tf_train_dataset, weights1) + biases1), weights2) + biases2  
  24.     loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))  
  25.     
  26.   # Optimizer.                                                                                                       -------------------------------------------4  
  27.     optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)  
  28.     
  29.     # Predictions for the training, validation, and test data.                            --------------------------------------------5  
  30.     train_prediction = tf.nn.softmax(logits)  
  31.     valid_prediction = tf.nn.softmax(tf.matmul(tf.nn.relu(tf.matmul(tf_valid_dataset, weights1) + biases1), weights2) + biases2)  
  32.     test_prediction = tf.nn.softmax(tf.matmul(tf.nn.relu(tf.matmul(tf_test_dataset, weights1) + biases1), weights2) + biases2)  
  33. num_steps = 3001  
  34.   
  35. with tf.Session(graph=graph) as session:  
  36.     tf.initialize_all_variables().run()  
  37.     print("Initialized")  
  38.     for step in range(num_steps):  
  39.     # Pick an offset within the training data, which has been randomized.  
  40.     # Note: we could use better randomization across epochs.  
  41.         offset = (step * batch_size) % (train_labels.shape[0] - batch_size)  
  42.     # Generate a minibatch.  
  43.         batch_data = train_dataset[offset:(offset + batch_size), :]  
  44.         batch_labels = train_labels[offset:(offset + batch_size), :]  
  45.     # Prepare a dictionary telling the session where to feed the minibatch.  
  46.     # The key of the dictionary is the placeholder node of the graph to be fed,  
  47.     # and the value is the numpy array to feed to it.  
  48.         #  传递值到tf的命名空间  
  49.         feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}  
  50.         _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)  
  51.         if (step % 500 == 0):  
  52.             print("Minibatch loss at step %d: %f" % (step, l))  
  53.             print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))  
  54.             print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))  
  55.     print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))  
运行结果如下:
Initialized
Minibatch loss at step 0: 379.534973
Minibatch accuracy: 8.6%
Validation accuracy: 21.7%
Minibatch loss at step 500: 12.951815
Minibatch accuracy: 86.7%
Validation accuracy: 80.8%
Minibatch loss at step 1000: 9.569818
Minibatch accuracy: 82.8%
Validation accuracy: 80.9%
Minibatch loss at step 1500: 7.165316
Minibatch accuracy: 84.4%
Validation accuracy: 78.8%
Minibatch loss at step 2000: 10.387121
Minibatch accuracy: 78.9%
Validation accuracy: 80.8%
Minibatch loss at step 2500: 3.324355
Minibatch accuracy: 80.5%
Validation accuracy: 80.8%
Minibatch loss at step 3000: 4.396149
Minibatch accuracy: 89.8%
Validation accuracy: 81.3%
Test accuracy: 88.9%
测试结果正确率达到了88.9%
这样一个简单的神经网络就搭建好了。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值