【Pytorch 学习笔记(五)】:跟着样例学torch

跟着样例学torch

本系列教程通过一系列独立的例子来介绍torch的基础概念。

torch的两个核心功能:

  • n维张量,类似于numpy,但可以在GPU上运行。
  • 对构建中和训练中的NN自动微分。

接下来我们会使用全连接的 ReLU 网络作为我们的示例网络。 该网络将具有单个隐藏层,并且将通过最小化网络输出与真实输出之间的欧几里德距离来进行梯度下降训练,以适应随机数据。

Tensors

Warm-up: numpy

在介绍Pytorch之前,我们首先会用numpy来使实现一下网络。

Numpy提供了n维数组对象和许多可以操作这些数组的方法。Numpy 是用于科学计算的通用框架,可惜的是,它不包括任何关于计算图,深度学习或梯度的内容。但是我们依然可以通过使用numpy手动实现网络的前向和后向传播来使两层网络可以适应随机数据。

# -*- coding: utf-8 -*-
import numpy as np

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random input and output data
x = np.random.randn(N, D_in)
y = np.random.randn(N, D_out)

# Randomly initialize weights
w1 = np.random.randn(D_in, H)
w2 = np.random.randn(H, D_out)

learning_rate = 1e-6
for t in range(500):
    # Forward pass: compute predicted y
    h = x.dot(w1)
    h_relu = np.maximum(h, 0)
    y_pred = h_relu.dot(w2)

    # Compute and print loss
    loss = np.square(y_pred - y).sum()
    print(t, loss)

    # Backprop to compute gradients of w1 and w2 with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.T.dot(grad_y_pred)
    grad_h_relu = grad_y_pred.dot(w2.T)
    grad_h = grad_h_relu.copy()
    grad_h[h < 0] = 0
    grad_w1 = x.T.dot(grad_h)

    # Update weights
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2

Tensors

Numpy 是一个很好的框架,但是它不可以使用GPU来加速数值计算。对于现在的深度神经网络,GPU通常都可以提供50x甚至更高的加速效果。但很遗憾,numpy不足以支持深度学习。

接下来我们会介绍Pytorch概念中最基础重要的一个:Tensor。从概念上说,Pytorch Tensor和numpy array是相同的:一个Tensor就是一个n维数组,并且torch可以提供很多用于这些Tensor的操作。除此之外,Tensor可以追踪一个计算图和其梯度,同时它对于科学计算也很有帮助。

另外,不同于Numpy,Pytorch可以利用GPU来加速计算过程。如果想要在GPU上运行一个Tensor,只需要简单地转换一下它的数据类型。

在这里,我们使用Pytorch Tensors来使两层网络可以使用于随机数据。像上面的numpy示例一样,我们需要手动实现网络的前向和后向转播过程。

# -*- coding: utf-8 -*-

import torch


dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random input and output data
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out, device=device, dtype=dtype)

learning_rate = 1e-6
for t in range(500):
    # Forward pass: compute predicted y
    h = x.mm(w1)
    h_relu = h.clamp(min=0)
    y_pred = h_relu.mm(w2)

    # Compute and print loss
    loss = (y_pred - y).pow(2).sum().item()
    if t % 100 == 99:
        print(t, loss)

    # Backprop to compute gradients of w1 and w2 with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.t().mm(grad_y_pred)
    grad_h_relu = grad_y_pred.mm(w2.t())
    grad_h = grad_h_relu.clone()
    grad_h[h < 0] = 0
    grad_w1 = x.t().mm(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值