1、tf.clip_by_value
将张量值裁剪到指定的最小值和最大值。
tf.clip_by_value(t, clip_value_min, clip_value_max):输入一个张量t,把t中的每一个元素的值都压缩在clip_value_min和clip_value_max之间。
用法:
tf.clip_by_value
(
t,
clip_value_min,
clip_value_max,
name=None
)
示例说明:
a = tf.range(10)
a
Out[22]: <tf.Tensor: shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>
# tf.maximum(a,2),返回的是a,2之间的最大值
tf.maximum(a, 2)
Out[23]: <tf.Tensor: shape=(10,), dtype=int32, numpy=array([2, 2, 2, 3, 4, 5, 6, 7, 8, 9])>
# tf.maximum(a,8),返回的是a,2之间的最小值
tf.minimum(a, 8)
Out[24]: <tf.Tensor: shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 8])>
tf.clip_by_value(a, 2, 8)
Out[25]: <tf.Tensor: shape=(10,), dtype=int32, numpy=array([2, 2, 2, 3, 4, 5, 6, 7, 8, 8])>
2、tf.nn.relu
用法见这篇教程
3、tf.clip_by_norm
根据 l 2 l_2 l2-范数进行裁剪,范数的简单概念见这篇博客
功能是:等比例的放缩,既没有该变tensor的方向,然后使得tensor的整体数值减少
计算方法如下:
t l 2 n o r m ( t ) ∗ c l i p _ n o r m \frac{t}{l_2norm(t)} * clip\_norm l2norm(t)t∗clip_norm
用法:
tf.clip_by_norm
(
t,
clip_norm,
axes=None,
name=None
)
示例:
a = tf.random.normal([2, 2], mean = 10)
tf.norm(a)
Out[27]: <tf.Tensor: shape=(), dtype=float32, numpy=19.932812>
aa = tf.clip_by_norm(a, 13)
tf.norm(aa)
Out[29]: <tf.Tensor: shape=(), dtype=float32, numpy=13.000001>
4、tf.clip_by_global_norm
将多个张量的值按其范数之和的比率裁剪。保持整个tensor的方向不变,值进行减小。
计算方法公式为:
t _ l i s t [ i ] m a x ( g l o b a l _ n o r m , c l i p _ n o r m ) ∗ c l i p _ n o r m \frac{t\_list[i]}{max(global\_norm, clip\_norm)} * clip\_norm max(global_norm,clip_norm)t_list[i]∗clip_norm
其中,
g l o b a l _ n o r m = s q r t ( s u m ( [ l 2 n o r m ( t ) 2 f o r t i n t _ l i s t ] ) ) global\_norm = sqrt(sum([l_2norm(t)^2\,for\,t\,in\,t\_list])) global_norm=sqrt(sum([l2norm(t)2fortint_list]))
用法:
tf.clip_by_global_norm
(
t_list,
clip_norm,
use_norm=None,
name=None
)