深度学习PyTorch入门基础,让你在60分钟内了解PYTORCH

Pytorch一小时入门教程

前言

虽然之前已经学习了很多有关机器学习的知识,但都是理论了解,真正遇到项目才发现自己实操验证不足,故而选择从基础学习,正好自己做一下笔记。

Pytorch是什么

它是一个基于python的科学计算库,致力于为两类用户提供服务:

  • 作为NumPy的替代品,并使用强大的GPU来进行运算
  • 一个可以提供最大灵活性和速度的深度学习研究平台

话不多说 冲!

1.张量的概念

张量很像Numpy中的ndarrays,并以此为基础使得他可以运行在GPU上来加速计算。

#导入包
from __future__ import print_function
import torch

#创建一个5x3的张量
x = torch.empty(5, 3)
print(x)
'''打印结果
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
'''

#创建一个均匀分布的初始化的,每个元素从0~1的张量,与第一个要区别开
#另外,还有其它的随机张量生成函数
#如torch.randn()、torch.normal()、torch.linespace()
#分别是标准正态分布,离散正态分布,线性间距向量
x = torch.rand(5, 3)
print(x)
'''打印结果
tensor([[0.0453, 0.6403, 0.7086],
        [0.3725, 0.9536, 0.4979],
        [0.8880, 0.4022, 0.0191],
        [0.0108, 0.3556, 0.3921],
        [0.7216, 0.6428, 0.1180]])
'''

# 这个是初始化一个全零张量,可以指定每个元素的类型。
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
"""打印结果
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
"""

#从已有矩阵转化为张量
x = torch.tensor([5.5, 3])
print(x)
"""
tensor([5.5000, 3.0000])
"""
#从已有张量在创建一个张量,新的张量会重用已有张量的数值
#如:若不提供新的值,那么每个值的类型将会被重用。

x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print(x)
x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x)                                      # result has the same size
'''
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[-1.9149, -2.1123, -0.0094],
        [-0.0293, -0.7709,  0.2928],
        [-0.5862, -0.4560,  0.3048],
        [-1.1351, -0.3346, -1.6508],
        [-0.2904, -0.2541,  0.6300]])
'''
# 最后我们学习如何获取张量的形状,一个小Tip,torch.Size是一个元组,所以支持元组的操作。
print(x.size())
"""
torch.Size([5, 3])
"""

2.张量的运算

张量的运算方法有很多,这里以加法为例子讲解,查看更多(100+种Tensor 运算,包括转置、索引、切片、数学运算、线性代数、随机数)。

#设定初始值
x = torch.rand(5, 3)
y = torch.rand(5, 3)
#加法方式1
print(x + y)
'''
tensor([[0.8933, 0.3901, 1.4612],
        [1.0388, 1.5159, 0.8598],
        [0.6628, 0.7821, 1.4633],
        [1.0268, 1.5891, 0.7690],
        [0.9112, 0.2712, 0.3129]])
'''

#加法方式2
print(torch.add(x, y))
'''
tensor([[0.8933, 0.3901, 1.4612],
        [1.0388, 1.5159, 0.8598],
        [0.6628, 0.7821, 1.4633],
        [1.0268, 1.5891, 0.7690],
        [0.9112, 0.2712, 0.3129]])
'''
#加法方式3 可以添加参数
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
'''
tensor([[0.8933, 0.3901, 1.4612],
        [1.0388, 1.5159, 0.8598],
        [0.6628, 0.7821, 1.4633],
        [1.0268, 1.5891, 0.7690],
        [0.9112, 0.2712, 0.3129]])
'''
#加法方式4 这是方法二的一种变式,注意有一个“_”,
#这个符号在所有替换自身操作符的末尾都有,另外,输出的方式还可以象python一样。
y.add_(x)
print(y)
"""
tensor([[ 1.2461,  0.6067, -0.9796],
        [ 0.0663, -0.9046,  0.8010],
        [ 0.4199,  1.8893,  0.7887],
        [ 0.6264, -0.2058,  1.8550],
        [ 0.0445, -0.8441,  2.2513]])
"""
#注意:任何改变自身张量的操作后面都有一个后缀“_”,比如x.copy_(y),x.t_()都将改变张量x

#你也可以使用任何Numpy的操作来操作张量
print(x[:, 1])
'''
tensor([-0.2405, -0.9072,  1.8072, -0.6766, -1.1166])
'''

张量加法运算先到这里,接下来我们看一先如何跳转张量形状及查看张量大小

#如果你想调整张量的维数 你可以使用torch.view()
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
'''
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
'''
#查看张量大小
x = torch.randn(1)
print(x)
print(x.item())
'''
tensor([0.4379])
0.4378727972507477
'''

3.张量和Numpy的转换

Tensor 和 NumPy 将共享其基础内存位置(如果 Tensor 位于 CPU 上),更改一个将更改另一个内存位置。

#tensor转换到Numpy
a = torch.ones(5)
print(a)
"""
tensor([1., 1., 1., 1., 1.])
"""
b = a.numpy()
print(b)
"""
[1. 1. 1. 1. 1.]
"""
#如果要改变值
a.add_(1)
print(a)
print(b)
"""
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
"""

#Numpy转换到tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
'''
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
'''
#注意 CPU 上的所有 Tensors,除了 Char Tensor 支持转换为 NumPy 和 返回值。

CUDA张量
所有的tensors都可以使用.cuda函数可以将张量移动到GPU上

# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!
'''
tensor([2.0968], device='cuda:0')
tensor([2.0968], dtype=torch.float64)
'''
Pytorch第一部分就到此结束啦 之后的学习还好继续记录 有什么问题欢迎大家一起讨论 谢谢大家。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值