python - Pytorch:创建一个大于批次中每个 2D 张量的第 n 个分位数的掩码
问题描述
我有一个torch.Tensor
形状(2, 2, 2)
(可以更大),其中值在 range 内标准化[0, 1]
。
现在我得到一个正整数K
,它告诉我需要创建一个掩码,其中对于批次中的每个 2D 张量,如果它大于1/k
所有值,则值为 1,而在其他地方为 0。返回面罩也有形状(2, 2, 2)
。
例如,如果我有这样的批次:
tensor([[[1., 3.],
[2., 4.]],
[[5., 7.],
[9., 8.]]])
let K=2
,这意味着我必须屏蔽大于每个 2D 张量内所有值的 50% 的值。
在示例中,0.5 分位数是2.5
和7.5
,因此这是所需的输出:
tensor([[[0, 1],
[0, 1]],
[[0, 0],
[1, 1]]])
我试过了:
a = torch.tensor([[[0, 1],
[0, 1]],
[[0, 0],
[1, 1]]])
quantile = torch.tensor([torch.quantile(x, 1/K) for x in a])
torch.where(a > val, 1, 0)
但这是结果:
tensor([[[0, 0],
[0, 0]],
[[1, 0],
[1, 1]]])
解决方案
t = torch.tensor([[[1., 3.],
[2., 4.]],
[[5., 7.],
[9., 8.]]])
t_flat = torch.reshape(t, (t.shape[0], -1))
quants = torch.quantile(t_flat, 1/K, dim=1)
quants = torch..reshape(quants, (quants.shape[0], 1, 1))
res = torch.where(t > val, 1, 0)
在这个 res 之后是:
tensor([[[0, 1],
[0, 1]],
[[0, 0],
[1, 1]]])
这就是你想要的
推荐阅读
- javascript - 当用户在Javascript中使用鼠标滚轮开始滚动时,如何确定用户将滚动多少像素
- vb.net - 在 Visual Basic 中旋转 BMP
- c++ - 从 C++ 项目调用 docker 容器
- wordpress - 如何在 WordPress 中禁用古腾堡
- ubuntu - AWK 提取列中具有相同单词的前两行
- azure - 通过 Azure 应用程序代理调用本地 OAuth API
- sql - 如何通过在oracle sql中同时比较多条记录来获取行
- python - 将 pandas 数据框转换为具有唯一整数对的元组列表作为第一个条目
- apache-flink - 如何使用 Flink CEP 实现模式以匹配暴力登录和端口扫描攻击
- vue.js - Vue - 检测插槽内的组件