電子發(fā)燒友App

硬聲App

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示
創(chuàng)作
電子發(fā)燒友網(wǎng)>電子資料下載>電子資料>PyTorch教程3.5之線性回歸的簡(jiǎn)潔實(shí)現(xiàn)

PyTorch教程3.5之線性回歸的簡(jiǎn)潔實(shí)現(xiàn)

2023-06-05 | pdf | 0.22 MB | 次下載 | 免費(fèi)

資料介紹

在過(guò)去的十年中,深度學(xué)習(xí)見(jiàn)證了某種形式的寒武紀(jì)大爆發(fā)。技術(shù)、應(yīng)用和算法的絕對(duì)數(shù)量遠(yuǎn)遠(yuǎn)超過(guò)了前幾十年的進(jìn)步。這是由于多種因素的偶然組合,其中之一是許多開(kāi)源深度學(xué)習(xí)框架提供的強(qiáng)大的免費(fèi)工具。Theano Bergstra等人,2010 年、DistBelief Dean等人,2012 年和 Caffe Jia等人,2014 年可以說(shuō)代表了被廣泛采用的第一代此類模型。與 SN2 (Simulateur Neuristique) 等早期(開(kāi)創(chuàng)性)作品相比 Bottou 和 Le Cun,1988,它提供了類似 Lisp 的編程體驗(yàn),現(xiàn)代框架提供了自動(dòng)微分和 Python 的便利性。這些框架使我們能夠自動(dòng)化和模塊化實(shí)現(xiàn)基于梯度的學(xué)習(xí)算法的重復(fù)性工作。

3.4 節(jié)中,我們僅依靠 (i) 張量進(jìn)行數(shù)據(jù)存儲(chǔ)和線性代數(shù);(ii) 計(jì)算梯度的自動(dòng)微分。在實(shí)踐中,由于數(shù)據(jù)迭代器、損失函數(shù)、優(yōu)化器和神經(jīng)網(wǎng)絡(luò)層非常普遍,現(xiàn)代圖書(shū)館也為我們實(shí)現(xiàn)了這些組件。在本節(jié)中,我們將向您展示如何 使用深度學(xué)習(xí)框架的高級(jí) API 簡(jiǎn)潔地實(shí)現(xiàn)3.4 節(jié)中的線性回歸模型。

import numpy as np
import torch
from torch import nn
from d2l import torch as d2l
from mxnet import autograd, gluon, init, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l

npx.set_np()
import jax
import optax
from flax import linen as nn
from jax import numpy as jnp
from d2l import jax as d2l
No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
import numpy as np
import tensorflow as tf
from d2l import tensorflow as d2l

3.5.1. 定義模型

當(dāng)我們?cè)诘?3.4 節(jié)中從頭開(kāi)始實(shí)現(xiàn)線性回歸時(shí) ,我們明確定義了我們的模型參數(shù)并編寫了計(jì)算代碼以使用基本線性代數(shù)運(yùn)算生成輸出。應(yīng)該知道如何做到這一點(diǎn)。但是一旦您的模型變得更加復(fù)雜,并且一旦您幾乎每天都必須這樣做,您就會(huì)很高興獲得幫助。這種情況類似于從頭開(kāi)始編寫自己的博客。做一兩次是有益和有益的,但如果你花一個(gè)月重新發(fā)明輪子,你將成為一個(gè)糟糕的 Web 開(kāi)發(fā)人員。

對(duì)于標(biāo)準(zhǔn)操作,我們可以使用框架的預(yù)定義層,這使我們能夠?qū)W⒂谟糜跇?gòu)建模型的層,而不用擔(dān)心它們的實(shí)現(xiàn)。回想一下圖 3.1.2中描述的單層網(wǎng)絡(luò)的架構(gòu)。該層稱為全連接層,因?yàn)樗拿總€(gè)輸入都通過(guò)矩陣向量乘法連接到它的每個(gè)輸出。

在 PyTorch 中,全連接層定義在LinearLazyLinear(自版本 1.8.0 起可用)類中。后者允許用戶指定輸出維度,而前者額外詢問(wèn)有多少輸入進(jìn)入該層。指定輸入形狀很不方便,這可能需要大量的計(jì)算(例如在卷積層中)。因此,為簡(jiǎn)單起見(jiàn),我們將盡可能使用此類“惰性”層。

class LinearRegression(d2l.Module): #@save
  """The linear regression model implemented with high-level APIs."""
  def __init__(self, lr):
    super().__init__()
    self.save_hyperparameters()
    self.net = nn.LazyLinear(1)
    self.net.weight.data.normal_(0, 0.01)
    self.net.bias.data.fill_(0)

In Gluon, the fully connected layer is defined in the Dense class. Since we only want to generate a single scalar output, we set that number to 1. It is worth noting that, for convenience, Gluon does not require us to specify the input shape for each layer. Hence we do not need to tell Gluon how many inputs go into this linear layer. When we first pass data through our model, e.g., when we execute net(X) later, Gluon will automatically infer the number of inputs to each layer and thus instantiate the correct model. We will describe how this works in more detail later.

class LinearRegression(d2l.Module): #@save
  """The linear regression model implemented with high-level APIs."""
  def __init__(self, lr):
    super().__init__()
    self.save_hyperparameters()
    self.net = nn.Dense(1)
    self.net.initialize(init.Normal(sigma=0.01))
class LinearRegression(d2l.Module): #@save
  """The linear regression model implemented with high-level APIs."""
  lr: float

  def setup(self):
    self.net = nn.Dense(1, kernel_init=nn.initializers.normal(0.01))

In Keras, the fully connected layer is defined in the Dense class. Since we only want to generate a single scalar output, we set that number to 1. It is worth noting that, for convenience, Keras does not require us to specify the input shape for each layer. We do not need to tell Keras how many inputs go into this linear layer. When we first try to pass data through our model, e.g., when we execute net(X) later, Keras will automatically infer the number of inputs to each layer. We will describe how this works in more detail later.

class LinearRegression(d2l.Module): #@save
  """The linear regression model implemented with high-level APIs."""
  def __init__(self, lr):
    super().__init__()
    self.save_hyperparameters()
    initializer = tf.initializers.RandomNormal(stddev=0.01)
    self.net = tf.keras.layers.Dense(1, kernel_initializer=initializer)

forward方法中,我們只調(diào)用預(yù)定義層的內(nèi)置__call__ 方法來(lái)計(jì)算輸出。

@d2l.add_to_class(LinearRegression) #@save
def forward(self, X):
  return self.net(X)
@d2l.add_to_class(LinearRegression) #@save
def forward(self, X):
  return self.net(X)
@d2l.add_to_class(LinearRegression) #@save
def forward(self, X):
  return self.net(X)
@d2l.add_to_class(LinearRegression) #@save
def forward(self, X):
  return self.net(X)

3.5.2. 定義損失函數(shù)

該類MSELoss計(jì)算均方誤差(沒(méi)有 1/2(3.1.5)中的因素)。默認(rèn)情況下,MSELoss 返回示例的平均損失。它比我們自己實(shí)現(xiàn)更快(也更容易使用)。

@d2l.add_to_class(LinearRegression) #@save
def loss(self, y_hat, y):
  fn = nn.MSELoss()
  return fn(y_hat, y)

The loss module defines many useful loss functions. For speed and convenience, we forgo implementing our own and choose the built-in loss.L2Loss instead. Because the loss that it returns is the squared error for each example, we use meanto average the loss across over the minibatch.

@d2l.add_to_class(LinearRegression) #@save
def loss(self, y_hat, y):
  fn = gluon.loss.L2Loss()
  return fn(y_hat, y).mean()
@d2l.add_to_class(LinearRegression) #@save
def loss(self, params, X, y, state):
  y_hat = state.apply_fn({'params': params}, *X)
  return optax.l2_loss(y_hat, y).mean()

The MeanSquaredError class computes the mean squared error (without the 1/2 factor in (3.1.5)). By default, it returns the average loss over examples.

@d2l.add_to_class(LinearRegression) #@save
def loss(self, y_hat, y):
  fn = tf.keras.losses.MeanSquaredError()
  return fn(y, y_hat)

3.5.3. 定義優(yōu)化算法

Minibatch SGD 是用于優(yōu)化神經(jīng)網(wǎng)絡(luò)的標(biāo)準(zhǔn)工具,因此 PyTorch 支持它以及模塊中該算法的許多變體optim。當(dāng)我們實(shí)例化一個(gè)SGD實(shí)例時(shí),我們指定要優(yōu)化的參數(shù),可通過(guò) 和我們的優(yōu)化算法所需的self.parameters()學(xué)習(xí)率 ( ) 從我們的模型中獲得。self.lr


下載該資料的人也在下載 下載該資料的人還在閱讀
更多 >

評(píng)論

查看更多

下載排行

本周

  1. 1ADE-12H混頻器規(guī)格書(shū)
  2. 0.28 MB   |  1次下載  |  5 積分
  3. 2AD9984A高性能10位顯示接口英文手冊(cè)
  4. 0.49 MB   |  1次下載  |  5 積分
  5. 351開(kāi)發(fā)板芯片資料
  6. 14.95 MB   |  1次下載  |  1 積分
  7. 4用TL431LI-Q1監(jiān)控電流供應(yīng)
  8. 176.71KB   |  1次下載  |  免費(fèi)
  9. 5十進(jìn)制數(shù)據(jù)轉(zhuǎn)十六進(jìn)制字符_轉(zhuǎn)ASCII碼
  10. 0.01 MB   |  次下載  |  免費(fèi)
  11. 6使用TRF7970A進(jìn)行NFC主動(dòng)和被動(dòng)點(diǎn)對(duì)點(diǎn)通信
  12. 926.87KB   |  次下載  |  免費(fèi)
  13. 7LP8864-Q1 LP8864S-Q1 LP8866-Q1和LP8866S-Q1診斷說(shuō)明和故障處理程序
  14. 577.42KB   |  次下載  |  免費(fèi)
  15. 8將設(shè)計(jì)移植到LP3470A低lq電壓監(jiān)控器,以改善電源監(jiān)控
  16. 115.28KB   |  次下載  |  免費(fèi)

本月

  1. 1HFSS電磁仿真設(shè)計(jì)應(yīng)用詳解PDF電子教程免費(fèi)下載
  2. 24.30 MB   |  129次下載  |  1 積分
  3. 2正激、反激、推挽、全橋、半橋區(qū)別和特點(diǎn)
  4. 0.91 MB   |  36次下載  |  1 積分
  5. 3GBT 4706.1-2024家用和類似用途電器的安全第1部分:通用要求
  6. 7.43 MB   |  20次下載  |  免費(fèi)
  7. 4在設(shè)計(jì)中使用MOSFET瞬態(tài)熱阻抗曲線
  8. 1.57MB   |  15次下載  |  免費(fèi)
  9. 5幾張電動(dòng)車充電器電路圖
  10. 0.23 MB   |  9次下載  |  1 積分
  11. 6AD18學(xué)習(xí)筆記
  12. 14.47 MB   |  8次下載  |  2 積分
  13. 7H橋中的電流感測(cè)
  14. 545.39KB   |  7次下載  |  免費(fèi)
  15. 8電機(jī)驅(qū)動(dòng)器電路板布局的最佳實(shí)踐
  16. 3.03MB   |  6次下載  |  免費(fèi)

總榜

  1. 1matlab軟件下載入口
  2. 未知  |  935113次下載  |  10 積分
  3. 2開(kāi)源硬件-PMP21529.1-4 開(kāi)關(guān)降壓/升壓雙向直流/直流轉(zhuǎn)換器 PCB layout 設(shè)計(jì)
  4. 1.48MB  |  420061次下載  |  10 積分
  5. 3Altium DXP2002下載入口
  6. 未知  |  233084次下載  |  10 積分
  7. 4電路仿真軟件multisim 10.0免費(fèi)下載
  8. 340992  |  191360次下載  |  10 積分
  9. 5十天學(xué)會(huì)AVR單片機(jī)與C語(yǔ)言視頻教程 下載
  10. 158M  |  183329次下載  |  10 積分
  11. 6labview8.5下載
  12. 未知  |  81578次下載  |  10 積分
  13. 7Keil工具M(jìn)DK-Arm免費(fèi)下載
  14. 0.02 MB  |  73804次下載  |  10 積分
  15. 8LabVIEW 8.6下載
  16. 未知  |  65985次下載  |  10 積分