PyTorch 介绍 | TENSORS

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

Tensor类似于Numpy的ndarrays,除了tensor能在GPUs或其它硬件加速器上运行。事实上,tensor和NumPy数组可以共享相同的底层内存,而不需要拷贝数据(see Bridge with NumPy)。Tensor还被优化用于自动微分(Autograd)。如果你熟悉ndarray,那么你也将对Tensor API也很熟悉,如果不是,跟着学吧!

import torch
import numpy as np

初始化Tensor

Tensor初始化有多种方式。查看下面的例子。

直接从数据初始化

Tensor可以直接利用data创建。数据类型是自动判断的。

data = [[1, 2], [3, 4]]
x_data = torch.tesnor(data)

从Numpy array初始化

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

从另一个tensor初始化

新的tensor保留参数tensor的属性(shape, datatype),除非明确重写。

x_ones = torch.ones_like(x_data) # 保留x_data的属性
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写x_data的数据类型
print(f"Random Tensor: \n {x_rand} \n")

输出:

Ones Tensor:
 tensor([[1, 1],
        [1, 1]])

Random Tensor:
 tensor([[0.4557, 0.7406],
        [0.5935, 0.1859]])

使用随机值或常数初始化

shape 是表示tensor维度的元组。在下面的函数中,它决定了输出tensor的维度

shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeroat32s(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

输出:

Random Tensor:
 tensor([[0.8012, 0.4547, 0.4156],
        [0.6645, 0.1763, 0.3860]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

Tensor的属性

Tensor的属性描述了它们的shape,datatype,以及保存的硬件

tensor = torch.rand(3, 4)

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

输出:

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

Tensor的操作

每一种操作都可以在GPU(通常速度快于CPU)运行。

默认情况下,tensor是在CPU上创建的。我们需要使用 .to 方法明确地将tensor移动到GPU(在检查GPU可用后)。注意,跨设备复制大型的tensor需要花费大量的时间和内存。

We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to('cuda')

尝试list的一些操作。如果你熟悉NumPy API,你会发现Tensor API使用也会很容易。

标准的类似于numpy的indexing和slicing

tensor = torch.ones(4, 4)
print('First row: ', tensor[0])
print('First column: ', tensor[:, 0])
print('Last column: ', tenosr[..., -1])
tensor[:, 1] = 0
print(tensor)

输出:

First row:  tensor([1., 1., 1., 1.])
First column:  tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor拼接

你可以使用 torch.cat 沿着给定维度拼接一系列的tensor。还有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.]])

数学运算

计算tensor的矩阵乘法. y1,y2,y3是相同的
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)

逐像素相乘. z1,z2,z3是相同的
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

单元素tensor

如果是单元素tensor,例如把一个tensor的所有值聚合一个,你可以使用 item() 将其转换成Python数值

12.0 <class 'float'>
</class>

In-place operations

In-place operations 会将结果保存到in-place操作数中。它们用下缀 _ 表示,例如: x.copy()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操作节约内存,但是在计算导数时可能会出问题,因为会立即丢失历史值。因此,不推荐使用。

Bridge with NumPy

CPU上的Tensor和NumPy数组共享底层内存位置,改变其中一个将改变另一个。

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"t: {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_numy(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/15735983.html
Author: Deep_RS
Title: PyTorch 介绍 | TENSORS

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

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

(0)

大家都在看

  • 【电子取证:镜像仿真篇】Windows Server镜像仿真、vmdk镜像仿真

    Windows Server镜像仿真、vmdk镜像仿真 时间过得真快呀!–【suy999】 一、qemu-img镜像转换工具 qemu-img(v2.3.0.0)镜像转…

    Linux 2023年6月13日
    0103
  • 怎么用vscode创建工程

    以下内容为本人的学习笔记,如需要转载,请声明原文链接微信公众号「englyf」 https://mp.weixin.qq.com/s/x2OXMTaLlxb_Os7NDHrKsg …

    Linux 2023年6月6日
    0110
  • Xshell的快捷键【转】

    删除ctrl + d 删除光标所在位置上的字符相当于VIM里x或者dlctrl + h 删除光标所在位置前的字符相当于VIM里hx或者dhctrl + k 删除光标后面所有字符相当…

    Linux 2023年5月28日
    093
  • Mysql实战技能全解

    一、数据库原理 1 数据的分类 结构化的数据:即有固定格式和有限长度的数据。例如填的表格就是结构化的数据,国籍:中华人民共和国,民族:汉,性别:男,这都叫结构化数据 非结构化的数据…

    Linux 2023年6月7日
    0146
  • Ubuntu系统报错The system is running in low-graphics mode

    我遇到过两次这种请况,这次解决了。很nice! 在csdn上搜到的大部分操作是: 鼠标进入系统 使用快捷键 Ctrl+Alt+F1 进入用户 输入密码 然后按照以下代码进行 cd …

    Linux 2023年5月27日
    0102
  • Typora Ubuntu 安装

    官网方法 终端命令行安装 or use sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys BA300B77…

    Linux 2023年6月7日
    098
  • GCC 内联汇编基础

    GCC 内联汇编 在 MIT6.828的实验中,有几处用到了很底层的函数,都以内联汇编的形式存在,例如 static inline uint32_t read_esp(void) …

    Linux 2023年6月8日
    087
  • MySQL半同步复制的实现和复制过滤器

    当客户端发送给服务端请求时,在等待服务端响应的时候,客户端可以做其他的事情,这样节约了时间,提高了效率。 当客户端发送请求给服务端,在等待服务端响应的请求时,客户端不做其他的事情。…

    Linux 2023年6月7日
    0102
  • 软件定义网络第一次作业

    配置结果 如何pip解决下载过慢问题 实验环境配置 环境安装截图如下 安装环境过程中一些问题的解决 github连接不上 在hosts文件中加上以下语句 140.82.114.3 …

    Linux 2023年6月7日
    0108
  • 阿里云函数-爱奇艺签到

    简介 是否支持多账号:是消息推送平台:PUSHPLUS 代码 -*- coding: utf8 -*- import requests,random,string,hashlib,…

    Linux 2023年6月7日
    086
  • Python 多线程

    import threading import time def userTest(aa,bb): print(aa) time.sleep(3) print(bb) if __n…

    Linux 2023年6月6日
    080
  • termius好用的shell终端

    ipad下可用 posted @2022-07-23 12:41 jiftle 阅读(75 ) 评论() 编辑 Original: https://www.cnblogs.com/…

    Linux 2023年5月28日
    0114
  • 计算机网络学习任务

    自学分析题 请分析,一个5KHz的无噪声信道能够达到的最大数据传输率是多少? 为什么? 假设你使用的宽带是100Mbps,你要把一个0.5GB的文件发送出去, 理论上要花多长时间?…

    Linux 2023年6月6日
    0139
  • 在RestController中获取各种信息的方法

    内容 获取方法 URL中路径的一部分 首先需要在RequestMapping做映射, 之后在方法中可以通过注解使用映射的变量@GetMapping(“/{id}&#82…

    Linux 2023年6月14日
    0123
  • Oracle 恢复delete误删数据

    — 开启行移动功能 alter table 表名 enable row movement; — 查询删除前的数据 select * from 表名 as of timestam…

    Linux 2023年6月8日
    090
  • QLabel图片自适应

    故事背景:由于要做终端定制的需求,在服务端上传一张128像素的图片,下发给客户端,适配所有图标(界面左上角、任务栏、快捷方式、托盘等),但是由于每个位置的图标大小不一样,代码要根据…

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