本笔记主要记录基于元素操作的+,-,*,/,//,%,**,log,exp等运算,矩阵乘法运算,多维tensor乘法相关运算
import tensorflow as tf
import numpy as np
tf.__version__
#element-wise运算,对应元素的+,-,*,/,**,//,%
tensor1 = tf.fill([3,3], 4)
tensor2 = tf.ones([3,3], dtype=tf.int32)
print(tensor1)
print(tensor2)
print("========tensor1 + tensor2=========\n", tensor1 + tensor2)
print("========tensor1 - tensor2=========\n", tensor1 - tensor2)
print("========tensor1 * tensor2=========\n", tensor1 * tensor2)
print("========tensor1 / tensor2=========\n", tensor1 / tensor2)
print("========tensor1 // tensor2=========\n", tensor1 // tensor2)
print("========tensor1 % tensor2=========\n", tensor1 % tensor2)
#计算tensor的元素的2次方
print("========tensor1 ** 2=========\n", tensor1 ** 2)
print("========tf.pow(tensor1, 2)===\n", tf.pow(tensor1, 2))
#开根号,tf.sqrt()
tensor1 = tf.cast(tensor1, dtype=tf.float32)
print("========tf.sqrt(tensor1)=====\n", tf.sqrt(tensor1))
#log操作,tf.math.log,注意这个函数以e为底
tensor = tf.ones([3,3], dtype=tf.float32)
print("========log(tensor)============\n", tf.math.log(tensor))
#如果要实现以任意数为底数,需要使用换底公式,下面的例子计算了以2为底,对tensor1做log操作
print("========log2(tensor1)==========\n", tf.math.log(tensor1) / tf.math.log(2.))
#指数操作,tf.exp,计算e的n次方
print("========exp(tensor1)===========\n", tf.exp(tensor1))
#矩阵乘法
#两个2x2矩阵相乘
matrix1 = tf.fill([2,2], 1)
matrix2 = tf.fill([2,2], 2)
print(matrix1, "@", matrix2)
print("==========matrix1@matrix2=========\n", matrix1 @ matrix2)
#也可以用tf.matmul()
print("==========tf.matmul(matrix1, matrix2)=\n", tf.matmul(matrix1, matrix2))
#多维tensor乘法
tensor1 = tf.ones([4, 2, 5])
tensor2 = tf.ones([4, 5, 1])
#相乘结果是一个[4,2,1]形状的tensor,具体操作是对应2*5和5*1的matrix相乘
print("==========tensor1@tensor2==========\n", tensor1@tensor2)
#相乘结果是一个[4,2,3,2]形状的tensor,具体操作是对应3*6和6*2的matrix相乘
tensor1 = tf.ones([4,2,3,6])
tensor2 = tf.ones([4,2,6,2])
print("==========tensor1@tensor2==========\n", tensor1@tensor2)
#使用broadcasting
tensor1 = tf.ones([4,2,3])
tensor2 = tf.ones([3,2])
#可以调用broadcast_to扩展,也可以直接用'@'运算符
#tensor2 = tf.broadcast_to(tensor2, [4,3,2])
print("==========tensor1@tensor2==========\n", tensor1@tensor2)
运行结果: