Tensorflow2.0笔记 - Tensor的限值clip操作

本笔记主要记录使用maximum/minimum,clip_by_value和clip_by_norm来进行张量值的限值操作。

复制代码
import tensorflow as tf
import numpy as np

tf.__version__


#maximum/minimumz做上下界的限值
tensor = tf.random.shuffle(tf.range(10))
print(tensor)

#maximum(x, y, name=None)
#对比x和y,保留两者最大值,可以用作保证最小值为某一个特定值
#https://blog.csdn.net/qq_36379719/article/details/104321914
print("=====tf.maximum(tensor, 5):\n", tf.maximum(tensor, 5).numpy())
print("=====tf.maximum(tensor, [6,6,6,5,5,5,4,4,4,3]):\n", tf.maximum(tensor, [6,6,6,5,5,5,4,4,4,3]).numpy())
#minimum作用和maximum正好相反,可以用来保证最大值为某一个特定值
print("=====tf.minimum(tensor, 5):\n", tf.minimum(tensor, 5).numpy())
print("=====tf.minimum(tensor, [6,6,6,5,5,5,4,4,4,3]):\n", tf.minimum(tensor, [6,6,6,5,5,5,4,4,4,3]).numpy())


#clip_by_value,可以指定上下界参数
#这个函数本身可以用maximum和minimum组合实现
tensor = tf.random.shuffle(tf.range(10))
print(tensor)
#限定tensor的元素值在[2,5]区间
print("=====tf.clip_by_value(tensor,2,5):\n", tf.clip_by_value(tensor, 2, 5).numpy())

#多维tensor
tensor = tf.random.uniform([2,3,3], maxval=10, dtype=tf.int32)
print(tensor)
print("=====tf.clip_by_value(tensor,2,5):\n", tf.clip_by_value(tensor, 2, 5).numpy())


#relu函数限值,大于0的值保留原值,小于零的值变为0
#第一种方式(推荐),使用tf.nn.relu()
tensor = tf.random.uniform([3,3], minval=-10, maxval=10, dtype=tf.int32)
print(tensor)
print("=====tf.nn.relu(tensor):\n", tf.nn.relu(tensor).numpy())

#第二种方式,使用maximum
print("=====tf.maximum(tensor, 0) simulates relu:\n", tf.maximum(tensor, 0).numpy())

#根据范数来限值,clip_by_norm
#参考资料:https://blog.csdn.net/wn87947/article/details/82345537
#应用场景一般是针对梯度进行限值处理,通过范数clip会保持梯度方向不变
tensor = tf.convert_to_tensor([[3,2],[3,2]], dtype=tf.float32)
print(tensor)
print("Tensor Norm:", tf.norm(tensor).numpy())
clipped = tf.clip_by_norm(tensor, 3)
print("=====tf.clip_by_norm(tensor, 3):", clipped)
print("     Norm:", tf.norm(clipped))

运行结果:

相关推荐
方安乐几秒前
react笔记之useCallback/useEffect闭包陷阱
前端·笔记·react.js
gentle coder几秒前
【langchain】agent部署的基础入门代码(持续更新中~)
python·langchain·react
我材不敲代码2 分钟前
深度学习的准备工作:CUDA安装配置、pytorch库、torchvision库、torchaudio库安装
人工智能·pytorch·深度学习
格林威2 分钟前
Baumer相机系统延迟测量与补偿:保障实时控制同步性的 5 个核心方法,附 OpenCV+Halcon 实战代码!
人工智能·数码相机·opencv·算法·计算机视觉·视觉检测·工业相机
喜欢吃豆2 分钟前
Ralph 架构深度解析报告:自主代理循环与软件工程的确定性重构
人工智能·重构·架构·大模型·软件工程
喜欢吃豆2 分钟前
构建下一代语境感知型 AI Agent:AGENTS.md 与 SKILL.md 发现系统的深度工程架构报告
人工智能·架构
uesowys3 分钟前
Apache Spark算法开发指导-Gradient-boosted tree classifier
人工智能·算法·spark
yhdata5 分钟前
2032年,数字化X线平板探测器市场规模有望接近189.8亿元
大数据·人工智能
.小墨迹6 分钟前
开源的自动驾驶框架
c++·人工智能·学习·算法·ubuntu·开源·自动驾驶
北京耐用通信6 分钟前
耐达讯自动化Profinet转Devicenet网关:汽车制造产线的“协议桥梁”
人工智能·物联网·网络协议·自动化·制造·信息与通信