PYTORCH: 60分钟 | TENSORS

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 = torch.tensor(data)
np_array = np.array(data)
x_np = torch.from_numpy(np_array)

除非明确覆盖,新的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使用起来轻而易举。

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.]])
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,沿着第二维度拼接(增加第二维度数值)

计算元素乘积
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数组可以共享它们的底层内存位置,改变其中一个,另一个也会随之改变

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.]
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.]

Original: https://www.cnblogs.com/DeepRS/p/15714994.html
Author: Deep_RS
Title: PYTORCH: 60分钟 | TENSORS

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/621344/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Java基础系列–01_基础类型

    J2SE、J2ME、J2EE分别指什么?J2SE 基础版,桌面应用。J2ME 微型版,手机开发。(android,ios)J2EE 企业版,所有浏览器访问的应用程序。注意:JDK5…

    Linux 2023年6月7日
    087
  • JCL 日志门面

    JCL( Jakarta Commons Logging ),是 Apache 提供的一个 通用日志 API 。用户可以自由选择第三方的日志组件作为具体实现,像 Log4j 或 J…

    Linux 2023年6月8日
    075
  • MSSQL·FOR XML PATH语法转义尖括号解决方案

    阅文时长 | 0.14分钟字数统计 | 225.6字符主要内容 | 1、引言&背景 2、示例及解决方案 3、声明与参考资料『MSSQL·FOR XML PATH语法转义尖括…

    Linux 2023年6月14日
    080
  • docker安装redis

    安装镜像 docker pull redis:7.0 下载配置文件 wget http://download.redis.io/redis-stable/redis.conf 修改…

    Linux 2023年6月7日
    0118
  • C语言基本语法

    C语言以分号代表一条语句结束,一条命令可以在多行显示 对于空格没有多大要求,只是为了代码美观,方便看懂,但python语法就比较严格必须要加空格 注释VS快捷键Ctrl+K,然后C…

    Linux 2023年6月8日
    086
  • Linux 0.11源码阅读笔记-高速缓冲

    高速缓冲 概念 高速缓冲区是内存中的一块内存,它充当块设备和内核中其他程序之间的桥梁。如果内核程序需要访问块设备中的数据,则需要通过高速缓冲区进行间接操作。 [En] The hi…

    Linux 2023年5月27日
    065
  • ASP.NET Core 2.2 : 二十三. 深入聊一聊配置的内部处理机制

    上一章介绍了配置的多种数据源被注册、加载和获取的过程,本节看一下这个过程系统是如何实现的。(ASP.NET Core 系列目录) 一、数据源的注册 在上一节介绍的数据源设置中,ap…

    Linux 2023年6月7日
    0124
  • cron 表达式

    cron 表达式 1.简介:一个cron表达式最少有5个空格来分割时间元素,总共有7个元素,分别如下: ① 秒(0-59) ② 分钟(0-59) ③ 小时(0-23) ④ 天(月的…

    Linux 2023年6月7日
    066
  • shell编程-杨辉三角简单实现

    shell编程-杨辉三角问题: 概述:中国古代数学家在数学的许多重要领域中处于遥遥领先的地位。中国古代数学史曾经有自己光辉灿烂的篇章,而杨辉三角的发现就是十分精彩的一页。杨辉三角形…

    Linux 2023年6月7日
    097
  • 青春浙江微信平台如何退出?如何重新登录?微信如何清除浏览器缓存,如何清除浏览器cookies?

    青春浙江不能退出重新登录,有同学可能寻找解决方法,给大家贴出来:bug 解决办法:1. debugmm.qq.com/?forcex5=true 打开调试2. http://deb…

    Linux 2023年5月27日
    086
  • 罗德岛

    自从转行以后就建博了,一直没有动手写内容,今天开始写。 主要记录技术上的积累和项目上的工作感悟。 这里就是罗德岛,就在这里跳。 Original: https://www.cnbl…

    Linux 2023年6月6日
    080
  • Docker容器搭建android编译环境

    Docker容器搭建android编译环境 .版本:v0.4作者:河东西望日期:2022-7-12. 1.1 手动部署 安装&#…

    Linux 2023年6月7日
    091
  • redis重点是 dir 的默认配置一定要改

    find / -name dump.rdb 发现有两个dump文件,这两个文件目录不一致,问题在于 redis.conf 文件属性dir,默认配置是dir ./ 表示在哪启动ser…

    Linux 2023年5月28日
    077
  • 设计模式——行为型设计模式

    行为型设计模式 针对对象之间的交互 解释器模式 java中用的很。JVM编译的时候就是对我们写的代码进行了解释操作;数据库SQL语句亦是如此 解释器:对语言进行解释,根据不同语义来…

    Linux 2023年6月7日
    0103
  • js学习笔记——条件 循环

    今天发现之前学的爱前端的课中JS部分函数等不全,果断换了一个课——渡一的《Web前端开发JavaScript高薪课堂》接着学习,不过废话有点多 语法:1、单if,条件成立,执行语句…

    Linux 2023年6月13日
    064
  • ASP.NET Core 3.0 : 二十八. 在Docker中的部署以及docker-compose的使用

    本文简要说一下ASP.NET Core 在Docker中部署以及docker-compose的使用 (ASP.NET Core 系列目录)。 系统环境为CentOS 8 。 一、概…

    Linux 2023年6月7日
    0102
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球