PyTorch常用函数摘抄
PyTorch常用函数摘抄

PyTorch常用函数摘抄

导入pytorch

from future import print_function

import torch

常用矩阵创建函数

torch.tensor(data, dtype) # data 可以是Numpy中的数组

torch.as_tensor(data)

torch.from_numpy(ndarray)

torch.empty(size)

torch.empty_like(input)

全零/全一/单位矩阵

torch.zeros(size)

torch.zeros_like(input, dtype)

torch.ones(size)

torch.ones_like(input, dtype)

torch.eye(size)

序列生成

torch.arange(start, end, step)  # 不包括end, step是两个点间距

torch.range(start, end, step) # 包括end,step是两个点间距

torch.linspace(start, end, steps) # 包括end, steps 是点的个数,包括端点, (等距离)

torch.logspace(start, end, steps) # 

稀疏矩阵

torch.sparse_coo_tensor(indices, values, size) # indices 值的x-y坐标,size 稀疏矩阵的大小

相同值填充矩阵

torch.full(size, fill_value)

torch.full_like(input, fill_value)

随机矩阵生成

torch.rand(size) # 数值范围[0, 1), size = [2,3] or 2,3

torch.rand_like(input, dtype) # 形状和input相同

torch.randn(size)  # 标准正态分布 N(0,1)

torch.randn_like(input, dtype)

torch.randint(low = 0, high, size) # 整数范围[low, high),  e.g. torch.randint(3, 8, [2,3])

torch.randint_like(input, low = 0, high, dtype)

随机排列生成

torch.randperm(n) # 生成一个0到n-1的n-1个整数的随机排列

Example: 

torch.empty(5,3)

torch.ones(5)

torch.rand(5,3)

torch.zeros(5,3, dtype = torch.long)

x = torch.tensor([5.5, 3])

x = x.new_ones(5,3, dtype = torch.double)

x = torch.rand_like(x, dtype = torch.float)

矩阵操作函数

x.size()     # 获取矩阵形状 output: torch.Size([5,3])

y = torch.rand(5,3)

加法

a. x + y

b. torch.add(x, y)

c. result = torch.empty(5,3)

torch.add(x, y, out = result)

print(result)

d. y.add_(x)

访问元素

x[:,1]    # numpy-like

改变形状

x = torch.randn(4, 4)

y = x.view(16)

z = x.view(-1, 8)

获取数值

x = torch.randn(1)

x.item()

转换为numpy数组

a = torch.ones(5)

b = a.numpy()

(b的值会随着a改变而变化)

a.add_(1)

合并矩阵

torch.cat(tensors = (a,b,c), dim = 0, out = None) # 按照某一维度对多个矩阵进行合并, 0-行 1-列

拆分矩阵

torch.chunk(tensor, chunks, dim = 0) # 按照某一维度对矩阵进行切分

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据