【Bug已解决】Converting python list to pytorch tensor 解决方案
问题描述
在 PyTorch 开发中,将 Python 列表转换为张量是最常见的操作之一。然而,开发者经常遇到数据类型不匹配、维度错误、性能问题等各种问题。
import torch
# 基本转换
python_list = [1, 2, 3, 4, 5]
tensor = torch.tensor(python_list)
print(f"Tensor: {tensor}, dtype: {tensor.dtype}")
# tensor([1, 2, 3, 4, 5]), dtype: int64
# 常见问题1:浮点数被转为整数
float_list = [1.0, 2.0, 3.0]
tensor = torch.tensor(float_list)
print(f"dtype: {tensor.dtype}") # float32
# 常见问题2:混合类型
mixed_list = [1, 2.0, 3]
tensor = torch.tensor(mixed_list)
print(f"dtype: {tensor.dtype}") # float64(自动提升)
# 常见问题3:嵌套列表
nested_list = [[1, 2], [3, 4]]
tensor = torch.tensor(nested_list)
print(f"Shape: {tensor.shape}") # [2, 2]
常见困惑:
torch.tensor
转载自 CSDN-专业IT技术社区




