You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将损失张量列表转换为NumPy数组?

将PyTorch张量列表转换为NumPy数组

你的张量位于CUDA设备且关联着计算图(带有grad_fn),转换需要处理设备迁移和计算图分离,以下是具体实现方式:

方法一:逐个转换后合并

先对每个张量执行分离计算图、转移到CPU、转换为NumPy元素,最后合并成数组:

import numpy as np
import torch

# 假设你的张量列表为loss_list
loss_list = [torch.tensor(0.0153, device='cuda:0', grad_fn=torch.div), 
             torch.tensor(0.0020, device='cuda:0', grad_fn=torch.div)]

# 逐个处理并转换为NumPy数组
np_loss_array = np.array([t.detach().cpu().numpy() for t in loss_list])

方法二:先合并为张量再整体转换

先把列表转为PyTorch张量,再统一处理设备和计算图,最后转换:

# 合并列表为单个张量
loss_tensor = torch.stack(loss_list)
# 转换为NumPy数组
np_loss_array = loss_tensor.detach().cpu().numpy()

简化方式:使用无梯度上下文管理器

如果不需要保留计算图,也可以用torch.no_grad()上下文管理器省略detach():

with torch.no_grad():
    np_loss_array = np.array([t.cpu().numpy() for t in loss_list])

内容的提问来源于stack exchange,提问作者Uqhah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:33:09