小花猫

TensorFlow入门

提纲

  • tf.Session 里面进行运算。
  • 通过 tf.constant() 创建常量 tensor。
  • tf.placeholder()feed_dict得到输入。
  • 应用 tf.add()tf.subtract()tf.multiply()tf.divide()函数进行数学运算。
  • 学习如何用 tf.cast()进行类型转换。

Session

TensorFlow 的 api 构建在 computational graph 的概念上,它是一种对数学运算过程进行可视化的方法。

1
2
3
4
5
6
7
8
9
10
# Hello World
import tensorflow as tf

# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')

with tf.Session() as sess:
# Run the tf.constant operation in the session
output = sess.run(hello_constant)
print(output)

这段代码用 tf.Session 创建了一个 sess 的 session 实例。然后 sess.run()函数对 tensor 求值,并返回结果。

tf.constant() 返回的 tensor 是一个常量 tensor,因为这个 tensor 的值不会变。

输入

tf.placeholder()feed_dict

1
2
3
4
5
6
x = tf.placeholder(tf.string)
y = tf.placeholder(tf.int32)
z = tf.placeholder(tf.float32)

with tf.Session() as sess:
output = sess.run(x, feed_dict={x: 'Test String', y: 123, z: 45.67})

数学运算

tf.add()
tf.substract()
tf.multiply

类型转换

tf.cast(tf.constant(2.0), tf.int32)

TensorFlow 里的权重和偏差

  • tf.Variable 类创建一个 tensor,其初始值可以被改变
    使用 tf.global_variables_initializer() 函数来初始化所有可变 tensor。它会从 graph 中初始化所有的 TensorFlow 变量。你可以通过 session 来调用这个操作来初始化所有上面的变量。用 tf.Variable 类可以让我们改变权重和偏差,但还是要选择一个初始值。
1
2
3
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
  • 使用 tf.truncated_normal()函数从一个正态分布中生成随机数。
  • tf.truncated_normal() 返回一个 tensor,它的随机值取自一个正态分布,并且它们的取值会在这个正态分布平均值的两个标准差之内。
  • tf.zeros() 函数返回一个都是 0 的 tensor。