add函数 pytorch_PyTorch常用函数摘抄

本文介绍了PyTorch中的一些基本矩阵创建和操作函数,包括torch.tensor、torch.empty、torch.zeros、torch.ones、torch.eye等,以及随机矩阵生成、稀疏矩阵创建、加法操作、元素访问、形状变换、数值获取、转换为numpy数组和矩阵合并拆分等实用功能。
摘要由CSDN通过智能技术生成

1. 导入pytorch

from __future__ import print_function

import torch

2.常用矩阵创建函数

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

torch.as_tensor(data)

torch.from_numpy(ndarray)

torch.empty(size)

torch.empty_like(input)

2.1 全零/全一/单位矩阵

torch.zeros(size)

torch.zeros_like(input, dtype)

torch.ones(size)

torch.ones_like(input, dtype)

torch.eye(size)

2.2 序列生成

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) #

2.3 稀疏矩阵

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

2.4 相同值填充矩阵

torch.full(size, fill_value)

torch.full_like(input, fill_value)

2.5 随机矩阵生成

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)

2.6 随机排列生成

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)

3.矩阵操作函数

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

y = torch.rand(5,3)

3.1 加法

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)

3.2 访问元素

x[:,1]    # numpy-like

3.3 改变形状

x = torch.randn(4, 4)

y = x.view(16)

z = x.view(-1, 8)

3.4 获取数值

x = torch.randn(1)

x.item()

3.5 转换为numpy数组

a = torch.ones(5)

b = a.numpy()

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

a.add_(1)

3.6 合并矩阵

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

3.7 拆分矩阵

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值