前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >《自然语言处理实战入门》第二章:NLP 前置技术(深度学习) ---- pytorch

《自然语言处理实战入门》第二章:NLP 前置技术(深度学习) ---- pytorch

作者头像
流川疯
发布2021-12-06 16:07:39
4310
发布2021-12-06 16:07:39
举报
文章被收录于专栏:流川疯编写程序的艺术

文章大纲

pytorch

FROM RESEARCH TO PRODUCTION

An open source machine learning framework that accelerates the path from research prototyping to production deployment.

机器学习框架有非常多的选择,并且都在不断的更新优化。目前框架的纷争很像是多年前windows 平台上开发工具之间的竞争,我们很难说清楚未来哪个框架会成为业界标准,目前从易用性角度来说,PyTorch 和 Keras 两者大体相当,PyTorch 在自定义网络结构方面更加灵活 , 因此受到学术界青睐, 从工程应用的角度来说,TensorFlow依然可以说是业界首选。 目前PyTorch 和Keras 在易用性上可以说是旗鼓相当,所以我的建议是,时机使用中,不用纠结,但这几个框架都得会用。

初学指南 快速上手

PyTorch是一个基于Torch的Python开源机器学习库,用于自然语言处理等应用程序。它主要由Facebookd的人工智能小组开发,不仅能够 实现强大的GPU加速,同时还支持动态神经网络,这一点是现在很多主流框架如TensorFlow都不支持的。

PyTorch提供了两个高级功能:

1.具有强大的GPU加速的张量计算(如Numpy) 2.包含自动求导系统的深度神经网络 除了Facebook之外,Twitter、GMU和Salesforce等机构都采用了PyTorch。

pytorch_with_examples

PyTorch provides two main features:

  • An n-dimensional Tensor, similar to numpy but can run on GPUs
  • Automatic differentiation for building and training neural networks
  • n维张量,类似于numpy,但可以在gpu上运行
  • 神经网络建立与训练的自动微分法

We will use a problem of fitting y=sin(x) with a third order polynomial as our running example. The network will have four parameters, and will be trained with gradient descent to fit random data by minimizing the Euclidean distance between the network output and the true output.

我们将用一个三阶多项式拟合 y=sin(x)的问题作为我们的运行示例。该网络将有四个参数,并将训练梯度下降,以适应随机数据之间的欧氏距离最小的网络输出和真实输出。

核心概念

pytorch 的核心概念都有哪些,我们一一道来

Tensors 张量

Numpy提供了一个n维数组对象,以及许多用于操纵这些数组的函数。Numpy是科学计算的通用框架;但它对计算图、深度学习或梯度没有提供单独的api 进行支持。

然而,我们可以很容易地使用numpy来拟合一个三阶多项式的正弦函数,通过使用numpy操作手动实现通过网络的向前和向后传递

代码语言:javascript
复制
# -*- coding: utf-8 -*-
import numpy as np
import math

# Create random input and output data
x = np.linspace(-math.pi, math.pi, 2000)
y = np.sin(x)

# Randomly initialize weights
a = np.random.randn()
b = np.random.randn()
c = np.random.randn()
d = np.random.randn()

learning_rate = 1e-6
for t in range(2000):
    # Forward pass: compute predicted y
    # y = a + b x + c x^2 + d x^3
    y_pred = a + b * x + c * x ** 2 + d * x ** 3

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

    # Backprop to compute gradients of a, b, c, d with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_a = grad_y_pred.sum()
    grad_b = (grad_y_pred * x).sum()
    grad_c = (grad_y_pred * x ** 2).sum()
    grad_d = (grad_y_pred * x ** 3).sum()

    # Update weights
    a -= learning_rate * grad_a
    b -= learning_rate * grad_b
    c -= learning_rate * grad_c
    d -= learning_rate * grad_d

print(f'Result: y = {a} + {b} x + {c} x^2 + {d} x^3')

结果:

99 3288.197517835848 199 2205.8381090834027 299 1481.7885032948413 399 997.107843749433 499 672.4355875758466 599 454.79007403169106 699 308.78016863388564 799 210.75084411144098 899 144.88143283939323 999 100.58400374530476 1099 70.76775908079199 1199 50.68055391022465 1299 37.13519912775959 1399 27.992439559214716 1499 21.815241462367307 1599 17.637478577708208 1699 14.809056939372285 1799 12.892145784887136 1899 11.591599343247974 1999 10.70826825824747 Result: y = 0.031071994224245697 + 0.8255524078914991 x + -0.00536043604389804 x^2 + -0.08889410572720181 x^3

换成pytorch 呢?

Numpy是一个很好的框架,但是它不能利用gpu来加速它的数值计算。对于现代的深度神经网络,gpu通常提供50倍或更高的加速,所以不幸的是,numpy对于现代的深度学习是不够的。

这里我们介绍最基本的PyTorch概念:张量。 PyTorch张量在概念上与numpy数组相同:张量是n维数组 ,PyTorch提供了许多函数来操作这些张量。在幕后,张量可以跟踪计算图和梯度,但作为科学计算的通用工具,它们也很有用。

与numpy不同的是,PyTorch张量可以利用gpu加速数值计算。要在GPU上运行PyTorch张量,只需指定正确的设备。 这里我们用PyTorch张量来拟合一个三阶多项式的正弦函数。像上面的numpy示例一样,我们需要手动实现通过网络的向前和向后传递:

代码语言:javascript
复制
# -*- coding: utf-8 -*-

import torch
import math


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

# Create random input and output data
x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)
y = torch.sin(x)

# Randomly initialize weights
a = torch.randn((), device=device, dtype=dtype)
b = torch.randn((), device=device, dtype=dtype)
c = torch.randn((), device=device, dtype=dtype)
d = torch.randn((), device=device, dtype=dtype)

learning_rate = 1e-6
for t in range(2000):
    # Forward pass: compute predicted y
    y_pred = a + b * x + c * x ** 2 + d * x ** 3

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

    # Backprop to compute gradients of a, b, c, d with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_a = grad_y_pred.sum()
    grad_b = (grad_y_pred * x).sum()
    grad_c = (grad_y_pred * x ** 2).sum()
    grad_d = (grad_y_pred * x ** 3).sum()

    # Update weights using gradient descent
    a -= learning_rate * grad_a
    b -= learning_rate * grad_b
    c -= learning_rate * grad_c
    d -= learning_rate * grad_d


print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/06/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章大纲
  • pytorch
    • 初学指南 快速上手
    • 核心概念
      • Tensors 张量
      相关产品与服务
      NLP 服务
      NLP 服务(Natural Language Process,NLP)深度整合了腾讯内部的 NLP 技术,提供多项智能文本处理和文本生成能力,包括词法分析、相似词召回、词相似度、句子相似度、文本润色、句子纠错、文本补全、句子生成等。满足各行业的文本智能需求。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档