python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyTorch Tensor转为Python列表

将PyTorch Tensor转换为Python列表的三种方法

作者:detayun

本文介绍了三种将PyTorch Tensor转换为Python列表的方法,推荐使用.tolist()方法,适用于任何维度的Tensor,自动处理CPU/GPU转换且性能更优,同时提到了注意事项,.list()仅适用于一维Tensor,转换后的列表元素保持原有的数据类型

方法一:使用.tolist()方法(推荐)

import torch

# 创建一个 tensor
tensor = torch.tensor([9.6919, -0.6950, 11.8760, 1.6362, 8.3674, 9.2179])

# 转换为列表
list_result = tensor.tolist()

print(list_result)
print(type(list_result))
# 输出: [9.6919, -0.695, 11.876, 1.6362, 8.3674, 9.2179]
# 输出: <class 'list'>

方法二:使用list()函数

import torch

tensor = torch.tensor([9.6919, -0.6950, 11.8760, 1.6362, 8.3674, 9.2179])

# 转换为列表
list_result = list(tensor)

print(list_result)
print(type(list_result))
# 输出: [9.6919, -0.695, 11.876, 1.6362, 8.3674, 9.2179]
# 输出: <class 'list'>

方法三:使用.numpy()方法(适用于 CPU tensor)

import torch

tensor = torch.tensor([9.6919, -0.6950, 11.8760, 1.6362, 8.3674, 9.2179])

# 先转换为 numpy 数组,再转换为列表
list_result = tensor.numpy().tolist()

print(list_result)
print(type(list_result))

处理 GPU Tensor

如果 tensor 在 GPU 上,需要先移动到 CPU:

import torch

# 假设 tensor 在 GPU 上
tensor_gpu = torch.tensor([9.6919, -0.6950, 11.8760, 1.6362, 8.3674, 9.2179]).cuda()

# 先移动到 CPU,再转换为列表
list_result = tensor_gpu.cpu().tolist()

print(list_result)

处理多维 Tensor

import torch

# 二维 tensor
tensor_2d = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])

# 转换为嵌套列表
list_2d = tensor_2d.tolist()
print(list_2d)
# 输出: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

# 三维 tensor
tensor_3d = torch.tensor([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]])
list_3d = tensor_3d.tolist()
print(list_3d)
# 输出: [[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]

完整示例

import torch

def tensor_to_list(tensor):
    """
    将 PyTorch tensor 转换为 Python 列表
    """
    if tensor.is_cuda:
        # 如果在 GPU 上,先移动到 CPU
        tensor = tensor.cpu()
    
    return tensor.tolist()

# 测试
tensor = torch.tensor([9.6919, -0.6950, 11.8760, 1.6362, 8.3674, 9.2179])
result = tensor_to_list(tensor)

print("原始 tensor:", tensor)
print("转换后的列表:", result)
print("列表类型:", type(result))
print("列表元素类型:", type(result[0]))

注意事项

.tolist() vs list():

数据类型: 转换后的列表元素会保持 tensor 的数据类型(如 float32、float64 等)

性能: 对于大型 tensor,.tolist() 可能比 list() 稍快

梯度: 如果 tensor 有梯度,.tolist() 会自动处理,只返回数值

推荐做法

始终使用 .tolist() 方法,因为它:

# 最佳实践
list_result = tensor.tolist()  # 对于 CPU tensor
# 或
list_result = tensor.cpu().tolist()  # 对于可能在 GPU 上的 tensor

到此这篇关于将PyTorch Tensor转换为Python列表的三种方法的文章就介绍到这了,更多相关PyTorch Tensor转为Python列表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文