一、算术操作(+,-,*,/,//,%)
(1)tensor-tensor操作(element-wise)
a = tf.ones([2, 2])
b = tf.fill([2, 2], 2.)
add = a + b
minus = a - b
multiply = a * b #点乘
divide = a / b
divideExactly = a // b #整除
surplus = b % a #取余
(2)tensor-scalar操作
#scalar-tensor操作。
#对tensor中所有element执行同样的操作(+,-,*,/)
#加法
add=a+2
#减法
minus=a-2
#乘法
multiply=a*2
#除法
divide=a/2
logarithm = tf.math.log(a) #以e为底数的对数
exponent = tf.exp(a) #以e为底数的指数
log8 = tf.math.log(8.) / tf.math.log(2.) # 以2为底数,8的对数
print("logarithm:", logarithm)
print("exponent:", exponent)
print("log8:", log8)
power1 = tf.pow(b, 3) #b^3
power2 = b ** 3 #b^3
sqrt = tf.sqrt(b) #b开平方根
print("power1:", power1)
print("power2:", power2)
print("sqrt:", sqrt)
二、矩阵运算
a = tf.ones([2, 2])
b = tf.fill([2, 2], 2.)
matrixMultiply1 = a @ b #矩阵相乘
matrixMultiply2 = tf.matmul(a, b)#矩阵相乘
print("matrixMultiply1:", matrixMultiply1)
print("matrixMultiply2:", matrixMultiply2)
三、多维张量运算
array1 = tf.ones([4, 2, 3])
array2 = tf.fill([4, 3, 5], 2.)
matrixMultiply3 = array1 @ array2
print("matrixMultiply3:", matrixMultiply3)
#matrixMultiply3.shape = [4, 2, 5]