PyTorch NLP 常用 API

根据官方文档整理,知道有这么些常用的函数,具体要用的时候再去官方文档里面查询,前三部分建议直接运行对照结果记函数功能

数据创建

由列表、numpy创建或tensor自定义的随机整数、正态分布等

import torch
import numpy as np


# *****tensor创建*****
device = torch.device('cuda:0')
a = np.array([1, 2, 3])
t1 = torch.from_numpy(a)  # 原地创建tensor
t2 = torch.as_tensor(a)  # 同一设备的话,原地创建tensor
t3 = torch.as_tensor(a, device=device)  # 先注释,为了后面运行快
a[0] = -1
t4 = torch.full_like(t1, 1)
t5 = torch.arange(1, 2.5, 0.5)
t6 = torch.linspace(start=-10, end=10, steps=5)  # 从-10到10分5步取完
t7 = torch.normal(mean=2, std=3, size=(2, 2, 3))  # 当mean=0,std=1时,等价于torch.randn(2,2,3)
t8 = t7.to(device) # 跟t7尺度数值一样的张量,但是在不同设备上
t9 = torch.rand(1, requires_grad=True, device=device)  # 生成一个[1]的浮点数随机矩阵,且计算梯度
t10 = t9.item()
for i in range(1, 11):
    print('-----t' + str(i) + '-----')
    eval('print(t' + str(i) + ')')

基本数学运算

加、减、除、哈达玛积、矩阵乘、幂、开方、指数、对数、绝对值、sigmoid函数、近似值、裁剪

import torch
import numpy as np

# a.shape = [2,2,3]
a = torch.tensor([[[4, 2, 3], [3, 2, 1]], [[1, 2, 3], [3, 2, 3]]], dtype=torch.float32)
# d.shape = [2,3,2]
d = torch.tensor(np.array([[[2, 1], [3, 2], [4, 3]], [[1, 4], [2, 3], [2, 3]]]), dtype=torch.float32)
# b.shape = [3] 相当于[1,3]
b = torch.tensor([1, -2, 3], dtype=torch.float32)

# ******基本数学运算*****
c1 = a + b #开新内存,用a.di
c2 = a - b
c3 = a / b
c4 = torch.mul(a, b)  # 逐个相乘
c5 = torch.matmul(a, d)  # 矩阵乘,要保证维度一致
c6 = b.pow(2)
c7 = b.sqrt()
c8 = b.rsqrt() #开方再取倒数
c9 = torch.exp(b)
c10 

你可能感兴趣的:(机器学习,PyTorch,deep,learning,深度学习,pytorch,神经网络,自然语言处理)