常用函数使用(1)
1.数据类型转换函数
# 定义一个张量
a = tf.constant([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]], dtype=tf.int64)
# 强制转换类型函数
b = tf.cast(a, tf.float32)
# reduce_max查找张量中最大的数,axis=x表示对对应的行或者列求和
# 本例中为二维张量,0对应的对列进行操作,1表示对行进行操作
# 如果没有设置axis则表示在整个张量中进行操作。
Max_col = tf.reduce_max(b, axis=0)
Max_val = tf.reduce_max(b)
# reduce_max查找张量中最小的数或者行列
min_row = tf.reduce_min(b, axis=1)
min_val = tf.reduce_min(b)
#根据操作轴求出对应操作轴的均值,没有设置axis时,得到总的平均值。
mean_col = tf.reduce_mean(b, axis=0)
# 对张量进行求和,axis没设置时,得到张量所有元素的和
sum_row = tf.reduce_sum(a, axis=1)
#输出结果b
tf.Tensor([6. 7. 8.], shape=(3,), dtype=float32)
tf.Tensor(8.0, shape=(), dtype=float32)
tf.Tensor([0. 3. 6.], shape=(3,), dtype=float32)
tf.Tensor(0.0, shape=(), dtype=float32)
tf.Tensor([3. 4. 5.], shape=(3,), dtype=int64)
tf.Tensor([ 3 12 21], shape=(3,), dtype=int64)
2.标记可训练的参数的函数
被标记的参数会在反向传播中记录梯度信息
w = tf.Variable(tf.random.normal([2, 2], mean=0.5, stddev=1))
#输出结果
<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[-1.0614961 , -0.11344022],
[-0.23131639, 1.2779665 ]], dtype=float32)>
3.数学运算函数
数的加减乘除,次方,平方,开方
注:进行数学运算时,必须保证shape,dtype相同才能运算
x = tf.ones([2, 3])
y = tf.fill([2, 3], 5.)
add = tf.add(x, y)
sub = tf.subtract(x, y)
mul = tf.multiply(x, y)
dvd = tf.divide(y, x)
pou = tf.pow(y, 3)
sqr = tf.square(y)
sqt = tf.sqrt(y)
#输出结果
tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
tf.Tensor([[5. 5. 5.]], shape=(1, 3), dtype=float32)
tf.Tensor([[6. 6. 6.]], shape=(1, 3), dtype=float32)
tf.Tensor([[-4. -4. -4.]], shape=(1, 3), dtype=float32)
tf.Tensor([[5. 5. 5.]], shape=(1, 3), dtype=float32)
tf.Tensor([[5. 5. 5.]], shape=(1, 3), dtype=float32)
tf.Tensor([[125. 125. 125.]], shape=(1, 3), dtype=float32)
tf.Tensor([[25. 25. 25.]], shape=(1, 3), dtype=float32)
tf.Tensor([[2.236068 2.236068 2.236068]], shape=(1, 3), dtype=float32)
矩阵乘法运算
x = tf.ones([2, 3])
y = tf.fill([3, 2], 5.)
mat = tf.matmul(x, y)
# 输出结果
tf.Tensor(
[[15. 15.]
[15. 15.]], shape=(2, 2), dtype=float32)
4.求导函数
使用函数,对指定的变量进行求导,注意变量类型。
with tf.GradientTape() as tape:
w = tf.Variable(tf.constant(3.0))
loss = tf.pow(w, 2)
grad = tape.gradient(loss, w)
print(grad)
输出结果:
tf.Tensor(6.0, shape=(), dtype=float32)
5.特征标签配对函数
使用Dataset.from_tensor_slices((特征,标签)),对特征和标签进行配对,构建数据集
feature = tf.constant([9, 8, 7, 6])
label = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((feature, label))
print(dataset)
for element in dataset:
print(element)
# 输出结果
<TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)>
(<tf.Tensor: id=9, shape=(), dtype=int32, numpy=9>
, <tf.Tensor: id=10, shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: id=11, shape=(), dtype=int32, numpy=8>
, <tf.Tensor: id=12, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=13, shape=(), dtype=int32, numpy=7>
, <tf.Tensor: id=14, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=15, shape=(), dtype=int32, numpy=6>
, <tf.Tensor: id=16, shape=(), dtype=int32, numpy=0>)