Tensorflow(六) —— Tensor如何进行数学运算
1 operation type
1.1 element wise (元素级运算)
+ - * /
1.2 matrix wise
- 矩阵相乘并行计算,一次完成多个矩阵相乘
- [b,3,4]@[b,4,5]
- 相当于多个[3,4]和[4,5]同时进行相乘
- 最后的得到[b,3,5]
1.3 dim wise
- 对某个维度进行操作(轴操作)
- mean max min sum
2 + - * / // %
"""
a = tf.fill([2,2],3.5)
b = tf.ones([2,2])
print("a:",a)
print("b:",b)
print("a+b:",a+b)
print("a-b:",a-b)
print("a*b",a*b)
print("a/b:",a/b)
print("a//b:",a//b)
print("a%b:",a%b)
3 tf.math.log 、 tf.exp
a = tf.fill([2,2],4.)
print("log(a):",tf.math.log(b))
print("exp(a):",tf.exp(a))
"""
注意log方法在math这个包里面
log是指以e为底的
计算其他对数 可用log(a)/log(b)
"""
print(tf.math.log(100.)/tf.math.log(10.))
4 pow、sqrt
a = tf.fill([2,2],3.)
b = tf.pow(a,2)
c = a**2
print("b、c:",b,"\n",c)
d = tf.sqrt(a)
print("d:",d)
5 @ 、 matmul
a = tf.fill([2,2],3.)
b = tf.fill([2,2],2.)
print("a@b:",a@b)
print("a@b:",tf.matmul(a,b))
c = tf.random.normal([8,3,4])
d = tf.random.normal([8,4,5])
print("c@d:",(c@d).shape)
e = tf.random.uniform([4,5])
print("c@e:",(c@e).shape)
# 用broadcast实现
f = tf.broadcast_to(e,d.shape)
print("c@f:",(c@f).shape)
本文为参考龙龙老师的“深度学习与TensorFlow 2入门实战“课程书写的学习笔记
by CyrusMay 2022 04 06