PyTorch张量(Tensor)创建的方式汇总详解和代码示例

发布于:2025-07-15 ⋅ 阅读:(14) ⋅ 点赞:(0)

在 PyTorch 中,张量(Tensor)是所有计算的基础数据结构,类似于 NumPy 的 ndarray,但支持 GPU 运算与自动求导。下面详细汇总 PyTorch 中张量的创建方式及其代码示例


一、基于数据创建张量

1. torch.tensor(data)

将列表、元组、NumPy 数组等数据直接转为张量。

import torch
import numpy as np

# 从列表创建
a = torch.tensor([1, 2, 3])
print(a)

# 从嵌套列表创建多维张量
b = torch.tensor([[1, 2], [3, 4]])
print(b)

# 从 NumPy 创建
c = torch.tensor(np.array([5, 6, 7]))
print(c)

二、创建特定值的张量

2. torch.zeros(size)

创建所有元素为 0 的张量。

a = torch.zeros(2, 3)  # shape: (2, 3)
print(a)

3. torch.ones(size)

创建所有元素为 1 的张量。

b = torch.ones(3, 2)
print(b)

4. torch.full(size, fill_value)

创建所有元素为指定值的张量。

c = torch.full((2, 2), 7)
print(c)

三、创建随机值张量

5. torch.rand(size)

[0, 1) 范围内均匀分布的随机值。

a = torch.rand(2, 3)
print(a)

6. torch.randn(size)

标准正态分布(均值为 0,标准差为 1)。

b = torch.randn(2, 3)
print(b)

7. torch.randint(low, high, size)

创建整数张量,区间 [low, high)

c = torch.randint(0, 10, (2, 3))
print(c)

四、创建单位矩阵与对角矩阵

8. torch.eye(n, m=None)

创建一个单位矩阵(对角为 1,其余为 0)。

a = torch.eye(3)      # 3x3单位矩阵
b = torch.eye(3, 4)   # 3x4单位矩阵
print(a, b)

五、使用范围和步长创建张量

9. torch.arange(start, end, step)

类似于 Python 中的 range

a = torch.arange(0, 10, 2)  # [0, 2, 4, 6, 8]
print(a)

10. torch.linspace(start, end, steps)

生成固定步数的等间距值。

b = torch.linspace(0, 1, 5)  # [0., 0.25, 0.5, 0.75, 1.]
print(b)

六、创建与已有张量相似的新张量

11. tensor.new_*(...) 系列(不推荐)

例如:

a = torch.tensor([1.0, 2.0, 3.0])
b = a.new_zeros(2, 2)
print(b)

12. torch.zeros_like(tensor)

根据已有张量形状创建新张量。

a = torch.ones(2, 3)
b = torch.zeros_like(a)
c = torch.ones_like(a)
d = torch.randn_like(a)
print(b, c, d)

七、张量创建时指定设备和数据类型

你可以指定 dtypedevice

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

a = torch.ones((2, 2), dtype=torch.float32, device=device)
print(a)

八、从 NumPy 转换 / 转回

13. torch.from_numpy(ndarray)

共享内存,修改张量或数组都会影响另一个。

import numpy as np

arr = np.array([[1, 2], [3, 4]])
tensor = torch.from_numpy(arr)
print(tensor)

14. .numpy()

将张量转为 NumPy 数组(要求在 CPU 上)。

a = torch.tensor([[1, 2], [3, 4]])
np_array = a.numpy()
print(np_array)

九、其他高级初始化方式

15. torch.empty(size)

创建未初始化的张量(内存内容不确定,运行速度快)。

a = torch.empty(2, 2)
print(a)

十、使用 requires_grad 创建可求导张量

a = torch.ones(2, 2, requires_grad=True)
print(a)

总结:张量创建方法对比表

方法 说明 是否可指定 dtype/device
torch.tensor() 从数据创建张量
torch.zeros() 全为 0
torch.ones() 全为 1
torch.full() 全为指定值
torch.rand() 均匀分布 [0, 1)
torch.randn() 标准正态分布
torch.randint() 随机整数
torch.eye() 单位矩阵
torch.arange() 区间整型值序列
torch.linspace() 区间等间隔浮点数
torch.empty() 未初始化张量
torch.from_numpy() NumPy 转张量 ❌(dtype 不可变)
tensor.numpy() 张量转 NumPy ❌(仅 CPU 张量)


网站公告

今日签到

点亮在社区的每一天
去签到