单张量api
- 强制类型转换
a = tf.constant([1.2,3.4,5.6],dtype=tf.float64)
#强制类型转换
b = tf.cast(a,dtype=tf.int32)
- 求张量最小值
min = tf.reduce_min(b)
- 求张量最大值
max = tf.reduce_max(b)
- 求均值求和以及axis的意义
a = tf.constant( [[1,2,3],[4,5,6]] )
#通过指定axis可以控制计算的对象维度
#age. 使用二维张量,axis=0则对列元素进行相应计算,=1则对行元素进行相应计算
#求均值
mean = tf.reduce_mean(a)
#求和
sum = tf.reduce_sum(a,axis=0)
输出结果
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor([5 7 9], shape=(3,), dtype=int32)
- 初始化可训练变量
w = tf.Variable(tf.random.truncated_normal([2,3],0,0.1))
张量间运算api
同维度张量运算
- 加减乘除
a = tf.constant( [[1,2,3],[4,5,6]] )
b = tf.constant( [[1,2,3],[4,5,6]] )
add = tf.add(a,b)
sub =tf.subtract(a,b)
mul = tf.multiply(a,b)
div = tf.divide(a,b)
该运算为相同下标元素进行的运算,运算结果如下
[[ 2 4 6]
[ 8 10 12]], shape=(2, 3), dtype=int32)
tf.Tensor(
[[0 0 0]
[0 0 0]], shape=(2, 3), dtype=int32)
tf.Tensor(
[[ 1 4 9]
[16 25 36]], shape=(2, 3), dtype=int32)
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float64)
- 平方,次方,开方
squ = tf.square(a)
pow = tf.pow(a,3)
sqr = tf.sqrt(tf.cast(mul,dtype = tf.float64));
矩阵运算
- 矩阵乘法
#矩阵乘法前提a列数=b行数
a = tf.constant([[1,2],[3,4],[5,6]]) #三行两列
b = tf.constant([[1,2,3,4],[4,3,2,1]]) #两行四列
mat = tf.matmul(a,b)
print(mat)
计算结果
[[ 9 8 7 6]
[19 18 17 16]
[29 28 27 26]], shape=(3, 4), dtype=int32)
数据处理api
- 将特征和标签组成数据集
特征张量第一维度和标签组成数据集
features = tf.constant([[1,2],[3,4]])
label = tf.constant([0.1,0.2])
dataset = tf.data.Dataset.from_tensor_slices((features,label))
- 求张量的梯度
grad = tap.gradient(待求导函数,求偏导变量)
with tf.GradientTape() as tap:
w =tf.Variable(tf.constant(5.0))
loss = tf.pow(w,2)
grad = tap.gradient(loss,w)
- python枚举
将遍历对象的每一个元素和序号进行组合
seq = ["a","b","c"]
for i,elem in enumerate(seq):
print(i,elem)
- 独热码
在分类问题中对标签进行转化
classes = 3
labels = tf.constant([1,1,2,3])
output = tf.one_hot(labels,classes)
print(output)
输出如下
tf.Tensor(
[[0. 1. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]], shape=(4, 3), dtype=float32)
- softmax
使n分类的n个输出符合概率分布
y = tf.constant([1,4,-9],dtype = tf.float64)
y_rate = tf.nn.softmax(y)
- Variable数值更新
w = tf.Variable(6)
#等效于w = w - 1
w.assign_sub(1)
- 获取沿张量指定维度最大值索引
axis=0为获取列索引
axis=1为获取行索引
a = tf.constant([[1,2],[2,3],[3,4]])
idx = tf.argmax(a,axis = 0)