pytorch.tensor常见操作

1. torch.randperm

  • 作用:返回从0到n - 1的整数的随机排列。特别适合生成相关数据
torch.randperm(n, *, generator=None, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor
  • 代码
import torch
num_rows, num_cols = 3,4
x = torch.randperm(num_rows*num_cols).reshape(num_rows,num_cols)
print(f"x={x}")
print(f"x.shape={x.shape}")
  • 结果:
x=tensor([[ 9,  5,  3, 11],
        [ 8,  0,  7,  6],
        [ 4,  2, 10,  1]])
x.shape=torch.Size([3, 4])

2. torch.repeat_interleave

  • 作用: 重复张量中的元素
  • 说明
torch.repeat_interleave(input, repeats, dim=None, *, output_size=None) → Tensor
  • input: 输入的张量
  • repeats: 每个元素的重复次数。可以通过给定轴的形状进行复制
  • dim: 用来重复值的维度。默认情况下,使用平坦输入数组,并返回一个平坦输出数组。
  • 代码
# -*- coding: utf-8 -*-
# @Project: zc
# @Author: zc
# @File name: repeatleave_test
# @Create time: 2022/2/12 21:45

import torch

# 1. 直接通过张量的属性进行复制
x_1 = torch.tensor([1, 2, 3])
y_1 = x_1.repeat_interleave(3)
print(f"x_1={x_1}")
print(f"y_1={y_1}")

# 2. 传入多维张量A,A先展平后再进行复制
x_2 = torch.tensor([[1, 2, 3], [4, 5, 6]])
y_2 = torch.repeat_interleave(x_2, 3)
print(f"x_2={x_2}")
print(f"y_2={y_2}")

# 3. 传入多维张量A,按指定维度进行复制;
# dim=0 ;表示按行进行堆砌;
# dim=1 ;表示按列进行并列
y_3_dim_0 = torch.repeat_interleave(x_2, 3, dim=0)
print(f"y_3_dim_0={y_3_dim_0}")
y_3_dim_1 = torch.repeat_interleave(x_2, 3, dim=1)
print(f"y_3_dim_1={y_3_dim_1}")

# 4. torch.repeat_interleave(A,B,dim=0)
# 表示的是 A 按照 B 中的数值进行个数的复制,比如,[2,3]表示第一个复制2行,第二个复制3行
y_5_tensor = torch.repeat_interleave(x_2, torch.tensor([2, 3]), dim=0)
print(f"y_5_tensor={y_5_tensor}")
  • 结果:
x_1=tensor([1, 2, 3])
y_1=tensor([1, 1, 1, 2, 2, 2, 3, 3, 3])
x_2=tensor([[1, 2, 3],
        [4, 5, 6]])
y_2=tensor([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6])
y_3_dim_0=tensor([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3],
        [4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]])
y_3_dim_1=tensor([[1, 1, 1, 2, 2, 2, 3, 3, 3],
        [4, 4, 4, 5, 5, 5, 6, 6, 6]])
y_5_tensor=tensor([[1, 2, 3],
        [1, 2, 3],
        [4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]])

3. torch.linspace

  • 作用:创建大小步长的一维张量,其值从头到尾(包括从头到尾)均匀间隔
  • 代码:
import torch

# x的间隔=(10-3)/(5-1)=1.75
x = torch.linspace(3, 10, steps=5)
# y的间隔=(10+10)/(5-1)=5
y = torch.linspace(-10, 10, steps=5)
z = torch.linspace(start=-10, end=10, steps=1)
print(f"x={x}")
print(f"y={y}")
print(f"z={z}")
  • 结果:
x=tensor([ 3.0000,  4.7500,  6.5000,  8.2500, 10.0000])
y=tensor([-10.,  -5.,   0.,   5.,  10.])
z=tensor([-10.])

4. torch.bmm

  • 作用:将mat1和mat2中矩阵进行批量矩阵乘积。
  • 注意:mat1.shape = (batch_size,a,b); mat2.shape=(batch_size,b,c)
import torch 

mat1 = torch.arange(6).reshape((1, 2, 3))
mat2 = torch.arange(12).reshape((1, 3, 4))
# 批量数不变,A=(2,3);B=(3,4);C=(2,4)
# output.shape=(1,2,4) 
output = torch.bmm(mat1, mat2)
print(f"mat1={mat1}")
print(f"mat1.shape={mat1.shape}")
print(f"mat2={mat2}")
print(f"mat2.shape={mat2.shape}")

print(f"output={output}")
print(f"output.shape={output.shape}")
  • 结果:
mat1=tensor([[[0, 1, 2],
         [3, 4, 5]]])
mat1.shape=torch.Size([1, 2, 3])
mat2=tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7],
         [ 8,  9, 10, 11]]])
mat2.shape=torch.Size([1, 3, 4])
output=tensor([[[20, 23, 26, 29],
         [56, 68, 80, 92]]])
output.shape=torch.Size([1, 2, 4])

5. tensor.repeat

  • 作用:将 张量进行复制,可以指定维度进行复制;传入的参数一定要大于给定的维度;

6. tensor.transpose

  • 作用:将张量的给定维度进行调换
  • 代码:
import torch

x = torch.ones(3, 4, 5, 6)
m = torch.tensor([1, 2, 3])
# 将m复制2行4列
m_repeat_2_4 = m.repeat(2, 4)
# 将x的第0行复制2遍,第1行复制3遍,第4行复制5遍
x_repeat = x.repeat(2, 3, 4, 5)
# 如果大于给定维度x ,那么在新的一维复制8遍
x_repeat_2 = x.repeat(8, 1, 1, 1, 1)
print(f"x.shape={x.shape}")
print(f"x_repeat.shape={x_repeat.shape}")
print(f"x_repeat_2.shape={x_repeat_2.shape}")
print(f"m.shape={m.shape}")
print(f"m_repeat_2_4.shape={m_repeat_2_4.shape}")
# 将x的第2维和第1维进行调换顺序
x_transpose_2_1 = x.transpose(2, 1)
# 将x的第3维和第2维进行调换顺序
x_transpose_3_2 = x.transpose(3, 2)
print(f"x_transpose_2_1.shape={x_transpose_2_1.shape}")
print(f"x_transpose_3_2.shape={x_transpose_3_2.shape}")
  • 结果:
x.shape=torch.Size([3, 4, 5, 6])
x_repeat.shape=torch.Size([6, 12, 20, 30])
x_repeat_2.shape=torch.Size([8, 3, 4, 5, 6])
m.shape=torch.Size([3])
m_repeat_2_4.shape=torch.Size([2, 12])
x_transpose_2_1.shape=torch.Size([3, 5, 4, 6])
x_transpose_3_2.shape=torch.Size([3, 4, 6, 5])

7.torch.eye

返回一个二维张量,对角线上为1,其他地方为0。可以根据输入值来确认生成对角矩阵的大小

import torch

# 创建一个4x4大小的矩阵,保证矩阵对角线为1,其他位置为0
x_1 = torch.eye(4)

# 创建一个4x5大小的矩阵,保证矩阵对角线为1,如果为长方形,就以短边为主
x_2 = torch.eye(4,5)
x_3 = torch.eye(6,4)
print(f"x_1={x_1}")
print(f"x_1.shape={x_1.shape}")
print(f"x_2={x_2}")
print(f"x_2.shape={x_2.shape}")
print(f"x_3={x_3}")
print(f"x_3.shape={x_3.shape}")

8. torch.sort

将输入张量的元素沿着给定的维度按值升序排序。

torch.sort(input, dim=- 1, descending=False, stable=False, *, out=None)
  • input:输入的张量
  • dim: 排序的维度
  • descending: 控制排序顺序(升序或降序)
  • stable:使排序例程稳定,这保证了等价元素的顺序被保留。
  • out:(张量,长张量)的输出元组,可以被任意指定用作输出缓冲区
# sorted:返回排好位置的值
# indices:返回值的坐标位置
sorted,indices = torch.sort(x)
import torch
# 在[0,10]范围内进行选整数值,创建一个(3,4)大小的矩阵
x = torch.randint(0, 10, (3, 4))
print(f"x={x}")
# 将x进行排序,sorted用来存储值,indices用来存储值对应的原来的坐标
sorted, indices = torch.sort(x)
print(f"sorted={sorted}")
print(f"indices={indices}")

9. torch.randint

返回一个张量,张量由低(包含)和高(不包含)之间均匀生成的随机整数填充。
即:给定一个初始的最低值,给定一个初始的最大值,在[lower,higher)之间随机均匀生成相关整数

torch.randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
  • 测试代码
import torch
# 在[3,8)之间随机生成整数,矩阵为10
x = torch.randint(3,8,(10,))
print(f"x={x}")
print(f"x.shape={x.shape}")
# 在[2,10)之间随机生成整数,矩阵为(2,2)
y = torch.randint(2,10,(2,2))
print(f"y={y}")
print(f"y.shape={y.shape}")
  • 结果
x=tensor([6, 5, 3, 3, 5, 4, 3, 7, 6, 6])
x.shape=torch.Size([10])
y=tensor([[4, 6],
        [3, 4]])
y.shape=torch.Size([2, 2])

10. torch.normal

返回一个由不同正态分布的随机数组成的张量,其均值和标准差已给出。

torch.normal(mean, std, *, generator=None, out=None) → Tensor
  • mean:均值;std:方差
# 从一个正太分布中(均值=0,方差=1)随机抽取值,组成一个3行4列的矩阵
x = torch.normal(0, 1, (3, 4))
print(f"x={x}")
print(f"x.shape={x.shape}")
# x=tensor([[-0.1513, -0.2133, -0.3154,  0.6668],
        [-0.0857, -0.5767,  1.0119,  0.5001],
        [-1.4901,  3.9077,  0.4591,  0.2615]])
# x.shape=torch.Size([3, 4])

11. torch.arange

返回一个1-D形状的张量, d = ⌈ e n d − s t a r t s t e p ⌉ d=\lceil \frac{end-start}{step}\rceil d=stependstart;数据是[start,end);注意是左闭右开的选择

  • 注:torch.range:未来版本中已经弃用;
  • 代码测试
x_1 = torch.arange(1, 10, 0.5)
print(f"x_1={x_1}")
print(f"x_1.shape={x_1.shape}")
x_2 = torch.arange(5)
print(x_2)
print(x_2.shape)
x_3 = torch.arange(1,6)
print(f"x_3={x_3}")
print(f"x_3.shape={x_3.shape}")
  • 结果:
import torch
x_1=tensor([1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000, 4.5000, 5.0000,
        5.5000, 6.0000, 6.5000, 7.0000, 7.5000, 8.0000, 8.5000, 9.0000, 9.5000])
x_1.shape=torch.Size([18])
tensor([0, 1, 2, 3, 4])
torch.Size([5])
x_3=tensor([1, 2, 3, 4, 5])
x_3.shape=torch.Size([5])

12. torch.rand & torch.randn

  • torch.rand:返回一个张量,里面填满了均匀分布在区间[0,1)[0,1)上的随机数。张量的形状由变量的大小来定义
  • torch.randn:返回一个张量,里面填满了均值为0、方差为1的正态分布(也称为标准正态分布)中的随机数。
  • 区别:rand是采样自均匀分布,randn是采样自正太分布

13. torch.sum

返回输入Tensor中的所有元素的总和;

14. torch.pow

求指数函数;torch.pow(x,y);
o u t p u t = x y output=x^y output=xy

import torch

x = torch.arange(5)
pow_10_x = torch.pow(10,x)
pow_x_10 = torch.pow(x,10)
print(f"x={x}")
print(f"pow_10_x={pow_10_x}")
print(f"pow_x_10={pow_x_10}")
x=tensor([0, 1, 2, 3, 4])
pow_10_x=tensor([    1,    10,   100,  1000, 10000])
pow_x_10=tensor([      0,       1,    1024,   59049, 1048576])

15. X[0::2],Y[0::2]

通过X[0::2],Y[0::2]来获得一个张量X中的奇数或偶数列
X[a::b]表示以a开头,以b为间隔进行取值

import torch

x = torch.arange(10)
# 表示以0开头,以2为间隔进行取值,得到偶数列
x_0_2 = x[0::2]
# 表示以1开头,以2为间隔进行取值,得到奇数列
x_1_2= x[1::2]
x_0_3 = x[0::3]
x_1_3 = x[1::3]
print(f"x={x}")
print(f"x_0_2={x_0_2}")
print(f"x_1_2={x_1_2}")
print(f"x_0_3={x_0_3}")
print(f"x_1_3={x_1_3}")
x=tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x_0_2=tensor([0, 2, 4, 6, 8])
x_1_2=tensor([1, 3, 5, 7, 9])
x_0_3=tensor([0, 3, 6, 9])
x_1_3=tensor([1, 4, 7])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值