TensorFlow - 浅层神经网络 (shallow neural networks)-云服务器玩法...

[复制链接]
查看: 492|回复: 0

32

主题

32

帖子

104

积分

注册会员

Rank: 2

积分
104
发表于 2020-12-28 10:29:42 | 显示全部楼层 |阅读模式

实验内容

TensorFlow是由Google开发的用于数值计算的开源软件库,本实验介绍浅层神经网络在 TensorFlow 上的实现,并使用模型处理 MNIST 数据集。

免费在线实验地址:点击进入

实验资源:云服务器,没有云服务器的朋友推荐1折抢购:69元/年的阿里云服务器或者88元/年的腾讯云服务器

软件环境Ubuntu 14.04 64 位


本实验介绍浅层神经网络在 TensorFlow 上的实现,并使用模型处理 MNIST 数据集。
MNIST数据集介绍
MNIST是一个手写阿拉伯数字的数据集。
其中包含有60000个已经标注了的训练集,还有10000个用于测试的测试集。
本次实验的任务就是通过手写数字的图片,识别出具体写的是0-9之中的哪个数字。
理论知识回顾
一个典型的浅层神经网络结构如下:




  • 上图所示的是一个只有一层隐藏层的浅层神经网络
  • 我们有3个输入层节点,分别对应i[1] i[2] i[3]
  • 隐藏层有4个节点,分别对应h[0] h[1] h[2] h[3],对应的激活函数为ReLu函数
  • 对于典型的二分类任务,我们只需要1个输出节点,就是out节点,对应的激活函数是softmax函数
激活函数定义(activation function):
  1. <formula>
  2. softmax(x^i) = \left[
  3.     \begin{matrix}
  4.         p(y^i=1|x^i,\theta) \\
  5.         p(y^i=2|x^i,\theta) \\
  6.         \cdots \\
  7.         p(y^i=n|x^i,\theta)
  8.     \end{matrix}
  9.     \right] = \frac{1}{\sum_{j=1}^{k}e^{\theta_j^Tx^i}} \left[
  10.         \begin{matrix}
  11.             e^{\theta_1^Tx^i} \\
  12.             e^{\theta_2^Tx^i} \\
  13.             \cdots \\
  14.             e^{\theta_k^Tx^i}
  15.         \end{matrix}
  16.     \right]
  17. </formula>
复制代码
  1. <formula>
  2. ReLu(x) = max(0, x)
  3. </formula>
复制代码
模型设计
  • MNIST数据一共有784个输入,所以我们需要一个有784个节点的输入层。
  • 对于中间层,我们设置为1000个节点,使用的激活函数为ReLu
  • MNIST数据使用One-Hot格式输出,有0-9 10个label,分别对应是否为数字0-9,所以我们在输出层有10个节点,由于0-9的概率是互斥的,我们使用 Softmax 函数作为该层的激活函数
训练模型
任务时间:30min ~ 60min
数据准备
首先我们需要先下载MNIST的数据集。使用以下的命令进行下载:
  1. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/t10k-images-idx3-ubyte.gz
  2. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/t10k-labels-idx1-ubyte.gz
  3. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/train-images-idx3-ubyte.gz
  4. wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/train-labels-idx1-ubyte.gz
复制代码
创建代码
现在您可以在 /home/ubuntu 目录下创建源文件 shallow_neural_networks.py,内容可参考:
示例代码:/home/ubuntu/shallow_neural_networks.py

  1. import numpy as np
  2. import tensorflow as tf
  3. from tensorflow.examples.tutorials.mnist import input_data

  4. def add_layer(inputs, in_size, out_size, activation_function=None):
  5.     W = tf.Variable(tf.random_normal([in_size, out_size]))
  6.     b = tf.Variable(tf.zeros([1, out_size]) + 0.01)

  7.     Z = tf.matmul(inputs, W) + b
  8.     if activation_function is None:
  9.         outputs = Z
  10.     else:
  11.         outputs = activation_function(Z)

  12.     return outputs


  13. if __name__ == "__main__":

  14.     MNIST = input_data.read_data_sets("./", one_hot=True)

  15.     learning_rate = 0.05
  16.     batch_size = 128
  17.     n_epochs = 10

  18.     X = tf.placeholder(tf.float32, [batch_size, 784])
  19.     Y = tf.placeholder(tf.float32, [batch_size, 10])

  20.     l1 = add_layer(X, 784, 1000, activation_function=tf.nn.relu)
  21.     prediction = add_layer(l1, 1000, 10, activation_function=None)

  22.     entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=prediction)
  23.     loss = tf.reduce_mean(entropy)

  24.     optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

  25.     init = tf.initialize_all_variables()

  26.     with tf.Session() as sess:
  27.         sess.run(init)

  28.         n_batches = int(MNIST.train.num_examples/batch_size)
  29.         for i in range(n_epochs):
  30.             for j in range(n_batches):
  31.                 X_batch, Y_batch = MNIST.train.next_batch(batch_size)
  32.                 _, loss_ = sess.run([optimizer, loss], feed_dict={X: X_batch, Y: Y_batch})
  33.                 if j == 0:
  34.                     print "Loss of epochs[{0}] batch[{1}]: {2}".format(i, j, loss_)

  35.         # test the model
  36.         n_batches = int(MNIST.test.num_examples/batch_size)
  37.         total_correct_preds = 0
  38.         for i in range(n_batches):
  39.             X_batch, Y_batch = MNIST.test.next_batch(batch_size)
  40.             preds = sess.run(prediction, feed_dict={X: X_batch, Y: Y_batch})
  41.             correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))
  42.             accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))

  43.             total_correct_preds += sess.run(accuracy)

  44.         print "Accuracy {0}".format(total_correct_preds/MNIST.test.num_examples)
复制代码
代码讲解add_layer 函数
允许用户指定上一层的输出节点的个数作为input_size, 本层的节点个数作为output_size, 并指定激活函数activation_function 可以看到我们调用的时候位神经网络添加了隐藏层1和输出层
示例代码:/home/ubuntu/shallow_neural_networks.py
  1. l1 = add_layer(X, 784, 1000, activation_function=tf.nn.relu) # 添加隐藏层1
  2.     prediction = add_layer(l1, 1000, 10, activation_function=None) # 添加输出层

  3.     entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=prediction)
  4.     loss = tf.reduce_mean(entropy)
复制代码
执行代码
  1. python shallow_neural_networks.py
复制代码
运行过程中,如果出现网络错误,请重试。
运行输出:
  1. Loss of epochs[0] batch[0]: 219.555664062
  2. Loss of epochs[1] batch[0]: 4.43757390976
  3. Loss of epochs[2] batch[0]: 6.34549808502
  4. Loss of epochs[3] batch[0]: 4.51894617081
  5. Loss of epochs[4] batch[0]: 1.93666791916
  6. Loss of epochs[5] batch[0]: 1.16164898872
  7. Loss of epochs[6] batch[0]: 2.4195971489
  8. Loss of epochs[7] batch[0]: 0.164100989699
  9. Loss of epochs[8] batch[0]: 2.35461592674
  10. Loss of epochs[9] batch[0]: 1.77732157707
  11. Accuracy 0.9434
复制代码
可以看到经过10轮的训练,准确度大约在94%左右
完成实验

腾讯云
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

精彩图文



在线客服(工作时间:9:00-22:00)
400-600-6565

内容导航

微信客服

Copyright   ©2015-2019  云服务器社区  Powered by©Discuz!  技术支持:尊托网络     ( 湘ICP备15009499号-1 )