Tensorflow_入门学习_2_一个神经网络栗子
3.0 A Neural Network Example
载入数据:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
ont_hot:将数据集的标签转换为ont-hot编码, i.e. “4”:[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]。
3.1 Setting things up
1.为训练数据创建placeholder变量
# Python optimisation variables
learning_rate = 0.5
epochs = 10
batch_size = 100 # declare the training data placeholders
# input x - for 28 x 28 pixels = 784
x = tf.placeholder(tf.float32, [None, 784])
# now declare the output data placeholder - 10 digits
y = tf.placeholder(tf.float32, [None, 10])
2.创建一个三层神经网络的weights和bias
# now declare the weights connecting the input to the hidden layer
W1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([300]), name='b1')
# and the weights connecting the hidden layer to the output layer
W2 = tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([10]), name='b2')
hidden layer有300个神经元。
tf.random_normal([784, 300], stddev=0.03):使用平均值为0,标准差为0.03的随机正态分布初始化weights和bias变量。
3.创建hidden layer的输入和激活函数:
# calculate the output of the hidden layer
hidden_out = tf.add(tf.matmul(x, W1), b1)
hidden_out = tf.nn.relu(hidden_out)
tf.matmul:矩阵乘法
这两行代码与下面两个等式等价:

4.创建输出层:
# now calculate the hidden layer output - in this case, let's use a softmax activated
# output layer
y_ = tf.nn.softmax(tf.add(tf.matmul(hidden_out, W2), b2))
这里使用softmax激活函数。
5.引入一个loss function用于反向传播算法优化上述weight和bias。这里使用交叉熵误差

y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999)
cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped) + (1 - y) * tf.log(1 - y_clipped), axis=1))
第一行:
将y_转换为剪辑版本(clipped version),取值位于1e-10,0.999999之间,是为了避免在训练时遇见log(0)而返回NaN并中止训练。
第二行:
tensor间的标量运算* / + -,
tensor*tensor:对两个tensor中的对应位置元素都进行运算。
tensor*scaler:对tensor中每个元素乘scaler。
tf.reduce_sum:按给定的坐标进行加和运算:
y * tf.log(y_clipped) + (1 - y) * tf.log(1 - y_clipped) 的运算结果是一个m*10的tensor。第一求和运算是对下标j求和,所以是对tensor的第2维进行求和,所以axis=1;得到结果是1*10的tensor。
tf.reduce_mean :对任何tensor求均值。
6.创建一个optimiser:
# add an optimiser
optimiser = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)
使用tensorflow提供的梯度下降优化器。
7.初始化所有变量和衡量准确度的运算。
# finally setup the initialisation operator
init_op = tf.global_variables_initializer() # define an accuracy assessment operation
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.equal:根据传入参数判断是否相等,返回True or False。
tf.argmax(tensor, axis):根据axis返回tensor中的最大值。返回的也是一个tensor。
correct_prediction:m*1的boolean tensor。
将其转换为float,然后计算平均值,就是准确率。
8.执行训练:
# start the session
with tf.Session() as sess:
# initialise the variables
sess.run(init_op)
total_batch = int(len(mnist.train.labels) / batch_size)
for epoch in range(epochs):
avg_cost = 0
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)
_, c = sess.run([optimiser, cross_entropy], feed_dict={x: batch_x, y: batch_y})
avg_cost += c / total_batch
print("Epoch:", (epoch + 1), "cost =", "{:.3f}".format(avg_cost))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))
使用mini-batch gradient descent。
Tensorflow_入门学习_2_一个神经网络栗子的更多相关文章
- Tensorflow_入门学习_1
1.0 TensorFlow graphs Tensorflow是基于graph based computation: 如: a=(b+c)∗(c+2) 可分解为 d=b+c e=c+2 a=d∗e ...
- Flask入门学习——自定义一个url转换器
我们知道,flask的url规则是可以添加变量部分的,这个参数变量是写在尖括号里的,比如:/item/<id>/,如果需要指出参数的类型要符合<converter:vai ...
- 【PyTorch深度学习60分钟快速入门 】Part3:神经网络
神经网络可以通过使用torch.nn包来构建. 既然你已经了解了autograd,而nn依赖于autograd来定义模型并对其求微分.一个nn.Module包含多个网络层,以及一个返回输出的方法f ...
- Swift入门学习之一常量,变量和声明
版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请表明出处:http://www.cnblogs.com/cavalier-/p/6059421.html Swift入门学习之一常量,变量和 ...
- 深度学习之卷积神经网络(CNN)
卷积神经网络(CNN)因为在图像识别任务中大放异彩,而广为人知,近几年卷积神经网络在文本处理中也有了比较好的应用.我用TextCnn来做文本分类的任务,相比TextRnn,训练速度要快非常多,准确性也 ...
- TensorFlow入门学习(让机器/算法帮助我们作出选择)
catalogue . 个人理解 . 基本使用 . MNIST(multiclass classification)入门 . 深入MNIST . 卷积神经网络:CIFAR- 数据集分类 . 单词的向量 ...
- 基于tensorflow搭建一个神经网络
一,tensorflow的简介 Tensorflow是一个采用数据流图,用于数值计算的 开源软件库.节点在图中表示数字操作,图中的线 则表示在节点间相互联系的多维数据数组,即张量 它灵活的架构让你可以 ...
- vue入门学习(基础篇)
vue入门学习总结: vue的一个组件包括三部分:template.style.script. vue的数据在data中定义使用. 数据渲染指令:v-text.v-html.{{}}. 隐藏未编译的标 ...
- Hadoop入门学习笔记---part4
紧接着<Hadoop入门学习笔记---part3>中的继续了解如何用java在程序中操作HDFS. 众所周知,对文件的操作无非是创建,查看,下载,删除.下面我们就开始应用java程序进行操 ...
随机推荐
- 4.1-4.2 基于HDFS云盘存储系统分析及hadoop发行版本
一.基于HDFS云盘存储系统 如:某度网盘 优点: *普通的商用机器 内存 磁盘 *数据的安全性 操作: *put get *rm mv *java api *filesystem 核心: *H ...
- c++中stl----map
1 map的本质 (1)关联式容器,键值对应 (2)增加和删除节点对迭代器的影响很小. (3)对于迭代器来说不可以修改键值,只能修改对应的实值. (4)map内部数据的祖居是自建一颗红黑树(或者说是平 ...
- python--flask学习1
1 windows/unix得安装 http://www.pythondoc.com/flask-mega-tutorial/helloworld.html http://www.pythondoc. ...
- 红帽系统制作yum本地源
1 首先得吐槽吐槽,机房冷就算了,不能用手机(哈哈你懂的),没有站的位置,显示屏看不清楚.就这样开始制作yum本地源. 2 记下注意得两点,以防以后会忘记 a:可能是因为红帽系统,加上是实用光盘挂载的 ...
- 洛谷 - P4861 - 按钮 - 扩展大步小步算法
https://www.luogu.org/problemnew/show/P4861 把好像把一开始b==1的特判去掉就可以AC了. #include<bits/stdc++.h> us ...
- 洛谷 P1712 [NOI2016]区间(线段树)
传送门 考虑将所有的区间按长度排序 考虑怎么判断点被多少区间覆盖,这个可以离散化之后用一棵权值线段树来搞 然后维护两个指针$l,r$,当被覆盖次数最多的点的覆盖次数小于$m$时不断右移$r$,在覆盖次 ...
- 【微服务】Dubbo初体验
一.前言 之前微服务这块只用过SpringCloud搭建,但是最近面试会被问到dubbo框架,虽然之前也学了但是都忘了,故写此博客加深印象. 二.原理简介 Dubbo是一个分布式服务框架,以及阿里巴巴 ...
- 集合:set
set 就是数学上的集合——每个元素最多只出现一次.和sort一样,自定义一个类型也可以构造set ,但是必须定义“小于”运算符. 例子: 输入一个文本,找出所有不同的单词(连续的字母序列),按字典从 ...
- Log4j2 - Unable to invoke factory method in class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFileAppender for element RollingFile
问题与分析 在使用Log4j2时,虽然可以正确读取配置文件并生成log文件,但偶然发现控制台打印了异常信息如下: 2018-12-31 17:28:14,282 Log4j2-TF-19-Config ...
- 设置导航栏 self.navigationItem.titleView 居中
喜欢交朋友的加:微信号 dwjluck2013-(void)viewDidLayoutSubviews{ [self setDisplayCustomTitleText:@"每日头条&quo ...