python - 找到最小张量值的 p% - 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的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
推荐阅读
- java - 使用 buffreader 进行 JAva 编程
- javascript - Trouble with Axios post request in basic MERN stack app
- firebase - 如何在 Next JS 项目中使用 Firebase Cloud FireStore 数据库。如何正确初始化?
- android - 如何在颤振应用程序中使用外部 USB 摄像头?
- sql - 如何在oracle中分别传递值?
- python - how using key(name) we will get output value(Address) in a .csv or .xls file?
- java - 使用继承在java中扩展一个类
- javascript - 我正在尝试在 svg 元素中创建一个 rect 元素,但它不起作用
- java - 为什么我不能将 int 类型值添加到数组中
- javascript - 为什么这个打印未定义?当我使用 ${name} 以外的变量时,它可以工作