张量tensor学习笔记

一.前言
  上篇博文我们介绍了numpy和pandas。这篇博文我们主要来介绍下pytorch里面的数据结构tensor。tensor是pytorch中最基础的知识,下面我们主要介绍tensor的基本创建方法。
二.tensor
2.1.tensor的简介
  tensor是什么,简单理解他就时可以用于pytorch计算的numpy,pytorch中的数据都是tensor,只有tensor才可以在pytorch中搭建神经网络,进行梯度反传,损失求导等操作。我们知道有标量,向量,矩阵,而张量就是他们三个的高维扩展。
在这里插入图片描述
2.1.tensor和variable
  在pytorch0.4.0版本之后,Variable就已经并入了tensor。但是我们还是要来看下什么是Variable。Variable是torch.autograd中的数据类型:
在这里插入图片描述
可以看到variable 总共有五个属性:

  • data:要创建的数据,就是被包装的tensor
  • grad:data的梯度
  • grad_fn:表示函数的意思,用于记录我们创建张量的时候所用到的方法,如:加减乘除等操作,这是自动求到的关键。
  • requires_grad:表示是否需要计算梯度
  • is_leaf:记录是否是叶子结点,只有叶子结点才可以计算梯度。

  所有的这些属性都是为了tensor的自动求导而设置的,从pytorch0.4.0版开始,variable并入了tensor, 看下tensor里面的属性:
在这里插入图片描述
可以看到tensor里面总共8个属性,其中5个来自variable,我们再来看下另外3个属性时干什么的:

  • dtype:tensor数据类型,如torch.FloatTensor, torch.cuda.FloatTensor, 用的最多的一般是float32和int64(torch.long)
  • shape:张量的形状,如(1,2,224,224)
  • device:tensor所在的设备,是CPU还是GPU

2.3.tensor的创建
2.3.1.直接创建
在这里插入图片描述

import torch

data = torch.tensor([[1, 2, 3],
                     [4, 5, 6]])
print(data)

输出:

tensor([[1, 2, 3],
        [4, 5, 6]])

  注意看,我们这里使用的是torch.tensor(),而不是torch.Tensor(),注意区分两者的区别,前者是个函数,后面是个类,虽然都能创建张量。具体可参考这个博文:Tensor和tensor的区别
2.3.2.通过numpy数组来创建

import numpy as np
import torch

arr = np.array(([[1, 2, 3],
                 [1, 2, 3]]))
print(arr.dtype)
print("*" * 100)
data = torch.from_numpy(arr)
print(data)

输出:

int32
****************************************************************************************************
tensor([[1, 2, 3],
        [1, 2, 3]], dtype=torch.int32)

  注意:通过numpy数组来创建tensor的时候,他们两个共享内存,也就是说创建的tensor和原始的numpy中只要有一个数据发生改变,另一个也会跟着变化。
2.3.3.依据数值创建
在这里插入图片描述
  其中layout表示布局,默认即可。out,表示输出张量,就是再把这个张量赋值给别的一个张量,但是这两个张量时一样的,指的同一个内存地址。

import torch

out_t = torch.tensor([1])
t = torch.zeros((3, 3), out=out_t)

print(out_t, '\n', t)
# 查看内存地址
print(id(t), "\n", id(out_t), "\n", id(t) == id(out_t))

输出:

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
2841767527992 
 2841767527992 
 True

类似的函数还有:

# 创建与input同形状的全0张量
torch.zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False) 
# 创建全1张量
torch.ones()
torch.ones_like()
torch.full()
torch.full_like()

我们挑一个torch.full()看一下:

在这里插入图片描述

import torch

data = torch.full((3,3), 6)
print(data)

输出:

tensor([[6, 6, 6],
        [6, 6, 6],
        [6, 6, 6]])
torch.arange()

在这里插入图片描述

import torch

data = torch.arange(1,10,3)
print(data)

输出:

tensor([1, 4, 7])

创建均分的1维张量, 数值区间[start, end] 注意这里都是闭区间,和上面的区分

torch.linspace()

在这里插入图片描述
其中steps表示总共多少个数,等间距分布

import torch

data = torch.linspace(2, 10, 5)   # tensor([2, 4, 6, 8, 10])
print(data)
print("*" * 100)
# 那么如果不是那么正好呢? 步长应该是多少?
data = torch.linspace(2, 10, 6)   # tensor([2, 3.6, 5.2, 6.8, 8.4, 10])
print(data)
# 这个步长是怎么算的?  (end-start) / (steps-1)

输出:

tensor([ 2.,  4.,  6.,  8., 10.])
****************************************************************************************************
tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])

对数均分数列:

torch.logspace()

在这里插入图片描述
base表示以多少为底数,默认是10。
创建单位阵:

torch.eye()

在这里插入图片描述
n, m分别是矩阵的行数和列数。
2.3.4.依概率分布创建张量

torch.normal(mean, std, size, out=None)

  mean是均值,std是标准差。 但是这个地方要注意, 根据mean和std,分别各有两种取值,所以这里会有四种模式:

  • mean为标量, std为标量
  • mean为标量, std为张量
  • mean为张量, std为标量
  • mean为张量,std为张量
    我们先来看个简单的例子:
import torch

mean = torch.arange(1., 11)
std = torch.arange(1, 0, -0.1)
print(mean)
print("*" * 80)
print(std)
print("*" * 80)
print(torch.normal(mean, std))

输出:

tensor([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
********************************************************************************
tensor([1.0000, 0.9000, 0.8000, 0.7000, 0.6000, 0.5000, 0.4000, 0.3000, 0.2000,
        0.1000])
********************************************************************************
tensor([2.4263, 2.0338, 2.3798, 4.5476, 5.1375, 6.9505, 6.9415, 8.2481, 9.0385,
        9.9140])

解释:

 1.5104#是从均值为1,标准差为1的正态分布中随机生成的
 1.6955#是从均值为2,标准差为0.9的正态分布中随机生成的
 2.4895
 4.9185
 4.9895
 6.9155
 7.3683
 8.1836
 8.7164
 9.8916
[torch.FloatTensor of size 10]

下面我们再来看下这个函数:

import numpy as np
import torch

# 第一种模式 - 均值是标量, 方差是标量 - 此时产生的是一个分布, 从这一个分部种抽样相应的个数,所以这个必须指定size,告诉函数我需要返回一个多大尺寸的正态分布
t_normal = torch.normal(0, 1, size=(4,))
print(t_normal)  # 来自同一个分布
print("*" * 80)
# 第二种模式 - 均值是标量, 方差是张量 - 此时会根据方差的形状大小,产生同样多个分布,每一个分布的均值都是那个标量
std = torch.arange(1, 5, dtype=torch.float)
print(std.dtype)
t_normal2 = torch.normal(1, std)
print("*" * 80)

print(t_normal2)  # 也产生来四个数,但是这四个数分别来自四个不同的正态分布,这些分布均值相等
print("*" * 80)

# 第三种模式 - 均值是张量,方差是标量 - 此时也会根据均值的形状大小,产生同样多个方差相同的分布,从这几个分布中分别取一个值作为结果
mean = torch.arange(1, 5, dtype=torch.float)
t_normal3 = torch.normal(mean, 1)
print(t_normal3)  # 来自不同的分布,但分布里面方差相等
print("*" * 80)

# 第四种模式 - 均值是张量, 方差是张量 - 此时需要均值的个数和方差的个数一样多,分别产生这么多个正太分布,从这里面抽取一个值
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal4 = torch.normal(mean, std)
print(t_normal4)  # 来自不同的分布,各自有自己的均值和方差

输出:

tensor([-0.7101,  1.0485,  0.8961,  0.8354])
********************************************************************************
torch.float32
********************************************************************************
tensor([2.3115, 2.4494, 3.0079, 0.2093])
********************************************************************************
tensor([2.7496, 3.6858, 3.6740, 2.3840])
********************************************************************************
tensor([ 0.0470,  1.0331,  2.5253, 10.4956])

创建标准正态分布:

torch.randn()
torch.randn_like()

创建均匀分布

torch.rand()
torch.rand_like()

创建整数均匀分布:

torch.randint()
torch.randint_like()

创建从0 - n-1的随机排列:

torch.randperm(n)

创建以input为概率,生成伯努利分布(0-1分布,两点分布):

torch.bernoulli(input)

三.张量的操作
  上面介绍了一些张量的创建方法,下面我们再来讲下怎么对这些张量进行操作,如:切片,索引,变换等。
3.1基本操作
3.1.1拼接

torch.cat(tensors, dim=0, out=None)

将张量按照dim维度进行拼接,tensors表示要拼接的张量

import numpy as np
import torch

# 张量的拼接
t = torch.ones((2, 3))
print(t)
print("*" * 80)
t_0 = torch.cat((t, t), dim=0)       # 行拼接
t_1 = torch.cat((t, t), dim=1)    # 列拼接
print(t_0, t_0.shape)
print("*" * 80)

print(t_1, t_1.shape)


输出:

tensor([[1., 1., 1.],
        [1., 1., 1.]])
********************************************************************************
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]) torch.Size([4, 3])
********************************************************************************
tensor([[1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1.]]) torch.Size([2, 6])
torch.stack(tensors, dim=0, out=None)

  在新创建的维度dim上进行拼接, tensors表示张量序列, dim要拼接的维度。就是 stack会新创建一个维度,然后完成拼接。

# 张量的拼接
t = torch.ones((2, 3))
print(t)
print("*" * 80)
t_stack = torch.stack([t,t,t], dim=0)
print(t_stack)
print("*" * 80)

print(t_stack.shape)
print("*" * 80)

t_stack1 = torch.stack([t, t, t], dim=1)
print(t_stack1)
print("*" * 80)

print(t_stack1.shape)

输出:

tensor([[1., 1., 1.],
        [1., 1., 1.]])
********************************************************************************
tensor([[[1., 1., 1.],
         [1., 1., 1.]],

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

        [[1., 1., 1.],
         [1., 1., 1.]]])
********************************************************************************
torch.Size([3, 2, 3])
********************************************************************************
tensor([[[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]],

        [[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]]])
********************************************************************************
torch.Size([2, 3, 3])

3.1.2切分

torch.chunk(input, chunks, dim=0)

  将张量按维度dim进行平均切分, 返回值是张量列表,注意,如果不能整除, 最后一份张量小于其他张量。 chunks代表要切分的维度。

import torch

# 张量的拼接
a = torch.ones((2, 7))  # 7
list_of_tensors = torch.chunk(a, dim=1, chunks=3)  # 第一个维度切成三块, 那么应该是(2,3), (2,3), (2,1)  因为7不能整除3,所以每一份应该向上取整,最后不够的有多少算多少
print(list_of_tensors)
for idx, t in enumerate(list_of_tensors):
        print("第{}个张量:{}, shape is {}".format(idx + 1, t, t.shape))
torch.split(tensor, split_size_or_sections, dim=0)

  这个也是将张量按维度dim切分,但是这个更加强大, 可以指定切分的长度, split_size_or_sections为int时表示每一份的长度, 为list时,按list元素切分。必须事先计算好每个切分的长度,总和加一块等于总长度。

import torch
# split
t = torch.ones((2, 5))

list_of_tensors = torch.split(t, [2, 1, 2], dim=1)  # [2 , 1, 2], 这个要保证这个list的大小正好是那个维度的总大小,这样才能切
for idx, t in enumerate(list_of_tensors):
    print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))

3.1.3索引

torch.index_select(input, dim, index, out=None)

在维度dim上,按index索引数据,返回值,以index索引数据拼接的张量。

import torch

t = torch.randint(0, 9, size=(3, 3))     #  从0-8随机产生数组成3*3的矩阵
print(t)
print("*" * 80)
idx = torch.tensor([0, 2], dtype=torch.long)   # 这里的类型注意一下,要是long类型
t_select = torch.index_select(t, dim=1, index=idx)  #第0列和第2列拼接返回
print(t_select)
tensor([[6, 6, 2],
        [4, 4, 2],
        [2, 0, 8]])
********************************************************************************
tensor([[6, 2],
        [4, 2],
        [2, 8]])

torch.masked_select(input, mask, out=None)

   按mask中的True进行索引,返回值:一维张量。 input表示要索引的张量, mask表示与input同形状的布尔类型的张量。 这种情况在选择符合某些特定条件的元素的时候非常好使, 注意这个是返回一维的张量。

import torch
t = torch.randint(0, 9, size=(3, 3))     #  从0-8随机产生数组成3*3的矩阵
mask = t.ge(5)   # le表示<=5, ge表示>=5 gt >5  lt <5
print("mask: \n", mask)
print("*" * 80)
t_select1 = torch.masked_select(t, mask)   # 选出t中大于5的元素
print(t_select1)
mask: 
 tensor([[ True, False, False],
        [False, False, False],
        [ True, False, False]])
********************************************************************************
tensor([5, 8])

3.1.4变换

torch.reshape(input, shape)

  变换张量的形状,这个很常用,input表示要变换的张量,shape表示新张量的形状。 但注意,当张量在内存中是连续时, 新张量与input共享数据内存。

import torch
# torch.reshape
t = torch.randperm(8)       # randperm是随机排列的一个函数
print(t)
print("*" * 80)
t_reshape = torch.reshape(t, (-1, 2, 2))    # -1的话就是根据后面那两个参数,计算出-1这个值,然后再转
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
print("*" * 80)
t[0] = 1024
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
print("*" * 80)
print("t.data 内存地址:{}".format(id(t.data)))
print("*" * 80)
print("t_reshape.data 内存地址:{}".format(id(t_reshape.data))) # 这个注意一下,两个是共内存的

输出:

tensor([6, 5, 0, 2, 1, 7, 4, 3])
********************************************************************************
t:tensor([6, 5, 0, 2, 1, 7, 4, 3])
t_reshape:
tensor([[[6, 5],
         [0, 2]],

        [[1, 7],
         [4, 3]]])
********************************************************************************
t:tensor([1024,    5,    0,    2,    1,    7,    4,    3])
t_reshape:
tensor([[[1024,    5],
         [   0,    2]],

        [[   1,    7],
         [   4,    3]]])
********************************************************************************
t.data 内存地址:1970095237304
********************************************************************************
t_reshape.data 内存地址:1970095237304
torch.transpose(input, dim0, dim1)

  交换张量的两个维度, 矩阵的转置常用, 在图像的预处理中常用, dim0, dim1表示要交换的维度题。

import torch
t = torch.rand((2, 3, 4))      # 产生0-1之间的随机数
print(t)
print("*" * 80)
t_transpose = torch.transpose(t, dim0=0, dim1=2)    # c*h*w     h*w*c, 这表示第0维和第2维进行交换
print("t shape:{}\nt_transpose shape: {}".format(t.shape, t_transpose.shape))

输出:

tensor([[[0.3864, 0.4362, 0.1226, 0.4043],
         [0.5839, 0.2080, 0.4125, 0.0041],
         [0.4701, 0.8920, 0.7798, 0.5639]],

        [[0.3524, 0.5536, 0.2164, 0.0231],
         [0.8450, 0.3551, 0.3100, 0.8345],
         [0.4601, 0.6818, 0.0190, 0.3050]]])
********************************************************************************
t shape:torch.Size([2, 3, 4])
t_transpose shape: torch.Size([4, 3, 2])
torch.t(input)

2维张量的转置, 对矩阵而言,相当于torch.transpose(inpuot, 0,1)

torch.squeeze(input, dim=None, out=None)

  压缩长度为1的维度, dim若为None,移除所有长度为1的轴,若指定维度,当且仅当该轴长度为1时可以被移除。

import torch
# torch.squeeze
t = torch.rand((1, 2, 3, 1))
t_sq = torch.squeeze(t)
t_0 = torch.squeeze(t, dim=0)
t_1 = torch.squeeze(t, dim=1)
print(t.shape)        # torch.Size([1, 2, 3, 1])
print("*" * 80)
print(t_sq.shape)     # torch.Size([2, 3])
print("*" * 80)
print(t_0.shape)     # torch.Size([2, 3, 1])
print("*" * 80)
print(t_1.shape)     # torch.Size([1, 2, 3, 1])

输出:

torch.Size([1, 2, 3, 1])
********************************************************************************
torch.Size([2, 3])
********************************************************************************
torch.Size([2, 3, 1])
********************************************************************************
torch.Size([1, 2, 3, 1])

3.2.数学运算
可以分为三大类: 加减乘除, 对数指数幂函数,三角函数。
在这里插入图片描述
  其中,torch.add(input, alpha=1, other, out=None)这个函数有个小细节,注意这里有个alpha,叫做乘项因子。类似权重的个东西,他可以让计算变得更加简洁, 比如线性回归我们知道有个y = wx + b, 在这里直接一行代码torch.add(b, w, x)就搞定。 类似的还有两个方法:

torch.addcdiv(input, value=1, tensor1, tensor2, out=None)

用于实现:
 out  i =  input  i +  value  ×  tensor  i  tensor  2 i \text { out }_{\mathrm{i}}=\text { input }_{\mathrm{i}}+\text { value } \times \frac{\text { tensor }_{\mathrm{i}}}{\text { tensor } 2_{\mathrm{i}}}  out i= input i+ value × tensor 2i tensor i

torch.addcmul(input, value=1, tensor1, tensor2, out=None)

用于实现:
 out  i =  input  i +  value  ×  tensor1  i ×  tensor 2 i \text { out }_{\mathrm{i}}=\text { input }_{\mathrm{i}}+\text { value } \times \text { tensor1 }_{\mathrm{i}} \times \text { tensor 2}_{\mathrm{i}}  out i= input i+ value × tensor1 i× tensor 2i

import torch
t_0 = torch.randn((3, 3))
t_1 = torch.ones_like(t_0)
t_add = torch.add(t_0, 10, t_1)

print("t_0:\n{}\nt_1:\n{}\nt_add_10:\n{}".format(t_0, t_1, t_add))

输出:

t_0:
tensor([[-0.7433,  1.2275,  1.4047],
        [ 0.1318, -0.0956,  0.9763],
        [-1.3330, -0.8972, -0.5193]])
t_1:
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
t_add_10:
tensor([[ 9.2567, 11.2275, 11.4047],
        [10.1318,  9.9044, 10.9763],
        [ 8.6670,  9.1028,  9.4807]])

3.2.1向量运算
  向量运算符只在一个特定轴上运算,将一个向量映射到一个标量或者另外一个向量。

import torch
#统计值
a = torch.arange(1,10).float()
print(torch.sum(a))
print("*" * 80)
print(torch.mean(a))
print("*" * 80)
print(torch.max(a))
print("*" * 80)
print(torch.min(a))
print("*" * 80)
print(torch.prod(a)) #累乘
print("*" * 80)
print(torch.std(a))  #标准差
print("*" * 80)
print(torch.var(a))  #方差
print("*" * 80)
print(torch.median(a)) #中位数

输出:

tensor(45.)
********************************************************************************
tensor(5.)
********************************************************************************
tensor(9.)
********************************************************************************
tensor(1.)
********************************************************************************
tensor(362880.)
********************************************************************************
tensor(2.7386)
********************************************************************************
tensor(7.5000)
********************************************************************************
tensor(5.)

import torch
#cum扫描
a = torch.arange(1,10)
print(torch.cumsum(a,0))    # 累加
print("*" * 80)
print(torch.cumprod(a,0))    # 累乘
print("*" * 80)
print(torch.cummax(a,0).values)
print("*" * 80)
print(torch.cummax(a,0).indices)
print("*" * 80)
print(torch.cummin(a,0))

输出:

tensor([ 1,  3,  6, 10, 15, 21, 28, 36, 45])
********************************************************************************
tensor([     1,      2,      6,     24,    120,    720,   5040,  40320, 362880])
********************************************************************************
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
********************************************************************************
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8])
********************************************************************************
torch.return_types.cummin(
values=tensor([1, 1, 1, 1, 1, 1, 1, 1, 1]),
indices=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0]))

import torch

# 排序
# torch.sort和torch.topk可以对张量排序
a = torch.tensor([[9, 7, 8], [1, 3, 2], [5, 6, 4]]).float()
print(torch.topk(a, 2, dim=0), "\n")
print("*" * 80)
print(torch.topk(a, 2, dim=1), "\n")
print("*" * 80)
print(torch.sort(a, dim=1), "\n")
# 利用torch.topk可以在Pytorch中实现KNN算法

输出:

torch.return_types.sort(
values=tensor([[7., 8., 9.],
        [1., 2., 3.],
        [4., 5., 6.]]),
indices=tensor([[1, 2, 0],
        [0, 2, 1],
        [2, 0, 1]])) 

3.2.2矩阵运算
矩阵必须是二维的。类似torch.tensor([1,2,3])这样的不是矩阵。

矩阵运算包括:矩阵乘法,矩阵转置,矩阵逆,矩阵求迹,矩阵范数,矩阵行列式,矩阵求特征值,矩阵分解等运算。
乘法:

import torch

#矩阵乘法
a = torch.tensor([[1,2],[3,4]])
b = torch.tensor([[2,0],[0,2]])
print(a@b)  #等价于torch.matmul(a,b) 或 torch.mm(a,b)

输出:

tensor([[2, 4],
        [6, 8]])

转置:

import torch
#矩阵转置
a = torch.tensor([[1.0,2],[3,4]])
print(a.t())

tensor([[1., 3.],
        [2., 4.]])

矩阵求逆:

import torch
#矩阵逆,必须为浮点类型
a = torch.tensor([[1.0,2],[3,4]])
print(torch.inverse(a))

tensor([[-2.0000,  1.0000],
        [ 1.5000, -0.5000]])

矩阵求迹:

import torch
#矩阵求trace
a = torch.tensor([[1.0,2],[3,4]])
print(torch.trace(a))
tensor(5.)

求范数和行列式:

import torch
#矩阵求范数
a = torch.tensor([[1.0,2],[3,4]])
print(torch.norm(a))
print("*" * 80)
#矩阵行列式
a = torch.tensor([[1.0,2],[3,4]])
print(torch.det(a))
tensor(5.4772)
********************************************************************************
tensor(-2.0000)

特征值和特征向量:

import torch

# 矩阵特征值和特征向量
a = torch.tensor([[1.0, 2], [-5, 4]], dtype=torch.float)
print(torch.eig(a, eigenvectors=True))
torch.return_types.eig(
eigenvalues=tensor([[ 2.5000,  2.7839],
        [ 2.5000, -2.7839]]),
eigenvectors=tensor([[ 0.2535, -0.4706],
        [ 0.8452,  0.0000]]))

QR分解:

import torch

# 矩阵QR分解, 将一个方阵分解为一个正交矩阵q和上三角矩阵r
# QR分解实际上是对矩阵a实施Schmidt正交化得到q

a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
q, r = torch.qr(a)
print(q, "\n")
print(r, "\n")
print(q @ r)
tensor([[-0.3162, -0.9487],
        [-0.9487,  0.3162]]) 

tensor([[-3.1623, -4.4272],
        [ 0.0000, -0.6325]]) 

tensor([[1.0000, 2.0000],
        [3.0000, 4.0000]])

SVD分解:

import torch

# 矩阵svd分解
# svd分解可以将任意一个矩阵分解为一个正交矩阵u,一个对角阵s和一个正交矩阵v.t()的乘积
# svd常用于矩阵压缩和降维
a = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])

u, s, v = torch.svd(a)

print(u, "\n")
print(s, "\n")
print(v, "\n")

print(u @ torch.diag(s) @ v.t())

# 利用svd分解可以在Pytorch中实现主成分分析降维

tensor([[-0.2298,  0.8835],
        [-0.5247,  0.2408],
        [-0.8196, -0.4019]]) 

tensor([9.5255, 0.5143]) 

tensor([[-0.6196, -0.7849],
        [-0.7849,  0.6196]]) 

tensor([[1.0000, 2.0000],
        [3.0000, 4.0000],
        [5.0000, 6.0000]])

注意:以上讲的tensor在用于pytorch的时候必须是浮点类型,否者报错。
欢迎给位大佬批评指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

I松风水月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值