1. 构造计算图
In [1]: import tensorflow as tf
H:\Software\Anaconda\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
In [2]: a = tf.constant(1,dtype=tf.float32,shape=[1,1],name="a") #‘a’,‘b’,‘c’等都是TensorFlow的(张量)对象,可以理解为一个一维数组
In [3]: print(a)
Tensor("a:0", shape=(1, 1), dtype=float32)
In [4]: b = tf.constant(1,dtype=tf.float32,shape=[1,1],name="b") #constant函数的第一个参数表示生成常量的值,是必备参数,‘dtype’和‘shape’是非必备参数,前者表示数据类型,后者表示张量的维度,表示生成一个一行一列的矩阵常量
In [5]: print(b)
Tensor("b:0", shape=(1, 1), dtype=float32)
In [6]: c = tf.constant(1,dtype=tf.float32,shape=[1,1],name="c") #一行一列矩阵相当于普通数字,但是TensorFlow里矩阵运算速度远高于数字
In [7]: print(c)
Tensor("c:0", shape=(1, 1), dtype=float32)
In [8]: #s=a+b
In [9]: s = tf.add(a,b,name="sum")
In [10]: print(s)
Tensor("sum:0", shape=(1, 1), dtype=float32)
In [11]: #re=c*s
In [12]: re = tf.multiply(c,s,name="multiply")
In [13]: print(re)
Tensor("multiply:0", shape=(1, 1), dtype=float32)
2. 执行定义好的计算图
为了执行计算图,需要创建session(会话)对象,通过session对象的run函数执行计算图上定义的运行,这一步骤也被称为数据的取回(fetches)
In [14]: #启动与外部运算的会话,通过‘run‘函数计算定义好的图
In [15]: sees = tf.Session()
In [16]: print(sees.run(s))
[[2.]]
In [17]: print(sees.run(re))
[[2.]]
3. TensorFlow提供的变量
除了constant(常量)外,TensorFlow还提供两种变量:Variable(可变变量),placeholder(占位符)
In [3]: x = tf.Variable(0,name="counter")
In [4]: one = tf.constant(1)
In [5]: #对可变变量赋值
In [6]: update = tf.assign(x,tf.add(x,one))
In [7]: #对可变变量初始化
In [8]: init = tf.global_variables_initializer()
In [9]: sess = tf.Session()
In [10]: sess.run(init)
In [11]: print(sess.run(x))
0
In [12]: sess.run(update)
Out[12]: 1
In [13]: print(sess.run(x))
1
In [14]: sess.run(update)
Out[14]: 2
In [15]: print(sess.run(x))
2
In [16]: import numpy as np
In [17]: #定义占位符mat1和mat2
In [18]: mat1 = tf.placeholder(tf.float32,shape=[1,3],name="mat2")
In [19]: mat1 = tf.placeholder(tf.float32,shape=[3,1],name="mat1")
In [20]: mat1 = tf.placeholder(tf.float32,shape=[1,3],name="mat2")
In [21]: mat2 = tf.placeholder(tf.float32,shape=[3,1],name="mat1")
In [22]: output = tf.matmul(mat1,mat2)
In [23]: #将数据传给占位符,并进行计算
In [25]: print(sess.run([output],feed_dict={
...: mat1:np.array([1,2,3]).reshape(1,3),
...: mat2:np.array([4,5,6]).reshape(3,1)}))
[array([[32.]], dtype=float32)]