pytorch中where方法介绍

本文详细介绍了PyTorch库中的where函数使用方法,包括其三个参数的含义:条件判断condition,符合条件时的值x,及不符合条件时的值y。并通过示例展示了如何使用where函数对张量进行条件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

一、具体用法

       torch.where(condition, x, y)→ 其中 x,y 必须是Tensor类型

※ 共有三个输入参数,第一个是condition判断条件,第二个是符合条件时取设置值x,第三个是不满足条件的设置值y;
                     即类似于 a n s = { x , c o n d i t i o n y , !   c o n d i t i o n ans=\left\{\begin{matrix} &x, &condition \\ &y, &!\ condition \end{matrix}\right. ans={x,y,condition! condition

 

二、示例

import torch

ans = torch.randn(3, 2)
x = torch.randn(3, 2)
y = torch.randn(3, 2)
print(ans)
print(x)
print(y)
print(torch.where(ans > 0, x, y))

Out:
              在这里插入图片描述

 

三、设置值必须是tensor类型

import torch

ans = torch.randn(3, 2)

print(ans)
print(torch.where(ans > 0, 0, 1))

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值