初识TensorFlow

TensorFlow 一词是Google工程师臆造的一个词,Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow是张量从图的一端流到另一端的计算过程
TensorFlow的运行机制属于'定义'与'运行'相分离,操作层面上讲抽象成两种:模型构建、模型运行

构建模型中的概念:

张量 tensor 数据,即某一类型的多维数组
变量 Variable   常用于定义模型中的参数,是通过不断训练得到的值
占位符 placeholder  输入变量的载体,理解成定义函数是的参数
图中的操作节点 operation Op  一个Op获得0个或多个tensor,执行计算,输出额外的0个或多个tensor                      

构建模型是在一个'图'中完成的, 一个图代表一个计算任务,模型在运行时,'图'会在会话Session中被启动

计算图是一个有向图,捕获有关计算方法的指令,图中可以定义许多计算节点。

import Tensorflow as tf
with tf.Session() as sess:  # with session 用法最常见,当程序结束后自动关闭session, 沿用了python的用法
    node1 = tf.constant(3., dtype=tf.float32)  # constant(value, dtype=None, shape=None, name="Const", verify_shape=False)
    node2 = tf.constant(4.)
    tensor = sess.run([node1, node2]) # 方法执行后,返回的是一个tensor. 在python中,返回的是numpy的ndarray对象。
    print(node1, node2)
    print(tensor)

1)程序首先引入 tensorflow,这个时候就会建立一张图,一张孤独而无助的图,空空如也

                                                       

2)通过 with 语法启动Session会话,也可以通过 sess = tf.Session() 来开启会话

3)通过 tf.constant() 定义了两个常量节点,这个时候图中就出现了两个节点,图不再孤单

                                                        

4)通过 sess.run() 方法返回两个常量的值,

5)打印两个常量的指针,以及打印 run 方法返回的tensor对象

上面的程序运行结果:

Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32)
[3.0, 4.0]

输出的第一行是两个 tf.Tensor 对象,这两个tensor对象只是两个指针,指向刚创建的两个常量,

第二行是Tensor对象的值。

上面只是一个简单的例子,下面看一个稍微复杂点的例子。

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
add_t = a + b
print(sess.run(add_t, {a: 3., b: 4.}))
print(sess.run(add_t, feed_dict={a: [2., 3.], b: [4., 5.]}))

这段程序只是通过占位符定义了两个变量,然后定义了一个加法运算。

还涉及到了Session与图交互的两种数据流向机制:

1)注入机制(feed): 通过占位符向模式中传入数据
2)取回机制(fetch): 从模式中得到结果

输出结果如下:

7.0
[6. 8.]

session的创建方式除了上面的一种,还有两种方式:

1)交互式:sess = tf.interactiveSession()

2)Supervisor方式:该方式更高级更复杂,可以自动管理session中的具体任务

下面是一个计算线性模型 y=w*x+b 的简单例子,我们一步一步的来实现一下:

import tensorflow as tf           # 引入 tensorflow 库
#定义系数 w 与偏移量 b
w = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# 通过占位符定义 x ,后面会赋值
x = tf.placeholder(dtype=tf.float32)
# 定义线性模型
linear_model = w*x+b
# 初始化全局变量
init = tf.global_variables_initializer()
sess.run(init)
# 将 x 值传给模型,计算
print(sess.run(linear_model, feed_dict={x: [1, 2, 3, 4]}))
# [0.  0.3   0.6   0.90000004]
# 通过占位符定义 y ,后面会赋值
y = tf.placeholder(tf.float32)
# 计算值与实际值之间的差得平方
deltas = tf.square(linear_model - y)
# 计算总的误差
loss = tf.reduce_sum(deltas)
# 计算 loss
print('loss func: ', sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
# loss func:  23.66
# ft.assign 变量重新赋值
ficW = tf.assign(w, [-1.])
ficB = tf.assign(b, [1.])
sess.run([ficW, ficB])
print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
# [ 0. -1. -2. -3.]
# 0.0
# 定义学习率
learning_rate = 0.01
# 定义梯度下降函数
optimizer = tf.train.GradientDescentOptimizer()
# 通过梯度下降函数最小化总的误差
train = optimizer.minimize(loss)
# 初始化变量
sess.run(init)
# 优化参数
for i in range(1000):
    sess.run(train, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})
#输出优化后的参数
print(sess.run([w, b]))
# [array([-0.9999969], dtype=float32), array([0.9999908], dtype=float32)]

下面是一个完整的训练线性回归模型

# Model parameters
w = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = w * x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y))  # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)  # reset values to wrong
for i in range(1000):
    sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([w, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))

猜你喜欢

转载自blog.csdn.net/qq_42413820/article/details/80897736