Getting Started With TensorFlow

TensorFlow provides multiple APIs.

The lowest level API--TensorFlow Core-- provides you with complete programming control. The higher level APIs are built on top of TensorFlow Core. These higher level APIs are typically easier to learn and use than TensorFlow Core.

Tensors

Tensor是N维数组,一个tensor的rank指其维度。

TensorFlow Core tutorial

The Computational Graph 计算图

可以将Tensorflow的核心程序理解为两个不同的部分:

  1. Building the computational graph 构建计算图
  2. Running the computational graph 运行计算图

计算图是指由一系列tensorflow运算构成的不同节点的图。每个节点接受0个或多个tensor,输出1个tensor。一种节点是常量,不需要输入。

node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)
Tensor("Const_1:0", shape=(), dtype=float32) Tensor("Const_2:0", shape=(), dtype=float32)

print节点并不会将数值打印出来。只有通过session运行了计算图,才能对值进行计算。

sess = tf.Session()
print(sess.run([node1, node2]))
[3.0, 4.0]

将节点通过运算连接起来,可以进行复杂一些的计算(运算也是节点),比如两个常量相加,生成新的图:

node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ", sess.run(node3))
node3:  Tensor("Add:0", shape=(), dtype=float32)
sess.run(node3):  7.0

placeholder 可以接受外部数据,运行的时候通过feed_dict将值传入.

a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b # + provides a shortcut for tf.add(a, b)

print(sess.run(adder_node, {a:3, b:4}))
print(sess.run(adder_node, {a: [1, 3], b: [2, 4]}))
7.0
[ 3.  7.]

机器学习需要模型能接受赋值。训练模型,需要能够根据同样的赋值生成不同的输出。Variable 用来训练图的参数。构建的时候需要声明类型和初始值

W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b

init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
[ 0.          0.30000001  0.60000002  0.90000004]

注意:init对所有的变量初始化;只有运行sess.run后,变量才会初始化

上述代码构建了线性模型。但是还没有对模型进行评估。评估一个模型,需要有y作为placehoder来存储期望值,此外还需要损失函数。

y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
23.66

assign可以手动给变量赋值

fixW = tf.assign(W, [-1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
0.0

tf.train API

tensorflow 提供了一些optimizers来最小化损失函数。最简单的optimizer是梯度下降。

optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
sess.run(init) # reset values to incorrect defaults.

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.99999082], dtype=float32)]

tf.estimator

tf.estimator是tensorflow提供的high level库,简化机器学习机制,包括:

  • running training loops
  • running evaluation loops
  • managing data sets

results matching ""

    No results matching ""