首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【深度学习】翻译:60分钟入门PyTorch(一)——Tensors

【深度学习】翻译:60分钟入门PyTorch(一)——Tensors

作者头像
黄博的机器学习圈子
发布2021-02-12 11:12:42
发布2021-02-12 11:12:42
9210
举报

前言

原文翻译自:Deep Learning with PyTorch: A 60 Minute Blitz

翻译:林不清(https://www.zhihu.com/people/lu-guo-92-42-88)

目录

60分钟入门PyTorch(一)——Tensors

60分钟入门PyTorch(二)——Autograd自动求导

60分钟入门Pytorch(三)——神经网络

60分钟入门PyTorch(四)——训练一个分类器

Tensors

Tensors张量是一种特殊的数据结构,它和数组还有矩阵十分相似。在Pytorch中,我们使用tensors来给模型的输入输出以及参数进行编码。Tensors除了张量可以在gpu或其他专用硬件上运行来加速计算之外,其他用法类似于Numpy中的ndarrays。如果你熟悉ndarrays,您就会熟悉tensor的API。如果没有,请按照这个教程,快速了解一遍API。

代码语言:javascript
复制
%matplotlib inline
import torch
import numpy as np

初始化Tensor

创建Tensor有多种方法,如:

直接从数据创建

可以直接利用数据创建tensor,数据类型会被自动推断出

代码语言:javascript
复制
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
从Numpy创建

Tensor 可以直接从numpy的array创建(反之亦然-参见bridge-to-np-label

代码语言:javascript
复制
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
从其他tensor创建

新的tensor保留了参数tensor的一些属性(形状,数据类型),除非显式覆盖

代码语言:javascript
复制
x_ones = torch.ones_like(x_data) # retains 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")
代码语言:javascript
复制
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.6075, 0.4581],
        [0.5631, 0.1357]])
从常数或者随机数创建

shape是关于tensor维度的一个元组,在下面的函数中,它决定了输出tensor的维数。

代码语言:javascript
复制
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}")
代码语言:javascript
复制
Random Tensor: 
 tensor([[0.7488, 0.0891, 0.8417],
        [0.0783, 0.5984, 0.5709]]) 

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

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

Tensor的属性

Tensor的属性包括形状,数据类型以及存储的设备

代码语言:javascript
复制
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}")
代码语言:javascript
复制
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

Tensor的操作

Tensor有超过100个操作,包括 transposing, indexing, slicing, mathematical operations, linear algebra, random sampling,更多详细的介绍请点击这里

它们都可以在GPU上运行(速度通常比CPU快),如果你使用的是Colab,通过编辑>笔记本设置来分配一个GPU。

代码语言:javascript
复制
# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

尝试列表中的一些操作。如果你熟悉NumPy API,你会发现tensor的API很容易使用。

标准的numpy类索引和切片:
代码语言:javascript
复制
tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)
代码语言:javascript
复制
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
合并tensors

可以使用torch.cat来沿着特定维数连接一系列张量。torch.stack另一个加入op的张量与torch.cat有细微的不同

代码语言:javascript
复制
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
代码语言:javascript
复制
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.]])
增加tensors
代码语言:javascript
复制
# This computes the element-wise product
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# Alternative syntax:
print(f"tensor * tensor \n {tensor * tensor}")
代码语言:javascript
复制
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之间的矩阵乘法

代码语言:javascript
复制
print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")
代码语言:javascript
复制
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.]])
原地操作

带有后缀_的操作表示的是原地操作,例如:x.copy_(y), x.t_()将改变 x.

代码语言:javascript
复制
print(tensor, "\n")
tensor.add_(5)
print(tensor)
代码语言:javascript
复制
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.]])
注意

原地操作虽然会节省许多空间,但是由于会立刻清除历史记录所以在计算导数时可能会有问题,因此不建议使用

Tensor转换为Numpt 数组

代码语言:javascript
复制
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
代码语言:javascript
复制
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

tensor的变化反映在NumPy数组中。

代码语言:javascript
复制
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
代码语言:javascript
复制
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

Numpy数组转换为Tensor

代码语言:javascript
复制
n = np.ones(5)
t = torch.from_numpy(n)

NumPy数组的变化反映在tensor中

代码语言:javascript
复制
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
代码语言:javascript
复制
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
代码语言:javascript
复制
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-01-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器学习初学者 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 目录
  • Tensors
    • 初始化Tensor
      • 直接从数据创建
      • 从Numpy创建
      • 从其他tensor创建
      • 从常数或者随机数创建
    • Tensor的属性
    • Tensor的操作
      • 标准的numpy类索引和切片:
      • 合并tensors
      • 增加tensors
      • 原地操作
      • 注意
    • Tensor转换为Numpt 数组
    • Numpy数组转换为Tensor
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档