练习norm,reduce_min/max,argmax/min, equal,unique等相关操作。
范数主要有三种:
import tensorflow as tf
import numpy as np
tf.__version__
#范数参考:https://blog.csdn.net/HiWangWenBing/article/details/119707541
tensor = tf.convert_to_tensor([[-3,-4],[3,4]])
tensor = tf.cast(tensor, dtype=tf.float32)
print(tensor)
#L1范数,ord=1
print("========L1 Norm============")
#不指定axis,所有元素的绝对值相加
print("====>tf.norm(tensor, ord=1):", tf.norm(tensor, ord=1))
#指定axis
print("====>tf.norm(tensor, ord=1, axis=0):", tf.norm(tensor, ord=1, axis=0))
print("====>tf.norm(tensor, ord=1, axis=1):", tf.norm(tensor, ord=1, axis=1))
#tf.norm不带参数,默认为L2范数(平方和开根号)
print("========L2 Norm============")
print("===>tf.norm(tensor):", tf.norm(tensor))
print(" sqrt(reduce_sum(square(tensor))):", tf.sqrt(tf.reduce_sum(tf.square(tensor))))
#指定axis维度上进行L2范数求解,
#对于例子中的2x2 tensor来说,axis=0表示按照行的维度进行计算
#(实际就是计算每列元素的L2范数,这里可能有点绕,抓住行的概念,
# 可以理解成矩阵的每行每个元素做平方和,然后对所有行进行相加,都是以行为基本概念即可,不拆分列)
print("====>tf.norm(tensor, axis=0):", tf.norm(tensor, axis=0))
print("====>tf.norm(tensor, axis=1):", tf.norm(tensor, ord=2, axis=1))
#inf-norm,无穷阶范数
print("========Inf Norm============")
#不带参数
print("===>tf.norm(tensor, ord=np.inf):", tf.norm(tensor, ord=np.inf))
print("===>tf.norm(tensor, ord=np.inf, axis=0):", tf.norm(tensor, ord=np.inf, axis=0))
print("===>tf.norm(tensor, ord=np.inf, axis=1):", tf.norm(tensor, ord=np.inf, axis=1))
#reduce_min/max/mean,找最小值/最大值/均值
tensor = tf.random.uniform([4,10], maxval=6, dtype=tf.int32)
tensor = tf.cast(tensor, dtype=tf.float32)
print(tensor)
#不指定维度,对所有元素进行统计
print("=====>axis not specified")
print("min:", tf.reduce_min(tensor))
print("max:", tf.reduce_max(tensor))
print("mean", tf.reduce_mean(tensor))
#指定维度
print("=====>axis=0")
print("min:", tf.reduce_min(tensor, axis=0))
print("max:", tf.reduce_max(tensor, axis=0))
print("mean", tf.reduce_mean(tensor, axis=0))
print("=====>axis=1")
print("min:", tf.reduce_min(tensor, axis=1))
print("max:", tf.reduce_max(tensor, axis=1))
print("mean", tf.reduce_mean(tensor, axis=1))
#argmin/max求最大最小值所在位置
tensor = tf.random.uniform([4,10], maxval=100, dtype=tf.int32)
tensor = tf.cast(tensor, dtype=tf.float32)
print(tensor)
#默认axis=0
print("=====>tf.argmax(tensor):", tf.argmax(tensor))
print("=====>tf.argmin(tensor, axis=1):", tf.argmin(tensor, axis=1))
#tf.equal,比较对应元素是否相等,相等返回True,不等返回False
tensor0 = tf.constant([1,2,2,3,5])
tensor1 = tf.range(5)
print(tensor0)
print(tensor1)
print("=====>tf.equal(tensor0,tensor1):", tf.equal(tensor0, tensor1))
#统计匹配上的元素个数
print("=====>tf.reduce_sum(tf.cast(tf.equal(tensor0,tensor1), dtype=tf.int32)):", tf.reduce_sum(tf.cast(tf.equal(tensor0,tensor1), dtype=tf.int32)))
#tf.unique用于统计重复元素,返回一个去重后的tensor和对应的index列表
#参考:https://www.w3cschool.cn/tensorflow_python/tensorflow_python-duv62o0r.html
#仅针对1维tensor
tensor = tf.random.uniform([10], maxval=10, dtype=tf.int32)
tensor = tf.cast(tensor, dtype=tf.float32)
print(tensor)
print("=====>tf.unique(tensor):", tf.unique(tensor))
运行结果: