
参考《TensorFlow 深度学习》和 《TensorFlow 学习指南》等书籍
学习新语言也好、新框架也好,我们都喜欢写一个 Hello World 开始。
第一个 Hello TensorFlow
import tensorflow as tf
定义常量为 Hello TensorFlow
hello = tf.constant("Hello TensorFlow")
sess = tf.Session()
print(sess.run(hello))
在 TensorFlow 中所有的计算都需要在Session(会话)中完成。这个大家一定要留心,否则就会出现问题得不到想要的效果。
第二个 Hello TensorFlow
h = tf.constant("Hello")
t = tf.constant("TensorFlow")
ht = h + t
with tf.Session() as sess:
result = sess.run(ht)
print(result)
h = tf.constant("Hello")
w = tf.constant(" world")
hw = tf.add(h,w)
mul = tf.multiply(a,b)
with tf.Session() as sess:
result = sess.run(hw)
print(result)
mul = tf.multiply(a,b)
with tf.Session() as sess:
result = sess.run(mul)
print(result)
TensorFlow 的操作符
定义操作符
a = tf.constant(5)
b = tf.constant(3)
c = tf.constant(2)
print(a)
Tensor("Const:0", shape=(), dtype=int32)
输出一个 a 的类型为 Tensor ,Tensor 类似一个对象,dtype 为数据类型。
mul = tf.multiply(a,b)
在 TensorFlow 中我们运算操作定义有区别于其他我们熟悉语言,输出 mul 为一个对象,而非 a 和 b 乘积的结果,而是 Tensor 节点,需要执行运算后才能得到结果。如果写成 a * b 则是 tf.multiply(a,b) 缩写。
Tensor("Mul:0", shape=(), dtype=int32)
使用 with 语句打开会话能够保证一旦所有计算完成后会话将自动关闭。
a = tf.constant(5)
b = tf.constant(3)
c = tf.constant(2)
# f = (a + b) * c
ab = tf.add(a,b)
f = tf.multiply(ab,c)
with tf.Session() as sess:
result = sess.run(f)
print(result)
当我们输入 Tensor(在这里可以叫张量或者节点)到会话进行计算,方法调用时会完成一组运算,从该节点根据依赖进行计算出所有节点。
网友评论