Tensor是一种特殊的数据结构,非常类似于数组和矩阵。在PyTorch中,我们使用tensor编码模型的输入和输出,以及模型的参数。

Tensor类似于Numpy的数组,除了tensor可以在GPUs或其它特殊的硬件上运行以加速运算。如果熟悉ndarray,那么你也会熟悉Tensor API。如果不是,跟随此快速API上手。

import torch
import numpy as np

Tensor 初始化

Tensor可以通过多种途径初始化。看看下面的例子:

直接从数据中初始化

Tensor可以直接从数据中初始化。数据类型是自动推断的。

data = [[1, 2], [3, 4]]
x_data = troch.tensor(data)

从数组中初始化

Tensor可以由NumPy数组创建(反之亦然 - 参见Bridge with NumPy)。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

从另一个tensor初始化:

除非明确覆盖,新的tensor保留参数tensor的属性(形状,数据类型)。

x_ones = torch.ones_like(x_data) # retatins the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

输出:

Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.3208, 0.9371],
[0.8172, 0.7103]])

使用随机值或常量值:

shape 是tensor维度的元祖。在以下函数中,它决定了输出tensor的维度。

shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape) print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor} \n")

输出:

Random Tensor:
tensor([[0.0546, 0.8256, 0.1878],
[0.6135, 0.0886, 0.0350]]) Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]]) Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])

Tensor 属性

Tensor属性描述了其形状、数据类型和存储的设备

tensor =  torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

输出:

Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

Tensor 操作

超过100种tensor操作,包括转置、索引、切片、数学运算、线性代数、随机采样,更多全面的描述见这里

以上每一种都可以在GPU上运行(通常比cpu速度更快)。如果你使用Colab,在Edit->Notebook Setting中配置GPU

# We move our tensor to the GPU if avaibale
if torch.cuda.is_available():
tensor = tensor.to('cuda')
print(f"Device tensor is stored on: {tensor.device}")

输出:

Device tensor is stored on: cuda:0

尝试列表中某些操作。如果你熟悉NumPy API,你会发现Tensor API使用起来轻而易举。

标准的类似于numpy的索引和切片:

tensor = torch.ones(4, 4)
tensor[:, 1] = 0
print(tensor)

输出:

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

拼接张量,你可以使用torch.cat沿着给定维度拼接一系列张量,另见torch.stack,另一个tensor的拼接操作,与torch.cat略有不同。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

输出:

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

dim=0,沿着第一维度拼接(增加第一维度数值),dim=1,沿着第二维度拼接(增加第二维度数值)

tensor乘法

# 计算元素乘积
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# 替代语法
print(f"tensor * tensor \n {tensor * tensor}")

输出:

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

计算两个tensor的矩阵乘法

print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# 替代语法:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")

输出:

tensor.matmul(tensor.T)
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]]) tensor @ tensor.T
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])

In-place operations:张量操作名带上“_”即是in-place。例如:x.copy_(y), x.t_(),将会改变x

print(tensor, "\n")
tensor.add_(5)
print(tensor)

输出:

tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]]) tensor([[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.]])

注意:In-place操作可以节省一些内存,但当计算导数时可能会出现问题,因为它会立即丢失历史记录。因此,不鼓励使用它们。

与NumPy的关联

CPU上的Tensor和NumPy数组可以共享它们的底层内存位置,改变其中一个,另一个也会随之改变

Tensor转换为NumPy数组

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

输出:

t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

在tensor上的改变将会反映在NumPy数组上

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

输出:

t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

Numpy数组转换为tensor

n = np.ones(5)
t = torch.from_numpy(n)

在NumPy上的改变将会反映在tensor上

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")

输出:

t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ | TENSORS的更多相关文章

  1. DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ | TORCH.AUTOGRAD

    torch.autograd 是PyTorch的自动微分引擎,用以推动神经网络训练.在本节,你将会对autograd如何帮助神经网络训练的概念有所理解. 背景 神经网络(NNs)是在输入数据上执行的嵌 ...

  2. DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ | NEURAL NETWORKS

    神经网络可以使用 torch.nn包构建. 现在你已经对autograd有所了解,nn依赖 autograd 定义模型并对其求微分.nn.Module 包括层,和一个返回 output 的方法 - f ...

  3. DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ | TRAINING A CLASSIFIER

    你已经知道怎样定义神经网络,计算损失和更新网络权重.现在你可能会想, 那么,数据呢? 通常,当你需要解决有关图像.文本或音频数据的问题,你可以使用python标准库加载数据并转换为numpy arra ...

  4. Deep learning with PyTorch: A 60 minute blitz _note(1) Tensors

    Tensors 1. construst matrix 2. addition 3. slice from __future__ import print_function import torch ...

  5. Summary on deep learning framework --- PyTorch

    Summary on deep learning framework --- PyTorch  Updated on 2018-07-22 21:25:42  import osos.environ[ ...

  6. Neural Network Programming - Deep Learning with PyTorch with deeplizard.

    PyTorch Prerequisites - Syllabus for Neural Network Programming Series PyTorch先决条件 - 神经网络编程系列教学大纲 每个 ...

  7. Neural Network Programming - Deep Learning with PyTorch - YouTube

    百度云链接: 链接:https://pan.baidu.com/s/1xU-CxXGCvV6o5Sksryj3fA 提取码:gawn

  8. (zhuan) Where can I start with Deep Learning?

    Where can I start with Deep Learning? By Rotek Song, Deep Reinforcement Learning/Robotics/Computer V ...

  9. rlpyt(Deep Reinforcement Learning in PyTorch)

    rlpyt: A Research Code Base for Deep Reinforcement Learning in PyTorch Github:https://github.com/ast ...

随机推荐

  1. 对ORM的理解

    1. 在面试中可能会问到这个问题,什么是ORM? ORM是对象关系映射(Object Relational Mapping),简称ORM,或O/RM,或O/R mapping,是一种程序技术. 白话理 ...

  2. CF1265B Beautiful Numbers 题解

    Content 给定一个 \(1\sim n\) 的排列,请求出对于 \(1\leqslant m\leqslant n\),是否存在一个区间满足这个区间是一个 \(1\sim m\) 的排列. 数据 ...

  3. JAVA使用百度链接实时推送API提交链接

    官网地址:http://data.zz.baidu.com/ 百度推广API的token获取 http://data.zz.baidu.com/site/index 填写完之后会进行验证, 验证完之后 ...

  4. Spring核心原理之 IoC容器中那些鲜为人知的细节(3)

    本文节选自<Spring 5核心原理> Spring IoC容器还有一些高级特性,如使用lazy-init属性对Bean预初始化.使用FactoryBean产生或者修饰Bean对象的生成. ...

  5. 分享一下java需要的一些技术

    1.前言 you are 大哥,老衲很佩服你们_.还是一样的,有我联系方式的人,哪些半吊子不知道要学习哪些技术,一天让我整知识点,老衲也有事情做的,哪有那么多时间来一直搞知识点啊,我的博客更新很慢的, ...

  6. nim_duilib(16)之xml学习实战(GTAV加载窗口实现)

    本文的目标 使用配置xml实现下面的结果 布局 整体采用水平布局,左边显示文字区域设置为垂直布局. lets go stage 1 创建一个空白窗体,并设置为半透明:同时,使得整个窗口可以移动,则 将 ...

  7. 【LeetCode】799. Champagne Tower 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 参考资料 日期 题目地址:https:// ...

  8. 【LeetCode】806. Number of Lines To Write String 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 使用ASIIC码求长度 使用字典保存长度 日期 题目 ...

  9. CS5213设计HDMI转VGA带音频信号输出|CS5213方案|CS5213设计电路

    CS5213是一款用于设计HDMI转VGA音视频信号转换器方案,CS5213设计HDMI转VGA转换器或者转接线产品特点: 将完整的HDMI信号转换为VGA输出支持数字信号到模似信号的转换支持 HDC ...

  10. CS5268替代AG9321MCQ 替代AG9321方案 TYPEC转HDMI多功能拓展坞

    台湾安格AG9321MCQ是一款TYPEC拓展坞产品方案,他集中了TYPEC 转HDMI  VGA  PD3.0快充  QC3.0数据传输 I2S接口的音频DAC输出以及可以各种读卡器功能. Caps ...