TensorFlow-0-入门

本节介绍TensorFlow最最最基本的东西。
TensorFlow

  对于TensorFlow的使用,网上已经有很多的教程,包括TensorFlow的中文社区有很好的翻译教程,只要安装好TensorFlow后,有着Python编程基础和基础的机器学习及神经网络所要求的基础数学知识,都是很好上手的。所以在这个系列的文章中,我不会着眼于环境搭建,以及详细的原理讲解,而更多的是源码级别的讲解,即对自己玩过的代码添加注释,表达感慨。

1.安装

我使用的平台是Ubuntu 16.04,安装方式是Anaconda,参照网址是:https://www.tensorfly.cn/tfdoc/get_started/os_setup.html

2.第一个测试程序

到此处认为你已经安装好了你的TensorFlow环境,我们来看官方推荐的第一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import tensorflow as tf
import numpy as np

# 使用 NumPy 生成假数据(phony data), 总共 100 个点.
x_data = np.float32(np.random.rand(2, 100)) # 生成 2*100的矩阵
y_data = np.dot([0.100, 0.200], x_data) + 0.300 //以 [0.1, 0.2]和 偏置生成虚拟的数据

# 构造一个线性模型
b = tf.Variable(tf.zeros([1])) #构建一个参数未知的线性模型 y= W*x_data + b
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0)) #由均匀分布得到初始化的W值
y = tf.matmul(W, x_data) + b #构建线性模型

# 最小化方差
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5) #下降步伐为0.5
train = optimizer.minimize(loss)

# 初始化变量
init = tf.initialize_all_variables()

# 启动图 (graph)
sess = tf.Session()
sess.run(init)

# 拟合平面
for step in range(0, 201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))

# 得到最佳拟合结果 W: [[0.100 0.200]], b: [0.300]

上面这个程序虽然很简单,但是TenSorflow的基本元素基本都涉及到了,

  • 先创建虚拟的x_data,然后设定要预测的参数值。
  • 构建线性模型
  • 构建一个TensorFlow会话
  • 执行会话
    经过200次梯度下降后,我们的预测值如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    0 [[-0.32990205  0.94440365]] [ 0.27961046]
    20 [[ 0.04070586 0.33752358]] [ 0.2542021]
    40 [[ 0.09684953 0.23069493]] [ 0.28419915]
    60 [[ 0.10159973 0.20767325]] [ 0.29472959]
    80 [[ 0.10094509 0.20211281]] [ 0.29826969]
    100 [[ 0.10037546 0.20062292]] [ 0.2994363]
    120 [[ 0.10013281 0.20019153]] [ 0.29981709]
    140 [[ 0.10004479 0.20006029]] [ 0.29994076]
    160 [[ 0.10001478 0.20001923]] [ 0.29998085]
    180 [[ 0.10000481 0.20000617]] [ 0.29999381]
    200 [[ 0.10000155 0.20000197]] [ 0.29999802]

版权声明:本文为博主原创文章,转载需声明为转载内容并添加原文地址。

原文地址:https://coderdock.com

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2017-2020 Dock
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信