torch.where()

API和用法:

python 复制代码
torch.where(condition, x, y) -> Tensor

condition:判断条件,一个布尔类型的张量,表示条件。

若当前index满足条件,则取x中index对应的元素

若当前index不满足条件,则取y中index对应的元素

形状:

d 是一个shape和 b,c 相同的tensor,也就是 b,c 的shape 也必须相同。

注意:a不需要和b,c一样的shape

示例:

python 复制代码
import torch

# 创建一个布尔类型的张量,表示条件
condition = torch.tensor([True, False, True, False])

# 创建两个与 condition 形状相同的张量
x = torch.tensor([1, 2, 3, 4])
y = torch.tensor([5, 6, 7, 8])

# 使用 torch.where() 函数获取满足条件的元素索引
result = torch.where(condition, x, y)

print(result)

输出:

tensor([1, 6, 3, 8])

torch.where()函数-CSDN博客

torch.where()详解-CSDN博客

torch.where()函数解读-CSDN博客

相关推荐
后端小肥肠12 小时前
突破 LLM 极限!n8n + MemMachine 打造“无限流”小说生成器
人工智能·aigc·agent
道199312 小时前
PyTorch 从小白到高级进阶教程[工业级示例](三)
人工智能·pytorch·python
南山乐只12 小时前
【原文翻译搬运】Equipping agents for the real world with Agent Skills
人工智能·职场和发展·创业创新
AI营销快线13 小时前
金融AI内容合规,三类系统怎么选?
大数据·人工智能
测试人社区-千羽13 小时前
智能测试的终极形态:从自动化到自主化的范式变革
运维·人工智能·python·opencv·测试工具·自动化·开源软件
用户91860343127313 小时前
AI重塑云原生应用开发实战-极客时间
人工智能
秋刀鱼 ..13 小时前
2026年机器人感知与智能控制国际学术会议(RPIC 2026)
运维·人工智能·科技·金融·机器人·自动化
listhi52013 小时前
使用Hopfield神经网络解决旅行商问题
人工智能·深度学习·神经网络
锐学AI13 小时前
从零开始学MCP(八)- 构建一个MCP server
人工智能·python
木棉知行者13 小时前
PyTorch 核心方法:state_dict ()、parameters () 参数打印与应用
人工智能·pytorch·python