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)

大家都在看

  • 什么是守护进程?

    在了解守护进程之前,需要先知道什么是什么是终端?什么是作业?什么是进程组?什么是会话? 在 Linux 中, 每一个系统与用户进行交流的界面称为终端,每一个从此终端开始运行的进程都…

    Linux 2023年6月8日
    0123
  • 辗转相除法:(求最大公约数)

    辗转相除法:(最大公约数)又名欧几里德算法(Euclidean algorithm),是求最大公约数的一种方法。它的具体做法是:用较大数除以较小数,再用出现的余数(第一余数)去除除…

    Linux 2023年6月7日
    0119
  • CSS解决父级边框坍塌的问题

    首先在父级标签内添加如下 标签 然后在CSS中对该标签进行如下修饰: #clear{ clear:both; margin:0px; padding: 0px; } 优点:简单。缺…

    Linux 2023年6月13日
    0102
  • Centos7 无法上网问题

    最近在VMware虚拟机里玩Centos,装好后发现上不了网。经过一番艰辛的折腾,终于找到出解决问题的方法了。最终的效果是无论是ping内网IP还是ping外网ip,都能正常pin…

    Linux 2023年6月13日
    075
  • 杨辉三角的变形—牛客网

    杨辉三角的变形_牛客题霸_牛客网 (nowcoder.com) #include using namespace std; int main() { //这个树的偶数规律为 -1 …

    Linux 2023年6月13日
    0129
  • null和空字符串对于查询where条件语句的影响

    在数据库中我们进行数据处理的过程中,对于null值或者空字符串的情况对于这种数据我们进行计算平均值以及查询过程中如何进行对于这类数据的处理呢? step1:建表:create ta…

    Linux 2023年6月14日
    0100
  • 附029.Kubernetes安全之网络策略

    [root@master01 cksstudy]# vi studyns01.yaml apiVersion: v1 kind: Namespace metadata: name:…

    Linux 2023年6月13日
    0126
  • 安装webgot漏洞实验平台时遇到的java环境配置问题

    6 .安装并注册 依次执行命令: 将已下载的Java版本登记为替代版本,将其改成作为默认版本来使用: update-alternatives –install /usr…

    Linux 2023年6月13日
    071
  • 【设计模式】Java设计模式-装饰者模式

    Java设计模式 – 装饰者模式 😄 不断学习才是王道🔥 继续踏上学习之路,学之分享笔记👊 总有一天我也能像各位大佬一样🏆原创作品,更多关注我CSDN: 一个有梦有戏的…

    Linux 2023年6月6日
    0161
  • 在.NET中体验GraphQL

    前言 以前需要提供Web服务接口的时候,除了标准的WEBAPI形式,还考虑了OData、GraphQL等形式,虽然实现思路上有很大的区别,但对使用方来说,都是将查询的主动权让渡给了…

    Linux 2023年6月6日
    0134
  • centos快速搭建nfs共享

    一、nfs服务器端 01.安装nfs服务 yum -y install nfs-utils 02.创建存储目录 mkdir -p /data/2haohr_backup 03.设置…

    Linux 2023年6月6日
    0113
  • Linux编译安装、压缩打包与定时任务服务

    一、编译安装 即使用源代码编译安装的方式,编译打包软件。特点: 可以自定制软件; 可以按需构建软件; 编译安装案例 1、下载源代码包(这里以Nginx软件包源代码为例) wget …

    Linux 2023年5月27日
    099
  • 散列数据结构以及在HashMap中的应用

    1. 为什么需要散列表? 对于线性表和链表而言,访问表中的元素,时间复杂度均为O(n)。即便是通过树结构存储数据,时间复杂度也为O(logn)。那么有没有一种方式可以将这个时间复杂…

    Linux 2023年6月7日
    0135
  • MySQL manager or server PID file could not be found!

    [root@centos var]# service mysqld stop MySQL manager or server PID file could not be found…

    Linux 2023年6月13日
    091
  • 正则表达式

    1.正则表达式分类 正则表达式:REGEXP,REGular EXPression。正则表达式分为两类: Basic REGEXP(基本正则表达式) Extended REGEXP…

    Linux 2023年6月6日
    0103
  • 最新超详细VMware下CentOS系统安装

    一、了解CentOS系统 CentOS是免费的、开源的、可以重新分发的开源操作系统,CentOS(Community Enterprise Operating System,中文意…

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