AI学习记录 -transformer 中对于torch和numpy常用函数的使用方式

在transformer源码中,使用了很多矩阵变换的方法,争取一句话描述这些方法,长期记录

torch.unsqueeze

在指定维度增加一个维度

import torch

# 创建一个 1D 张量
tensor_1d = torch.tensor([1, 2, 3, 4])
print("原始张量:", tensor_1d)

# 在维度 0 处增加一个维度
tensor_2d = torch.unsqueeze(tensor_1d, dim=0)
print("在维度 0 处增加维度:", tensor_2d)

# 在维度 1 处增加一个维度
tensor_2d_alt = torch.unsqueeze(tensor_1d, dim=1)
print("在维度 1 处增加维度:", tensor_2d_alt)

打印:

原始张量: tensor([1, 2, 3, 4])
在维度 0 处增加维度: tensor([[1, 2, 3, 4]])
在维度 1 处增加维度: tensor([
        [1],
        [2],
        [3],
        [4]
 ])

.shape[n]

获取指定维度的形状

torch.zeros

创建全 0 张量

import torch
# 创建一个 2x3 的全零张量
zero_tensor = torch.zeros(2, 3)
print(zero_tensor)
tensor([[0., 0., 0.],
        [0., 0., 0.]])

torch.arange

可以生成有数值叠加的数组

import torch

# 创建从 0 到 9 的一维张量
tensor_1d = torch.arange(10)
print(tensor_1d)

# 创建从 1 到 9 的一维张量,步长为 2
tensor_1d_step = torch.arange(1, 10, 2)
print(tensor_1d_step)

输出:

tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([1, 3, 5, 7, 9])

torch.transpose

交换张量的指定维度

import torch

# 创建一个 2x3 的张量
tensor = torch.tensor([[1, 2, 3],
                       [4, 5, 6]])
print("原始张量:")
print(tensor)

# 转置张量
transposed_tensor = torch.transpose(tensor, 0, 1)
print("转置后的张量:")
print(transposed_tensor)

打印:

原始张量:
tensor([[1, 2, 3],
        [4, 5, 6]])
转置后的张量:
tensor([[1, 4],
        [2, 5],
        [3, 6]])

torch.exp

1、将数组每一项 转成 e 的 x 次方。
2、激活函数:在神经网络中,通常用于计算 softmax 函数的一部分。

import torch

# 创建一个张量
tensor = torch.tensor([0.0, 1.0, 2.0])
# 计算每个元素的指数
exp_tensor = torch.exp(tensor)
print(exp_tensor)

输出

tensor([ 1.0000,  2.7183,  7.3891])

tensor.eq(0)

将整数数组转成true和false

import torch

# 创建一个张量
tensor = torch.tensor([1, 0, 2, 0, 3])

# 使用 .eq(0) 检查哪些元素等于 0
zero_check = tensor.eq(0)
print(zero_check)

输出

tensor([False,  True, False,  True, False])

numpy.ones

创建一个指定形状的数组,并将所有元素初始化为 1。

import numpy as np

# 创建一个 2x3 的数组,所有元素为 1
ones_array = np.ones((2, 3))
print(ones_array)

# 创建一个 3 维的数组
ones_3d_array = np.ones((2, 2, 2), dtype=int)
print(ones_3d_array)

输出

[[1. 1. 1.]
 [1. 1. 1.]]

[[[1 1]
  [1 1]]

 [[1 1]
  [1 1]]]

numpy.triu

返回一个矩阵的上三角部分,其他元素设为 0。

import numpy as np

# 创建一个 3x3 的矩阵
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# 获取上三角部分
upper_triangle = np.triu(matrix)
print(upper_triangle)

输出

[[1 2 3]
 [0 5 6]
 [0 0 9]]

torch.from_numpy

将 NumPy 数组转换为 PyTorch 张量。

import numpy as np
import torch

# 创建一个 NumPy 数组
numpy_array = np.array([[1, 2, 3], [4, 5, 6]])

# 将 NumPy 数组转换为 PyTorch 张量
torch_tensor = torch.from_numpy(numpy_array)
print(torch_tensor)

torch.matmul 点乘,点乘的性质在某些场景下可以代表批量点积,在transformer中可以体现

不管多少维度的矩阵,最后两个维度进行矩阵乘法

import torch

# 创建张量 A 和 B
A = torch.randn(2, 3, 4)  # 形状为 (2, 3, 4)
B = torch.randn(2, 4, 5)  # 形状为 (2, 4, 5)

# 使用 torch.matmul 进行矩阵乘法
C = torch.matmul(A, B)  # 结果形状为 (2, 3, 5)

print(C.shape)  # 输出: torch.Size([2, 3, 5])

torch.dot 点积

import torch

# 创建两个一维张量
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([4.0, 5.0, 6.0])

# 计算点积
dot_product = torch.dot(a, b)

print(dot_product)  # 输出: tensor(32.)

numpy.sqrt

对传入的数组进行逐元素的平方根操作

import numpy as np

# 创建一个数组
arr = np.array([1, 4, 9, 16])

# 计算平方根
sqrt_arr = np.sqrt(arr)

print(sqrt_arr)  # 输出: [1. 2. 3. 4.]

torch.masked_fill_

将矩阵中为 True 的位置替换为 -1e9(也就是负无穷大)

import torch

# 创建一个示例张量
scores = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])

# 创建一个掩码张量(布尔型)
mask = torch.tensor([[False, True, False], [False, False, True]])

# 使用 masked_fill_ 来掩盖某些元素
scores.masked_fill_(mask, -1e9)

print(scores)
# 输出:
# tensor([[ 1.0000e+00, -1.0000e+09,  3.0000e+00],
#         [ 4.0000e+00,  5.0000e+00, -1.0000e+09]])

torch.view

重新调整张量形状的函数

import torch

# 创建一个 2x3 的张量
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])

# 使用 view 重新调整为 3x2 的张量
reshaped_tensor = tensor.view(3, 2)

print(reshaped_tensor)
# 输出:
# tensor([[1, 2],
#         [3, 4],
#         [5, 6]])

torch.repeat

在指定维度重复张量并设置重复次数

import torch

# 创建一个 2x2 的张量
tensor = torch.tensor([[1, 2], [3, 4]])

# 第1维度重复2词,第2维度重复3次
repeated_tensor = tensor.repeat(2, 3)

print(repeated_tensor)
# 输出:
# tensor([[1, 2, 1, 2, 1, 2],
#         [3, 4, 3, 4, 3, 4],
#         [1, 2, 1, 2, 1, 2],
#         [3, 4, 3, 4, 3, 4]])

tensor.reshape

调整矩阵的展示方向

import torch

# 创建一个 2x3 的张量
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])

# 使用 reshape 重新调整为 3x2 的张量
reshaped_tensor = tensor.reshape(3, 2)

print(reshaped_tensor)
# 输出:
# tensor([[1, 2],
#         [3, 4],
#         [5, 6]])

nn.ModuleList

有点像数组存了很多函数,然后函数返回当作是下个函数的输入

import torch
import torch.nn as nn

# 定义一个简单的 DecoderLayer 类,继承自 nn.Module
class DecoderLayer(nn.Module):
    def __init__(self):
        super(DecoderLayer, self).__init__()
        self.linear = nn.Linear(10, 10)
    
    def forward(self, x):
        return self.linear(x)

# 定义网络时,我们创建 n_layers 个 DecoderLayer
n_layers = 3
decoder_layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)])

# 输入数据
x = torch.randn(5, 10)  # 假设输入张量大小为 (5, 10)

# 逐个层进行前向传播
for layer in decoder_layers:
    x = layer(x)

print(x)

torch.gt

对比两个张量的大小

import torch

# 创建两个张量
a = torch.tensor([1, 2, 3, 4])
b = torch.tensor([2, 2, 2, 2])

# 比较 a 是否大于 b
result = torch.gt(a, b)

print(result)
# 输出:
# tensor([False, False, True, True])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值