一、Python 内置类型

1、数字

a = 3           # int 整数
b = 3.14        # float 浮点数
c = True        # bool 布尔值

2、序列

lst = [1, 2, 3]          # list 列表,可变
tup = (1, 2, 3)          # tuple 元组,不可变
st = {1, 2, 3}           # set 集合,元素唯一
d = {"a": 1, "b": 2}     # dict 字典,键值对

二、NumPy 数组

NumPy 提供了 ndarray,是多维数组,比 Python list 快很多。

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])  # 2D 数组
print(arr.shape)   # 维度(2, 3)
print(arr.dtype)   # int64

np.zeros((2,2))      # 全 0 数组
np.ones((3,3))       # 全 1 数组
np.eye(3)            # 单位矩阵
np.arange(0, 10, 2)  # 从0开始到10结束(10不算),间隔2,[0,2,4,6,8]
np.random.randn(2,3) # 随机数组

三、PyTorch 张量

可以看成带 GPU 加速的 NumPy ndarray

import torch

x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)  # 2×2 张量
print(x.shape)   # torch.Size([2, 2])
print(x.dtype)   # torch.float32
print(x.device)  # 默认在 CPU 上
x = x..cuda()    # 放在GPU上

torch.zeros((2,2))
torch.ones((3,3))
torch.eye(3)
torch.arange(0, 10, 2)
torch.randn(2,3)   # ~ N(0,1)

四、PyTorch 特殊张量类型

1、稀疏张量

存稀疏矩阵

# 构造一个稀疏矩阵,只在指定坐标存值,其余全为 0 (省内存、加速运算) 

indices = torch.tensor([[0, 1], [2, 0]])    # 非零元素的坐标,第 0 维是行号,第 1 维是列号
values = torch.tensor([3., 4.])             # 非零元素的值
sparse = torch.sparse_coo_tensor(indices, values, (3, 3))   # 矩阵大小3*3
print(sparse.to_dense())

# 打印结果
# tensor([[3., 0., 0.],
        [0., 0., 0.],
        [4., 0., 0.]])

2、Embedding

用 ID 查表

emb = torch.nn.Embedding(10, 4)  # 10个id,每个4维
print(emb(torch.tensor([2, 5, 7])))

3、Parameter

用于神经网络可训练参数

from torch import nn
w = nn.Parameter(torch.randn(3,3))

五、PyTorch 中的数值类型

名字 说明
torch.float32 常用浮点(训练默认)
torch.float64 双精度浮点
torch.float16 半精度(省显存)
torch.bfloat16 bfloat16(大模型常用)
torch.int64 整数(id 常用)
torch.int32 32位整数
torch.bool 布尔值
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐