笔记基于北大的tensorflow2.0教程,将课程的一些重要内容记下来,方便于学习。
一、常用函数
强制数据类型转换——tf.cast(张量名,dtype=数据类型)
找张量最小值——tf.reduce_min(张量名)
找张量最大值——tf.reduce_max(张量名)
二维张量中,可以通过调整axis控制执行维度;axis=1表示横向操作;axis=0表示纵向操作 。
计算张量指定维度的平均值——tf.reduce_mean(张量名,axis=操作轴),如果不指定axis,则对所有元素进行操作
计算张量指定维度的和——tf.reduce_sum(张量名,axis=操作轴),如果不指定axis,则对所有元素进行操作
将变量标记为可训练——tf.Variable(初始值);被标记的变量会在反向传播中记录梯度信息。
二、常用计算函数
四则运算:tf.add(张量1,张量2),tf.subtract(张量1,张量2),tf.multiply(张量1,张量2),tf.divide(张量1,张量2);维度相同,才可以进行四则运算
示例:
import tensorflow as tf
a = tf.ones([1,3])
b = tf.fill([1,3],3.)
print(a)
print(b)
print(tf.add(a,b))
print(tf.subtract(a,b))
print(tf.multiply(a,b))
print(tf.divide(a,b))
tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
tf.Tensor([[0.33333334 0.33333334 0.33333334]], shape=(1, 3), dtype=float32)
平方、次方与开方:tf.square(张量名),tf.pow(张量名,n次方),tf.sqrt(张量名)
矩阵乘法:tf.matmul(矩阵1,矩阵2)
示例:
import tensorflow as tf
a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print(tf.matmul(a,b))
结果
tf.Tensor(
[[6. 6. 6.]
[6. 6. 6.]
[6. 6. 6.]], shape=(3, 3), dtype=float32)
三、输入特征与标签配对
生成输入特征/标签对,构建数据集
data = tf.data.Dataset.from_tensor_slices(输入特征,标签)
示例:
import tensorflow as tf
features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
for element in dataset:
print(element)
结果
(<tf.Tensor: id=9, shape=(), dtype=int32, numpy=12>, <tf.Tensor: id=10, shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: id=11, shape=(), dtype=int32, numpy=23>, <tf.Tensor: id=12, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=13, shape=(), dtype=int32, numpy=10>, <tf.Tensor: id=14, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=15, shape=(), dtype=int32, numpy=17>, <tf.Tensor: id=16, shape=(), dtype=int32, numpy=0>)
可以看出,标签与特征配对成功啦!!!
四、求导
1.with结构中利用tf.GradientTapeq()求张量梯度,结构如下:
with tf.GradientTapeq() as tape:
计算过程
grad = tape.gradient(函数,对谁求导)
示例:
import tensorflow as tf
with tf.GradientTape() as tape:
w = tf.Variable(tf.constant(3.0))
loss = tf.pow(x, 2)
grad = tape.gradient(loss, w)
print(grad)
运行结果:tf.Tensor(6.0, shape=(), dtype=float32)
2.enumerate(列表名)
enumerate可遍历每个元素,常在for循环中使用
示例:
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, element)
结果:
0 one
1 two
2 three
3.独热码(one-hot encoding)表示标签
1表示是,0表示非
tf.one_hot()函数将待转换数据转换为one-hot形式的数据输出。
tf.one_hot(待转换数据,depth=几分类)
示例:
import tensorflow as tf
classes = 3
labels = tf.constant([1, 0, 2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels, depth=classes)
print("result of labels1:", output)
print("\n")
结果:
result of labels1: tf.Tensor(
[[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)
4.输出概率
tf.nn.softmax()可以将n分类的n输出转换为概率输出
示例:
import tensorflow as tf
y = tf.constant([1.01, 2.01, -0.66])
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:", y_pro) # y_pro 符合概率分布
print("The sum of y_pro:", tf.reduce_sum(y_pro)) # 通过softmax后,所有概率加起来和为1
结果:
After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046 0.0481878 ], shape=(3,), dtype=float32)
The sum of y_pro: tf.Tensor(1.0, shape=(), dtype=float32)
5.assign_sub(w要自减的大小n) 并将w-n返回
使用前要利用tf.Variable将变量定义为可更新(可训练)。
示例:
import tensorflow as tf
x = tf.Variable(4)
x.assign_sub(1)
print("x:", x) # 4-1=3
结果:
x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
6.tf.argmax(张量名,axis=操作轴)返回指定方向最大值的索引
示例:
import numpy as np
import tensorflow as tf
test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print("test:\n", test)
print("每一列的最大值的索引:", tf.argmax(test, axis=0)) # 返回每一列最大值的索引
print("每一行的最大值的索引", tf.argmax(test, axis=1)) # 返回每一行最大值的索引
结果:
test:
[[1 2 3]
[2 3 4]
[5 4 3]
[8 7 2]]
每一列的最大值的索引: tf.Tensor([3 3 1], shape=(3,), dtype=int64)
每一行的最大值的索引 tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)