pytorch零星笔记

tensor

import torch
x=torch.empty(5,3)
x=torch.rand(5,3)
torch.randint(5, (3,), dtype=torch.int64)
x=torch.zeros(5,3)
x=torch.ones(5,3,dtype=torch.long)

layer torch.nn.

layer要先实例化,再调用。
Linear线性层:
实例化2:class torch.nn.Linear(in_features, out_features, bias=True)
调用:输入1个向量,维数:N***in_features
输出1个向量,维数:N***out_features
注意:只要输入输出的最后一维和初始化线性层类相同就行,前面有多少维都没关系,所以用N***。

Softmax激活函数层
实例化0:class torch.nn.Softmax(dim=None)
输入向量1:任意维度
输出向量1:维度与输入相同
默认会把最后一位进行softmax操作

function torch.nn.functional.

函数要直接调用
import torch.nn.functional as F

F.softmax(input, dim=None, _stacklevel=3)
F.log_softmax(input, dim=None, _stacklevel=3)
NLLLoss The negative log likelihood loss. -sigma_i(golden_i*log(prediction_i)

torch.nn.functional.nll_loss(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction=‘elementwise_mean’)

torch.nn.functional.cross_entropy(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction=‘elementwise_mean’)
This criterion combines log_softmax and nll_loss in a single function.

对于单分类问题
input维度:(N,C) (N,C,d1,d2…dk) 接收的是log_softmax值
target维度:(N)(N,d1,d2,…dk)


>>> # input is of size N x C = 3 x 5
>>> input = torch.randn(3, 5, requires_grad=True)
>>> # each element in target has to have 0 <= value < C
>>> target = torch.tensor([1, 0, 4])
>>> output = F.nll_loss(F.log_softmax(input), target)
>>> output.backward()

>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randint(5, (3,), dtype=torch.int64)
>>> loss = F.cross_entropy(input, target)
>>> loss.backward()

stacked layers

import copy
def clones(module, N):
    "Produce N identical layers."
    return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])

要写的东西
nn.Dropout
nn.Embeddings
nn.Sequencial()
torch.arange()

>>> torch.arange(5)
tensor([ 0,  1,  2,  3,  4])
>>> torch.arange(1, 4)
tensor([ 1,  2,  3])
>>> torch.arange(1, 2.5, 0.5)
tensor([ 1.0000,  1.5000,  2.0000])

masked_fill

a.size(-1) The returned value is a subclass of tuple.(tuple是不可变的list)
torch.transpose(input, dim0, dim1) → Tensor 或者 input.transpose(-2,-1)也可以,两维交换维数

a.view(-1,2)改变形状,-1是根据其他维数算出来的
a.unsqueeze(1)增加再第x个维前面加上一维 23变成213 a.unsqueeze(-1) 变成231 【索引方向不同 加的那一列的位置不同】
a.squeeze(1)减少1的个数 2
131变成231
contiguous()

contiguous:view只能用在contiguous的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。
一种可能的解释是:
有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式。
判断是否contiguous用torch.Tensor.is_contiguous()函数。

import torch
x = torch.ones(10, 10)
x.is_contiguous()  # True
x.transpose(0, 1).is_contiguous()  # False
x.transpose(0, 1).contiguous().is_contiguous()  # True

在pytorch的最新版本0.4版本中,增加了torch.reshape(), 这与 numpy.reshape 的功能类似。它大致相当于 tensor.contiguous().view()

python 的zip会参照短板效应

self.linears = clones(nn.Linear(d_model, d_model), 4)
query, key, value = [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2) for l, x in zip(self.linears, (query, key, value))]

以上虽然是4个linear的list但是只用了前三个,linear0(query),linear1(key),linear(value)
zip函数就值参照最外层(第一层)的维数235维 实际上只看成了2个3*5维进行zip
注意如果
在conda虚拟环境中,用pip install --user http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl numpy matplotlib spacy torchtext seaborn
安装以上包,会在所有conda虚拟环境中都安装上,包括base环境。心痛啊 我的base环境最新版的torch。如果只想再当下虚拟环境中安装,可以用 ~/miniconda/env/env1/bin/python -m --user pip install blabla命令。毕竟有时候conda安装网速太慢了 下载不下来,不过还是建议conda install和pip install不要混用。

numpy np.triu()提取矩阵上三角

@staticmethod

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值