pytorch知识点

在 Pytorch 中,Tensor 和 tensor 都用于生成新的张量,但二者并不相同。

a = torch.Tensor([1, 2])
a  # tensor([1., 2.])
a=torch.tensor([1,2])
a  # tensor([1, 2])

torch.Tensor

torch.Tensor()是默认张量类型torch.FloatTensor()的别名,生成单精度浮点类型的张量。

a=torch.Tensor([1,2])
a.type()  # 'torch.FloatTensor'

torch.tensor()

torch.tensor()的函数原型为

torch.tensor(data, dtype=None, device=None, requires_grad=False)
  • data 类型可为:list, tuple, array, scalar 等;
  • torch.tensor()可根据原始数据类型生成相应类型的 tensor;
a = torch.tensor([1, 2])
a.type()  # 'torch.LongTensor'
a = torch.tensor([1., 2.])
a.type() # 'torch.FloatTensor'
a = np.zeros(2, dtype=np.float64)
a = torch.tensor(a)
a.type()  # torch.DoubleTensor

transforms.ToTensor()

import torchvision.transforms as transforms
y = transforms.ToTensor()
x = np.random.randint(0,10,[2,3,5])
y(x)  # 将x转为tensor,并将维度转换为(5,2,3)

numpy转为tensor的几种方式:

x = np.random.randint(0,10,[2,3,5])
# 方式1
x = torch.from_numpy(x).float()  # 要转为float类型才能在神经网络中使用
# 方式2
x = torch.tensor(x,dtype=torch.float)  # 要进行类型转换才能在神经网络中使用

输出张量的类型:

x.type()  # 默认x为张量
x.dtype()

torch.nn.LSTM()

#函数原型
class RNNBase(Module):
    ...
    def __init__(self, mode, input_size, hidden_size,
                 num_layers=1, bias=True, batch_first=False,
                 dropout=0., bidirectional=False):

输入的参数列表包括:
        input_size: 输入数据的特征维数,通常就是embedding_dim(词向量的维度)
        hidden_size: LSTM中隐层的维度
        num_layers: 循环神经网络的层数
        bias: 用不用偏置,default=True
        batch_first: 这个要注意,通常我们输入的数据shape=(batch_size,seq_length,embedding_dim),而batch_first默认是False,所以我们的输入数据最好送进LSTM之前将batch_size与seq_length这两个维度调换
        dropout: 默认是0,代表不用dropout
        bidirectional: 默认是false,代表不用双向LSTM
输入数据包括input, (h_0, c_0):
        input: shape = [seq_length, batch_size, input_size]的张量
        h_0: shape = [num_layers * num_directions, batch, hidden_size]的张量,它包含了在当前这个batch_size中每个句子的初始隐藏状态,num_layers就是LSTM的层数,如果bidirectional = True,则num_directions = 2,否则就是1,表示只有一个方向
        c_0: 与h_0的形状相同,它包含的是在当前这个batch_size中的每个句子的初始细胞状态。h_0,c_0如果不提供,那么默认是0
输出数据包括output, (h_t, c_t):
        output.shape = [seq_length, batch_size, num_directions * hidden_size]它包含的LSTM的最后一层的输出特征(h_t),t是batch_size中每个句子的长度.
        h_t.shape = [num_directions * num_layers, batch, hidden_size]
        c_t.shape = h_t.shape

维度转换 

原文链接:https://blog.csdn.net/qq_43894221/article/details/125747577
改变维度view
view 可以改变维度,合并拆分都可

#创建tensor变量
a=torch.rand(4,1,28,28)#4张图,1灰度图片,图片大小28*28
a.shape
#torch.Size([4, 1, 28, 28])

#将后面三个维度合并在一起,1*28*28
a.view(4,28*28).shape
#torch.Size([4, 784])

#前3个维度合并在一起
a.view(4*1*28,28).shape
#out:torch.Size([112, 28])

b=a.view(4,784)
b.view(4,28,28,1).shape#1维转4维,但此转变没有物理意义
#out:torch.Size([4, 28, 28, 1])

squeeze/unsqueeze
增加维度unsqueeze

#创建tensor变量
a=torch.rand(4,1,28,28)#4张图,1灰度图片,图片大小28*28

#在0的位置插入一个维度
a.unsqueeze(0).shape#0之前插入
#out:torch.Size([1, 4, 1, 28, 28])

a.unsqueeze(-1).shape#-1之后插入
#out:torch.Size([4, 1, 28, 28, 1])

删减维度squeeze

b=torch.rand(1,32,1,1)#32个channel,每个Chanel上有一个点

b.squeeze().shape#挤压维度维1的
#out:torch.Size([32])

b.squeeze(0).shape#删减第一位
#out:torch.Size([32, 1, 1])

b.squeeze(-1).shape#删减倒数第一位
#out:torch.Size([1, 32, 1])

expand/repeat
expand()函数可以将张量广播到新的形状,但是切记以下两点:

1、只能对维度值为1的维度进行扩展,且扩展的Tensor不会分配新的内存,只是原来的基础上创建新的视图并返回;
2、无需扩展的维度请保持维度值不变。

a=torch.rand(1,32,14,14)
a.expand(4,32,14,14).shape#expand维度与之前一致,
#out:torch.Size([4, 32, 14, 14])

a.expand(4,32,-1,-1).shape#-1代表保持原来的维度不变
#out:torch.Size([4, 32, 14, 14])

repeat(),这个函数如函数名一样,是复制函数,参数表示把这个tensor复制成多少个,参数以1,2,3位来解释:

b=torch.rand(1,32,1,1)
a.repeat(4,1,1,1).shape#数字代表重复的字数
b.repeat(4,1,32,32).shape#重复4次,保持不变,重复32,。。32

转置操作

a=torch.randn(3,4)
a.t().shape

transpose维度交换
torch.transpose(Tensor, a,b):transpose只能操作2D矩阵的转置

a=torch.rand([4,3,32,32])

#transpose(1,3),代表交换的维度,1和3维度。
a1=a.transpose(1,3).view(4,3*32*32).view(4,3,32,32)
#[abcd]变成[adcb]在变成[abdc]
#注意数据不可用view随意变换

a2=a.transpose(1,3).contiguous().view(4,3*32*32).view(4,32,32,3).transpose(1,3)
#[abcd]-[adcb]-[abcd]

#比较a和a1,会发现
torch.all(torch.eq(a,a1))
#False

torch.all(torch.eq(a,a2))
#True

permute
Tensor.permute(a,b,c,d, …):permute函数可以对任意高维矩阵进行转置,但没有 torch.permute() 这个调用方式, 只能 Tensor.permute():

a=torch.rand(4,3,28,28)
a.transpose(1,3).shape

b=torch.rand(4,3,28,32)
b.transpose(1,3).shape

#所有维度可以随意变换
b.permute(0,2,3,1).shape
#torch.Size([4, 28, 32, 3])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值