查找最小张量值的 p% - TensorFlow 2.0
Finding p% of smallest tensor values - TensorFlow 2.0
我正在使用 Python 3.7 和 TensorFlow 2.0,但遇到以下问题。在任意维度的给定张量内,如果我想找到 p% 的最小权重(其中,p 可以是用户输入),我该怎么做?
示例:
x = tf.random.normal(shape=(3, 2, 2))
x.numpy()
Out[8]:
array([[[-0.30938825, 0.40093166],
[ 1.5417175 , -0.9551434 ]],
[[-0.7977963 , -2.0784302 ],
[-1.5039488 , -0.75159657]],
[[ 1.7954558 , 0.19909047],
[-0.2359499 , -2.4791834 ]]], dtype=float32)
在张量 'x'(形状:(3, 2, 2))中,我如何找到 p = 30% 的最小权重?然后我计划通过将它们设置为零来删除最小权重的 p%。
谢谢!
使用TensorFlow Probability's stats.percentile
:
In [5]: import tensorflow_probability as tfp
In [6]: p30 = tfp.stats.percentile(x, q=30.)
In [7]: p30
Out[7]: <tf.Tensor: id=1159, shape=(), dtype=float32, numpy=-0.9551434>
In [8]: tf.where(x <= p30, 0, x)
Out[8]:
<tf.Tensor: id=1108, shape=(3, 2, 2), dtype=float32, numpy=
array([[[-0.30938825, 0.40093166],
[ 1.5417175 , 0. ]],
[[-0.7977963 , 0. ],
[ 0. , -0.75159657]],
[[ 1.7954558 , 0.19909047],
[-0.2359499 , 0. ]]], dtype=float32)>
最低要求:
tensorflow==2.0
tensorflow-probability==0.7
我正在使用 Python 3.7 和 TensorFlow 2.0,但遇到以下问题。在任意维度的给定张量内,如果我想找到 p% 的最小权重(其中,p 可以是用户输入),我该怎么做?
示例:
x = tf.random.normal(shape=(3, 2, 2))
x.numpy()
Out[8]:
array([[[-0.30938825, 0.40093166],
[ 1.5417175 , -0.9551434 ]],
[[-0.7977963 , -2.0784302 ],
[-1.5039488 , -0.75159657]],
[[ 1.7954558 , 0.19909047],
[-0.2359499 , -2.4791834 ]]], dtype=float32)
在张量 'x'(形状:(3, 2, 2))中,我如何找到 p = 30% 的最小权重?然后我计划通过将它们设置为零来删除最小权重的 p%。
谢谢!
使用TensorFlow Probability's stats.percentile
:
In [5]: import tensorflow_probability as tfp
In [6]: p30 = tfp.stats.percentile(x, q=30.)
In [7]: p30
Out[7]: <tf.Tensor: id=1159, shape=(), dtype=float32, numpy=-0.9551434>
In [8]: tf.where(x <= p30, 0, x)
Out[8]:
<tf.Tensor: id=1108, shape=(3, 2, 2), dtype=float32, numpy=
array([[[-0.30938825, 0.40093166],
[ 1.5417175 , 0. ]],
[[-0.7977963 , 0. ],
[ 0. , -0.75159657]],
[[ 1.7954558 , 0.19909047],
[-0.2359499 , 0. ]]], dtype=float32)>
最低要求:
tensorflow==2.0
tensorflow-probability==0.7