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]])
相关推荐
软糯小野猫4 分钟前
使用Pytorch从零开始构建StyleGAN
pytorch·深度学习·gan·图像生成·stylegan
hhzz16 小时前
《深度学习框架PyTorch入门与实践》系列:11-实战猫狗大战之可复用的PyTorch项目架构
人工智能·pytorch·深度学习
玩三国杀玩的18 小时前
Pytorch-c++-CUDA
c++·pytorch·python·深度学习
内蒙深海大鲨鱼1 天前
5.Introduction to PyTorch YouTube Series--visualable train
人工智能·pytorch·python
承渊政道1 天前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(从注意力到自回归生成:彻底理解Transformer解码器)
pytorch·回归·transformer·chatglm·注意力机制·解码器
盼小辉丶1 天前
PyTorch强化学习实战(22)——将强化学习应用于TextWorld互动小说游戏
pytorch·深度学习·强化学习
Uncommon.2 天前
使用Pytorch自动计算梯度
人工智能·pytorch·python
Uncommon.3 天前
使用pandas处理csv并转为张量
pytorch·python·深度学习·pandas
Uncommon.3 天前
使用Pytorch操作张量(多维数组)
人工智能·pytorch·python
HZZD_HZZD3 天前
非侵入式负荷监测选`Seq2Point`还是`LSTM`?合众致达实测:洗衣机分解F1达0.87、`NDE`误差降27%,附PyTorch完整实现
人工智能·pytorch·lstm