放风铃的兔子头像
关注
【Bug已解决】Converting python list to pytorch tensor 解决方案封面图

【Bug已解决】Converting python list to pytorch tensor 解决方案

【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]

常见困惑:

  1. torch.tensor

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/mrdeam/article/details/164734129

文章来源转载

评论

赞0

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--