什么是张量
张量(Tensor)是 PyTorch 中的核心数据结构,类似于 NumPy 的数组,但可以在 GPU 上运行以加速计算。
标量(0维)
单个数值:5
向量(1维)
一维数组:[1, 2, 3]
矩阵(2维)
二维数组:[[1, 2], [3, 4]]
高维张量(3维+)
多维数组:图像、视频等
张量的创建
从 Python 列表创建
import torch
# 创建向量
vector = torch.tensor([1, 2, 3, 4, 5])
print(vector)
# 创建矩阵
matrix = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(matrix)
print(matrix.shape) # torch.Size([2, 3])
使用内置函数
# 全0张量
zeros = torch.zeros(3, 4)
# 全1张量
ones = torch.ones(2, 3)
# 随机张量(0-1均匀分布)
rand = torch.rand(2, 2)
# 随机张量(标准正态分布)
randn = torch.randn(3, 3)
# 指定范围的张量
arange = torch.arange(0, 10, 2) # [0, 2, 4, 6, 8]
# 等间隔张量
linspace = torch.linspace(0, 1, 5) # [0.0, 0.25, 0.5, 0.75, 1.0]
从 NumPy 数组转换
import numpy as np
# NumPy 转 PyTorch
np_array = np.array([1, 2, 3])
tensor = torch.from_numpy(np_array)
# PyTorch 转 NumPy
tensor = torch.tensor([1, 2, 3])
np_array = tensor.numpy()
张量的属性
tensor = torch.randn(3, 4)
# 形状
print(tensor.shape) # torch.Size([3, 4])
print(tensor.size()) # torch.Size([3, 4])
# 数据类型
print(tensor.dtype) # torch.float32
# 设备
print(tensor.device) # cpu 或 cuda:0
# 元素总数
print(tensor.numel()) # 12