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]])
相关推荐
希露菲叶特格雷拉特7 小时前
PyTorch深度学习笔记(二十)(模型验证测试)
人工智能·pytorch·笔记
NewsMash7 小时前
PyTorch之父发离职长文,告别Meta
人工智能·pytorch·python
领航猿1号21 小时前
Pytorch 内存布局优化:Contiguous Memory
人工智能·pytorch·深度学习·机器学习
化作星辰1 天前
使用房屋价格预测的场景,展示如何从多个影响因素计算权重和偏置的梯度
pytorch·深度学习
kyle-fang1 天前
pytorch-张量
人工智能·pytorch·python
woshihonghonga1 天前
Dropout提升模型泛化能力【动手学深度学习:PyTorch版 4.6 暂退法】
人工智能·pytorch·python·深度学习·机器学习
Danceful_YJ1 天前
28. 门控循环单元(GRU)的实现
pytorch·python·深度学习
2401_836900331 天前
PyTorch图像分割训练全流程解析
pytorch·模型训练
三排扣1 天前
手搓transformer
pytorch·python·transformer
Victory_orsh2 天前
“自然搞懂”深度学习(基于Pytorch架构)——010203
人工智能·pytorch·python·深度学习·神经网络·算法·机器学习