tensor

[转载]PyTorch上的contiguous

点点圈 提交于 2019-12-06 12:00:16
[转载]PyTorch上的contiguous 来源: https://zhuanlan.zhihu.com/p/64551412 这篇文章写的非常好,我这里就不复制粘贴了,有兴趣的同学可以去看原文,我这里只摘录一些结论过来以便查询: PyTorch 提供了 is_contiguous 、 contiguous (形容词动用)两个方法 ,分别用于判定Tensor是否是 contiguous 的,以及保证Tensor是 contiguous 的。 is_contiguous 直观的解释是 Tensor底层一维数组元素的存储顺序与Tensor按行优先一维展开的元素顺序是否一致 。 为什么需要 contiguous ? torch.view 等方法操作需要连续的Tensor。 transpose、permute 操作虽然没有修改底层一维数组,但是新建了一份Tensor元信息,并在新的元信息中的 重新指定 stride。 torch.view 方法约定了不修改数组本身,只是使用新的形状查看数据。如果我们在 transpose、permute 操作后执行 view,Pytorch 会抛出错误. 原文中举了一个例子来说明:transpose、permute不修改底层数组,而view是直接访问底层数组的,所以在执行transpose、permute之后如果直接调用view

[转载]PyTorch中permute的用法

家住魔仙堡 提交于 2019-12-06 11:45:17
[转载]PyTorch中permute的用法 来源: https://blog.csdn.net/york1996/article/details/81876886 permute(dims) 将tensor的维度换位。 参数:参数是一系列的整数,代表原来张量的维度。比如三维就有0,1,2这些dimension。 例: import torch import numpy as np a=np.array([[[1,2,3],[4,5,6]]]) unpermuted=torch.tensor(a) print(unpermuted.size()) # ——> torch.Size([1, 2, 3]) permuted=unpermuted.permute(2,0,1) print(permuted.size()) # ——> torch.Size([3, 1, 2]) 再比如图片img的size比如是(28,28,3)就可以利用img.permute(2,0,1)得到一个size为(3,28,28)的tensor。 利用这个函数permute(0,2,1)可以把Tensor([[[1,2,3],[4,5,6]]]) 转换成 tensor([[[1., 4.], [2., 5.], [3., 6.]]]) 如果使用view,可以得到 tensor([[[1., 2.], [3.,

pytorch--基础类型之间的转换

不想你离开。 提交于 2019-12-06 10:54:48
在pytorch自己定义张量并进行计算的时候,往往会因为类型不匹配而报错,这里稍微记下pytorch之间的类型转换: 对tensor基础类型进行转换:比如说int()、float()、long()、double()、byte()等,直接 .类型 即可,例如 float()->int:data.int() GPU与CPU类型之间的转换: GPU->CPU:data.cpu() CPU->GPU:data.cuda() Variable与Tensor:貌似Variable已经被合并到Tensor中了; numpy与Tensor之间的转换: numpy->tensor:data.from_numpy tensor->numoy:data.numpy() 来源: https://www.cnblogs.com/xiximayou/p/11979401.html

Porting PyTorch code from CPU to GPU

此生再无相见时 提交于 2019-12-06 09:31:58
Following the tutorial from https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb There is a USE_CUDA flag that is used to control the variable and tensor types between CPU (when False) to GPU (when True) types. Using the data from en-fr.tsv and converting the sentences to variables: import unicodedata import string import re import random import time import math from gensim.corpora.dictionary import Dictionary import torch import torch.nn as nn from torch.autograd import Variable from torch import LongTensor, FloatTensor from torch import optim

动手学深度学习_2.2_autograd

a 夏天 提交于 2019-12-06 04:33:17
Tensor import torch x = torch.ones(2, 2, requires_grad=True) # 将其属性.requires_grad设置为True,它将开始追踪(track)在其上的所有操作。完成计算后,可以调用.backward()来完成所有梯度计算 print(x) print(x.grad_fn) # 每个Tensor都有一个.grad_fn属性,该属性即创建该Tensor的Function(除非用户创建的Tensors时设置了grad_fn=None)# tensor([[1., 1.], # [1., 1.]], requires_grad=True) # None y = x + 2 print(y) print(y.grad_fn) # tensor([[3., 3.], # [3., 3.]], grad_fn=<AddBackward0>) # <AddBackward0 object at 0x7fecef6f5320> attension: x是直接创建的,所以他没有grad_fn,而y通过一个加法操作创建的,所以它有一个的grad_fn # x这种直接创建的称为叶⼦节点,叶⼦节点对应的 grad_fn 是 None print(x.is_leaf, y.is_leaf) # True False z = y * y * 3

动手学深度学习_2.1_tensor

ε祈祈猫儿з 提交于 2019-12-06 04:31:18
数据操作 1 import torch 2 3 torch.manual_seed(0) 4 torch.cuda.manual_seed(0) 5 print(torch.__version__) # 1.3.1 创建tensor 1 # 创建一个5x3的未初始化的tensor 2 x = torch.empty(5, 3) 3 print(x) 4 5 # tensor([[1.3563e-19, 1.3563e-19, 7.9717e-10], 6 # [5.8270e-10, 5.8270e-10, 4.9153e-14], 7 # [1.3563e-19, 1.8578e-01, 3.9157e-02], 8 # [4.7429e+30, 2.2639e+35, 1.8971e+31], 9 # [1.4587e-19, 1.1703e-19, 1.5637e-01]]) # 随机初始化的tensor x = torch.rand(5, 3) print(x) # tensor([[0.4963, 0.7682, 0.0885], # [0.1320, 0.3074, 0.6341], # [0.4901, 0.8964, 0.4556], # [0.6323, 0.3489, 0.4017], # [0.0223, 0.1689, 0.2939]]) #

PyTorch的十七个损失函数

痞子三分冷 提交于 2019-12-05 21:56:18
本文截取自《PyTorch 模型训练实用教程》,获取全文pdf请点击: tensor-yu/PyTorch_Tutorial ​github.com 版权声明:本文为博主原创文章,转载请附上博文链接! 我们所说的优化,即优化网络权值使得损失函数值变小。但是,损失函数值变小是否能代表模型的分类/回归精度变高呢?那么多种损失函数,应该如何选择呢?请来了解PyTorch中给出的十七种损失函数吧。 1.L1loss 2.MSELoss 3.CrossEntropyLoss 4.NLLLoss 5.PoissonNLLLoss 6.KLDivLoss 7.BCELoss 8.BCEWithLogitsLoss 9.MarginRankingLoss 10.HingeEmbeddingLoss 11.MultiLabelMarginLoss 12.SmoothL1Loss 13.SoftMarginLoss 14.MultiLabelSoftMarginLoss 15.CosineEmbeddingLoss 16.MultiMarginLoss 17.TripletMarginLoss 请运行配套代码,代码中有详细解释,有手动计算,这些都有助于理解损失函数原理。 本小节配套代码: /Code/3_optimizer/3_1_lossFunction 1.L1loss class torch

pytorch中backward()函数详解

末鹿安然 提交于 2019-12-05 21:54:41
最近由于实际需要在学习pytorch,作为深度学习中最为重要的反向传播计算,pytorch用非常简单的backward( )函数就实现了,但是在实现过程中对于其参数存在一些疑问,下面就从pytorch中反向传播求导的计算方式,backward( )函数参数来进行说明。 这里首先还是放出backward( )函数的pytorch文档,因为整个说明主要还是围绕这个函数来进行的。 问题描述 从上面的文档可以看到backward函数有一个奇怪的参数:grad_tensors,在实现pytorch的官方教程中可以发现: import torch import torch . nn as nn x = torch . tensor ( [ 2 , 3 , 4 ] , dtype = torch . float , requires_grad = True ) print ( x ) y = x * 2 while y . norm ( ) < 1000 : y = y * 2 print ( y ) y . backward ( torch . ones_like ( y ) ) print ( x . grad ) 上面的程序的输出为: tensor ( [ 2 . , 3 . , 4 . ] , requires_grad = True ) tensor ( [ 512 . , 768 .

pytorch的梯度计算以及backward方法

蓝咒 提交于 2019-12-05 21:54:22
基础知识 tensors: tensor在pytorch里面是一个n维数组。我们可以通过指定参数reuqires_grad=True来建立一个反向传播图,从而能够计算梯度。在pytorch中一般叫做dynamic computation graph(DCG)——即动态计算图。 import torch import numpy as np # 方式一 x = torch.randn(2,2, requires_grad=True) # 方式二 x = torch.autograd.Variable(torch.Tensor([2,3]), requires_grad=True) #方式三 x = torch.tensor([2,3], requires_grad=True, dtype=torch.float64) # 方式四 x = np.array([1,2,3] ,dtype=np.float64) x = torch.from_numpy(x) x.requires_grad = True # 或者 x.requires_grad_(True) note1: 在pytorch中,只有浮点类型的数才有梯度,故在方法四中指定np数组的类型为float类型。为什么torch.Tensor中不需要呢,可以通过以下代码验证 import torch import numpy as

Pytorch:BertModel使用

情到浓时终转凉″ 提交于 2019-12-05 21:43:46
文章目录 基本介绍 简单例子: 参考 基本介绍 环境: Python 3.5+, Pytorch 0.4.1/1.0.0 安装: pip install pytorch-pretrained-bert 必需参数: --data_dir : "str" : 数据根目录.目录下放着, train.xxx/dev.xxx/test.xxx 三个数据文件. --vocab_dir : "str" : 词库文件地址. --bert_model : "str" : 存放着bert预训练好的模型. 需要是一个 gz 文件, 如 "..x/xx/bert-base-chinese.tar.gz " , 里面包含一个 bert_config.json 和 pytorch_model.bin 文件. --task_name : "str" : 用来选择对应数据集的参数,如 "cola" ,对应着数据集. --output_dir : "str" : 模型预测结果和模型参数存储目录. 简单例子: 导入所需包 import torch from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM 创建分词器 tokenizer = BertTokenizer.from_pretrained(--vocab_dir