代码记录(3)

目录

torch.mul

torch.mm

torch.matmul

【pytorch】torch.rand()  均匀分布

【pytorch】torch.randn()  标准正态分布

【pytorch】torch.normal()  离散正态分布

【pytorch】torch.linespace()  线性间距向量

【pytorch】unsqueeze()

【pytorch】squeeze()

torch.nn.Parameter()

def pairwise_distances(x, y):

assert

torch.max(input, dim):

torch.cat() 


torch.mul

点乘都是broadcast的,可以用torch.mul(a, b)实现,也可以直接用*实现。

>>> a = torch.ones(3,4)
>>> a
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
>>> b = torch.Tensor([1,2,3]).reshape((3,1))
>>> b
tensor([[1.],
        [2.],
        [3.]])
>>> torch.mul(a, b)
tensor([[1., 1., 1., 1.],
        [2., 2., 2., 2.],
        [3., 3., 3., 3.]])

当a, b维度不一致时,会自动填充到相同维度相点乘。


矩阵相乘有torch.mm和torch.matmul两个函数。其中前一个是针对二维矩阵,后一个是高维。当torch.mm用于大于二维时将报错。

 

torch.mm

>>> a = torch.ones(3,4)
>>> b = torch.ones(4,2)
>>> torch.mm(a, b)
tensor([[4., 4.],
        [4., 4.],
        [4., 4.]])

 

torch.matmul

>>> a = torch.ones(3,4)
>>> b = torch.ones(5,4,2)
>>> torch.matmul(a, b).shape
torch.Size([5, 3, 2])
>>> a = torch.ones(5,4,2)
>>> b = torch.ones(5,2,3)
>>> torch.matmul(a, b).shape
torch.Size([5, 4, 3])
>>> a = torch.ones(5,4,2)
>>> b = torch.ones(5,2,3)
>>> torch.matmul(b, a).shape
报错。

 

【pytorch】torch.rand()  均匀分布

torch.rand(*sizes, out=None) → Tensor

返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数。张量的形状由参数sizes定义。

参数:

  • sizes (int…) - 整数序列,定义了输出张量的形状
  • out (Tensor, optinal) - 结果张量
import torch
torch.rand(2, 3) 

tensor([[0.3423, 0.6812, 0.0086],
        [0.1165, 0.3162, 0.0455]])

 

【pytorch】torch.randn()  标准正态分布

torch.randn(*sizes, out=None) → Tensor

返回一个张量,包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数。张量的形状由参数sizes定义。

参数:

  • sizes (int…) - 整数序列,定义了输出张量的形状
  • out (Tensor, optinal) - 结果张量
import torch
torch.randn(2, 3) 

tensor([[-0.6150, -0.5125, -0.6214],
        [-0.2230, -0.1409,  0.3014]])

 

【pytorch】torch.normal()  离散正态分布

torch.normal(means, std, out=None) → → Tensorv

返回一个张量,包含了从指定均值means和标准差std的离散正态分布中抽取的一组随机数。

标准差std是一个张量,包含每个输出元素相关的正态分布标准差。

参数:

  • means (float, optional) - 均值
  • std (Tensor) - 标准差
  • out (Tensor) - 输出张量
>>> torch.normal(mean=0.5, std=torch.arange(1, 6))
 
  0.5723
  0.0871
 -0.3783
 -2.5689
 10.7893
[torch.FloatTensor of size 5]
 

 

【pytorch】torch.linespace()  线性间距向量

torch.linspace(start, end, steps=100, out=None) → Tensor

返回一个1维张量,包含在区间start和end上均匀间隔的step个点。

输出张量的长度由steps决定。

参数:

  • start (float) - 区间的起始点
  • end (float) - 区间的终点
  • steps (int) - 在start和end间生成的样本数
  • out (Tensor, optional) - 结果张量
import torch
torch.linspace(3, 10, steps=5) 

tensor([ 3.0000,  4.7500,  6.5000,  8.2500, 10.0000])

 

【pytorch】unsqueeze()

1. 首先初始化一个a

a = torch.arange(0,6)
b = a.view(2,3)
print(b)

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

可以看出a的维度为(2,3)

2. 在第二维增加一个维度,使其维度变为(2,1,3)

print(b.unsqueeze(1))
print(b.unsqueeze(1).size())

tensor([[[0, 1, 2]],

        [[3, 4, 5]]])
torch.Size([2, 1, 3])

可以看出a的维度已经变为(2,1,3)了,同样如果需要在倒数第二个维度上增加一个维度,那么使用b.unsqueeze(-2)

 

【pytorch】squeeze()

1. 首先得到一个维度为(1,2,3)的tensor(张量)

c = b.unsqueeze(0)
c

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

由图中可以看出c的维度为(1,2,3)

2.下面使用squeeze()函数将第一维去掉

c.squeeze(-3)

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

3.另外

c.squeeze(-2)

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

可以看出维度并没有变化,仍然为(1,2,3),这是因为只有维度为1时才会去掉。

c.squeeze(0)
tensor([[0, 1, 2],
        [3, 4, 5]])

isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。

isinstance() 与 type() 区别:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。

  • isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

语法

以下是 isinstance() 方法的语法:

isinstance(object, classinfo)

参数

  • object -- 实例对象。
  • classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。

返回值

如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True
class A:
    pass
 
class B(A):
    pass
 
isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

torch.nn.Parameter()

torch.nn.Parameter是继承自torch.Tensor的子类,其主要作用是作为nn.Module中的可训练参数使用。

它与torch.Tensor的区别就是nn.Parameter会自动被认为是module的可训练参数,即加入到parameter()这个迭代器中去;

而module中非nn.Parameter()的普通tensor是不在parameter中的。

注意到,nn.Parameter的对象的requires_grad属性的默认值是True,即是可被训练的,这与torth.Tensor对象的默认值相反。

在nn.Module类中,pytorch也是使用nn.Parameter来对每一个module的参数进行初始化的。

def pairwise_distances(x, y):

def pairwise_distances(x, y):
    '''
    Input: x is a Nxd matrix
           y is a Mxd matirx
    Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]
    i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2

    Advantage: Less memory requirement O(M*d + N*d + M*N) instead of O(N*M*d)
    Computationally more expensive? Maybe, Not sure.
    adapted from: https://discuss.pytorch.org/t/efficient-distance-matrix-computation/9065/2
    '''
    x_norm = (x ** 2).sum(1).view(-1, 1)
    y_norm = (y ** 2).sum(1).view(1, -1)
    y_t = torch.transpose(y, 0, 1)

    # a^2 + b^2 - 2ab
    dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t)
    # dist[dist != dist] = 0 # replace nan values with 0
    return dist

assert

def testAssert():
    try:
        int_var = int(input("please enter a positive number:"))
        # 如果输入的数值不大于0,断言失败,抛出异常
        assert int_var > 0
    except:
        print(f"sorry, please enter a positive number")
    print(f"what you enter is: {int_var}")

if __name__ == "__main__":
    testAssert()

torch.max(input, dim):

output = torch.max(input, dim)

输入

  • input是softmax函数输出的一个tensor
  • dim是max函数索引的维度0/10是每列的最大值,1是每行的最大值

输出

  • 函数会返回两个tensor,第一个tensor是每行的最大值,softmax的输出中最大的是1,所以第一个tensor是全1的tensor;第二个tensor是每行最大值的索引。

我们通过一个实例可以更容易理解这个函数的用法。

import torch
a = torch.tensor([[1,5,62,54], [2,6,2,6], [2,65,2,6]])
print(a)

tensor([[ 1,  5, 62, 54],
        [ 2,  6,  2,  6],
        [ 2, 65,  2,  6]])

索引每行的最大值:

torch.max(a, 1)

输出:

torch.return_types.max(
values=tensor([62,  6, 65]),
indices=tensor([2, 3, 1]))

torch.cat() 

torch.cat是将两个张量(tensor)拼接在一起,cat是concatnate的意思,即拼接,联系在一起。

  • 使用torch.cat((A,B),dim)时,除拼接维数dim数值可不同外其余维数数值需相同,方能对齐。
C = torch.cat( (A,B),0 )  #按维数0拼接(竖着拼)

C = torch.cat( (A,B),1 )  #按维数1拼接(横着拼)
>>> import torch
>>> A=torch.ones(2,3) #2x3的张量(矩阵)                                     
>>> A
tensor([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])
>>> B=2*torch.ones(4,3)#4x3的张量(矩阵)                                    
>>> B
tensor([[ 2.,  2.,  2.],
        [ 2.,  2.,  2.],
        [ 2.,  2.,  2.],
        [ 2.,  2.,  2.]])
>>> C=torch.cat((A,B),0)#按维数0(行)拼接
>>> C
tensor([[ 1.,  1.,  1.],
         [ 1.,  1.,  1.],
         [ 2.,  2.,  2.],
         [ 2.,  2.,  2.],
         [ 2.,  2.,  2.],
         [ 2.,  2.,  2.]])
>>> C.size()
torch.Size([6, 3])
>>> D=2*torch.ones(2,4) #2x4的张量(矩阵)
>>> C=torch.cat((A,D),1)#按维数1(列)拼接
>>> C
tensor([[ 1.,  1.,  1.,  2.,  2.,  2.,  2.],
        [ 1.,  1.,  1.,  2.,  2.,  2.,  2.]])
>>> C.size()
torch.Size([2, 7])

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值