[tensorflow] 第一个模型 回归
本文来自https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/2-2-example2/
在此基础上加上了自己的笔记。
1 创建数据
首先, 我们这次需要加载 tensorflow 和 numpy 两个模块, 并且使用 numpy 来创建我们的数据.
import tensorflow as tf
import numpy as np
# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3
random.rand
numpy.random.rand(d0, d1, ..., dn)
rand函数根据给定维度生成[0,1)之间的数据,包含0,不包含1
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.rand.html
接着, 我们用 tf.Variable 来创建描述 y 的参数.
我们可以把 y_data = x_data*0.1 + 0.3
想象成 y=Weights * x + biases
, 然后神经网络也就是学着把 Weights 变成 0.1, biases 变成 0.3.
2 搭建模型
### create tensorflow structure start ###
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights*x_data + biases
WARNING:tensorflow:From C:\Anaconda\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
tf.random_uniform
从均匀分布中输出随机值.
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-rnix2gv7.html
tf.random_uniform 函数
random_uniform(
shape,
minval=0,
maxval=None,
dtype=tf.float32,
seed=None,
name=None
)
这里tf.Variable(tf.random_uniform([1], -1.0, 1.0))
意思是返回1维长度为1的张量,产生于low和high之间,产生的值是均匀分布的.
TF使用张量(tensor)表示数据,用“阶”表示张量的维度。关于这一点需要展开一下
0阶张量称为标量,表示单独的一个数
1阶张量称为向量,表示一个一维数组
2阶张量称为矩阵,表示一个二维数组
……
张量是几阶的可以通过张量右边的方括号数来判断。例如 t = [ [ [ ] ] ],显然这个为3阶
3 计算误差
loss = tf.reduce_mean(tf.square(y-y_data))
tf.reduce_mean
可跨越维度的计算张量各元素的平均值,相当于np.mean.
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-hckq2htb.html
4 传播误差
反向传递误差的工作就教给optimizer了, 我们使用的误差传递方法是梯度下降法: Gradient Descent 让后我们使用 optimizer 来进行参数的更新.
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
### create tensorflow structure end ###
5 训练
到目前为止, 我们只是建立了神经网络的结构, 还没有使用这个结构. 在使用这个结构之前, 我们必须先初始化所有之前定义的Variable, 所以这一步是很重要的!
init = tf.global_variables_initializer()
接着,我们再创建会话 Session. 我们会在下一节中详细讲解 Session. 我们用 Session 来执行 init 初始化步骤. 并且, 用 Session 来 run 每一次 training 的数据. 逐步提升神经网络的预测准确性.
sess = tf.Session()
sess.run(init) # Very important
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(Weights), sess.run(biases))
0 [-0.07752031] [0.4923944]
20 [0.04362428] [0.32690617]
40 [0.0855123] [0.30691448]
60 [0.09627688] [0.30177692]
80 [0.09904323] [0.30045664]
100 [0.09975414] [0.30011734]
120 [0.09993681] [0.30003017]
140 [0.09998377] [0.30000776]
160 [0.09999581] [0.300002]
180 [0.09999893] [0.30000052]
200 [0.09999973] [0.30000013]
- weight是tensor(张量),无法直接输出,只能通过sess.run输出
- 采用with语句包装,可以在结束with语句块的时候,自动销毁会话的资源