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 awk命令详解

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年8月8日
    0292
  • Apache Bench压力测试使用方法

    Apache Bench是Apache轻量级压力测试工具,使用方便,简单,本文章简单介绍Windows平台使用Apache bench进行接口压力测试(ab测试) ApacheBe…

    Linux 2023年6月8日
    027
  • shell中参数的用法 && wait的用法

    转载自https://www.jianshu.com/p/4db526ff6560 参数 说明 $0 当前脚本的文件名(间接运行时还包括绝对路径) $n 传递给脚本或函数的参数。n…

    Linux 2023年5月28日
    021
  • 开放平台架构指南

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年10月15日
    0171
  • Linux安装Node.js

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年8月13日
    0179
  • realloc,c语言

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年8月24日
    0152
  • Linux下使用Vim粘贴文本后出现乱码解决

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    2022年8月9日
    1347
  • ubuntu中vi编辑器键盘错乱的问题

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    2022年8月11日
    0224
  • 【Example】C++ std::thread 及 std::mutex

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年11月5日
    0172
  • docker 安装redis

    安装docker https://www.cnblogs.com/ximensama/p/14903105.html 安装redis https://www.cnblogs.com…

    Linux 2023年5月28日
    018
  • 小公司比较吃亏的两道微服务面试题

    其实选择工作的时候,很多技术牛人都会选择一些小而美的公司,技术全面,能够以一个更全面的视角看整个公司的运作,人和人之间的相处也很简单。但是,有两道微服务的面试题,小公司的朋友们会比…

    Linux 2023年6月14日
    028
  • 内存分配-slab分配器

    1 slab综述 1.1 slab分配器产生的背景 类似 task_struct mm_struct 等结构被内核中被频繁分配和释放,同时创建和销毁这些结构会产生一定的开销(ove…

    Linux 2023年6月7日
    020
  • 笔记8:Linux知识

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年8月24日
    0226
  • 一篇长文说 git 基础

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

    Linux 2022年8月30日
    0283
  • 如何快速提高英飞凌单片机编译器 TASKING TriCore Eclipse IDE 编译速度

    1、前言 使用英飞凌单片机编译器 TASKING TriCore Eclipse IDE 开发编译时,想必感受最深刻的就是编译速度,那是非常慢了,如果是部分修改的源文件编译还好,不…

    Linux 2023年6月7日
    018
  • Linux磁盘空间查看、磁盘被未知资源耗尽

    注入产生的原理: 数据库设置为GBK编码: 宽字节注入源于程序员设置MySQL连接时错误配置为:set character_set_client=gbk,这样配置会引发编码转换从而…

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