torch.where()两种用法

参考官方文档。

官方文档中只给了第一种用法。根据条件condition,从input,other中选择元素f返回。如果满足条件,则返回input元素。若不满足,返回other元素。

还有一种用法是通过where返回张量中满足条件condition的坐标,以二维张量为例。

代码如下:

python 复制代码
import torch

nums = torch.tensor([
    [1, 2, 3], [4, 5, 6], [7, 8, 9]
])

x_loc, y_loc = torch.where(nums>5)
print('x_loc: ', x_loc)
print('y_loc: ', y_loc)

z = torch.where(nums>5, 10, 1)
print('z: ', z)

输出结果如下:

bash 复制代码
x_loc: tensor([1, 2, 2, 2])
y_loc: tensor([2, 0, 1, 2])
z: tensor([[ 1,  1,  1],
        [ 1,  1, 10],
        [10, 10, 10]])
相关推荐
林晓lx2 天前
【程序员AI课】学习神经网络的前置任务:PyTorch框架使用(八)
人工智能·pytorch·ai编程
郝学胜-神的一滴3 天前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
Be for thing3 天前
Pytorch【16】迁移学习|torchvision预训练ResNet,微调实战
人工智能·pytorch·迁移学习
Be for thing12 天前
Pytorch【12】transforms进阶|图像数据增强实战,提升模型泛化能力
人工智能·pytorch·机器学习
电科_银尘14 天前
【深度学习项目实战·33】自定义数据集:把自己的图片接入PyTorch
人工智能·pytorch·深度学习
aifannihao15 天前
AI 学习第 14 课:CNN 训 6 轮卡在 0.5352,数据没打乱
pytorch·python·深度学习·cnn·学习路线
2601_9679873716 天前
Scikit-Learn 1.8引入Array,支持 PyTorch 与 CuPy 张量的原生 GPU 加速
pytorch·scikit-learn·交叉验证·gpu加速·cupy
盼小辉丶16 天前
PyTorch强化学习实战(35)——多智能体强化学习
人工智能·pytorch·深度学习·强化学习
一条大祥脚18 天前
深入理解 PyTorch FlexAttention:从 Score Mod 到 Mask Mod 的稀疏加速之道
人工智能·pytorch·python·注意力机制·flex attention·可编程注意力
Yolanda_202218 天前
week4(下)
pytorch