1. eager模式基础
x = [[2,]] m = tf.matmul(x,x) print(m) • 1 • 2 • 3
tf.Tensor([[4]], shape=(1, 1), dtype=int32)
tf.matmul(x,x)的返回值是tesor对象,它是一个张量,它就是高维数组它有两个特征,一个是shape和dtype,与numpy(ndarry)不同的是张量是不可变的对象,它不仅可以存储在内存当中,还可以存储在GPU显存当中。
我们还可以将tensor和numpy的array相互转化。
a = tf.constant([[1,2],[3,4]])#建立一个常量 print(a) b = tf.add(a,1)#对他进行加法 print(b) print(a.numpy()) print(b.numpy())
tf.Tensor( [[1 2] [3 4]], shape=(2, 2), dtype=int32) tf.Tensor( [[2 3] [4 5]], shape=(2, 2), dtype=int32) [[1 2] [3 4]] [[2 3] [4 5]]
以上是从tensor转换为了numpy,我们怎么转换tensor类型呢,利用tf.convert_to_tensor()方法即可。
import numpy as np d = np.array([[5,6], [7,8]]) g = tf.convert_to_tensor(d) print(g)
tf.Tensor( [[5 6] [7 8]], shape=(2, 2), dtype=int64)
2 变量与自动微分计算
变量的定义域tf.1.x版本相似,方法tf.Variable()专门用于创建变量,它可以参与运算,其计算的值为tensor类型。
v = tf.Variable(0.0)#用于专门创建变量,和tf1.0相似 print(v + 1) #转换为tensor,我们可以直接使用它的值
tf.Tensor(1.0, shape=(), dtype=float32)
我们怎么改变变量的值?有一种方法是assign(),这是一个赋值的操作,我们也可以用read_value()方法把变量的值读取出来,读取出来它就变称了tensor类型。
print(v) v.assign(10) #我们就把变量的值给改变了 print(x) v.assign_add(1)#我们使用assign_add() print(v) print(v.read_value())
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=11.0> [[2]] <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=11.0> tf.Tensor(11.0, shape=(), dtype=float32)
对于微分的计算我们需要tf.GradientTape()这个上下文管理器,自动跟踪运算。
w = tf.constant([[3.0]])# 必须是float数据类型,记录这个计算的过程,自动跟踪变量的运算 with tf.GradientTape() as t: t.watch(w) #让t跟踪常量的运算 loss = w * w dloss_dw = t.gradient(loss,w) print(dloss_dw)
tf.Tensor([[6.]], shape=(1, 1), dtype=float32)
需要注意的微分计算,当我们计算一次微分后,记录已经释放,如果还需要再求微分,我们需要将tf.GradientTape()的参数persistent=True。
w = tf.constant([[3.0]])# 必须是float数据类型,记录这个计算的过程,自动跟踪变量的运算 with tf.GradientTape(persistent=True) as t: t.watch(w) #让t跟踪常量的运算 y = w * w z = y * y dy_dw = t.gradient(y,w) print(dy_dw) dz_dw = t.gradient(z,w) print(dz_dw)
tf.Tensor([[6.]], shape=(1, 1), dtype=float32) tf.Tensor([[108.]], shape=(1, 1), dtype=float32)