在线观看www成人影院-在线观看www日本免费网站-在线观看www视频-在线观看操-欧美18在线-欧美1级

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

PyTorch教程-6.2. 參數管理

jf_pJlTbmA9 ? 來源:PyTorch ? 作者:PyTorch ? 2023-06-05 15:44 ? 次閱讀

一旦我們選擇了一個架構并設置了我們的超參數,我們就進入訓練循環,我們的目標是找到最小化損失函數的參數值。訓練后,我們將需要這些參數來進行未來的預測。此外,我們有時會希望提取參數以在其他上下文中重用它們,將我們的模型保存到磁盤以便它可以在其他軟件中執行,或者進行檢查以期獲得科學理解。

大多數時候,我們將能夠忽略參數聲明和操作的具體細節,依靠深度學習框架來完成繁重的工作。然而,當我們遠離具有標準層的堆疊架構時,我們有時需要陷入聲明和操作參數的困境。在本節中,我們將介紹以下內容:

訪問用于調試、診斷和可視化的參數。

跨不同模型組件共享參數。

import torch
from torch import nn

from mxnet import init, np, npx
from mxnet.gluon import nn

npx.set_np()

import jax
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 tensorflow as tf

我們首先關注具有一個隱藏層的 MLP。

net = nn.Sequential(nn.LazyLinear(8),
          nn.ReLU(),
          nn.LazyLinear(1))

X = torch.rand(size=(2, 4))
net(X).shape

torch.Size([2, 1])

net = nn.Sequential()
net.add(nn.Dense(8, activation='relu'))
net.add(nn.Dense(1))
net.initialize() # Use the default initialization method

X = np.random.uniform(size=(2, 4))
net(X).shape

(2, 1)

net = nn.Sequential([nn.Dense(8), nn.relu, nn.Dense(1)])

X = jax.random.uniform(d2l.get_key(), (2, 4))
params = net.init(d2l.get_key(), X)
net.apply(params, X).shape

(2, 1)

net = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(4, activation=tf.nn.relu),
  tf.keras.layers.Dense(1),
])

X = tf.random.uniform((2, 4))
net(X).shape

TensorShape([2, 1])

6.2.1. 參數訪問

讓我們從如何從您已知的模型中訪問參數開始。

當通過類定義模型時Sequential,我們可以首先通過索引模型來訪問任何層,就好像它是一個列表一樣。每個層的參數都方便地位于其屬性中。

When a model is defined via the Sequential class, we can first access any layer by indexing into the model as though it were a list. Each layer’s parameters are conveniently located in its attribute.

Flax and JAX decouple the model and the parameters as you might have observed in the models defined previously. When a model is defined via the Sequential class, we first need to initialize the network to generate the parameters dictionary. We can access any layer’s parameters through the keys of this dictionary.

When a model is defined via the Sequential class, we can first access any layer by indexing into the model as though it were a list. Each layer’s parameters are conveniently located in its attribute.

我們可以如下檢查第二個全連接層的參數。

net[2].state_dict()

OrderedDict([('weight',
       tensor([[-0.2523, 0.2104, 0.2189, -0.0395, -0.0590, 0.3360, -0.0205, -0.1507]])),
       ('bias', tensor([0.0694]))])

net[1].params

dense1_ (
 Parameter dense1_weight (shape=(1, 8), dtype=float32)
 Parameter dense1_bias (shape=(1,), dtype=float32)
)

params['params']['layers_2']

FrozenDict({
  kernel: Array([[-0.20739523],
      [ 0.16546965],
      [-0.03713543],
      [-0.04860032],
      [-0.2102929 ],
      [ 0.163712 ],
      [ 0.27240783],
      [-0.4046879 ]], dtype=float32),
  bias: Array([0.], dtype=float32),
})

net.layers[2].weights

[,
 ]

我們可以看到這個全連接層包含兩個參數,分別對應于該層的權重和偏差。

6.2.1.1. 目標參數

請注意,每個參數都表示為參數類的一個實例。要對參數做任何有用的事情,我們首先需要訪問基礎數值。做這件事有很多種方法。有些更簡單,有些則更通用。以下代碼從返回參數類實例的第二個神經網絡層中提取偏差,并進一步訪問該參數的值。

type(net[2].bias), net[2].bias.data

(torch.nn.parameter.Parameter, tensor([0.0694]))

參數是復雜的對象,包含值、梯度和附加信息。這就是為什么我們需要顯式請求該值。

除了值之外,每個參數還允許我們訪問梯度。因為我們還沒有為這個網絡調用反向傳播,所以它處于初始狀態。

net[2].weight.grad == None

True

type(net[1].bias), net[1].bias.data()

(mxnet.gluon.parameter.Parameter, array([0.]))

Parameters are complex objects, containing values, gradients, and additional information. That is why we need to request the value explicitly.

In addition to the value, each parameter also allows us to access the gradient. Because we have not invoked backpropagation for this network yet, it is in its initial state.

net[1].weight.grad()

array([[0., 0., 0., 0., 0., 0., 0., 0.]])

bias = params['params']['layers_2']['bias']
type(bias), bias

(jaxlib.xla_extension.Array, Array([0.], dtype=float32))

Unlike the other frameworks, JAX does not keep a track of the gradients over the neural network parameters, instead the parameters and the network are decoupled. It allows the user to express their computation as a Python function, and use the grad transformation for the same purpose.

type(net.layers[2].weights[1]), tf.convert_to_tensor(net.layers[2].weights[1])

(tensorflow.python.ops.resource_variable_ops.ResourceVariable,
 )

6.2.1.2. 一次所有參數

當我們需要對所有參數執行操作時,一個一個地訪問它們會變得乏味。當我們使用更復雜的模塊(例如,嵌套模塊)時,情況會變得特別笨拙,因為我們需要遞歸遍歷整個樹以提取每個子模塊的參數。下面我們演示訪問所有層的參數。

[(name, param.shape) for name, param in net.named_parameters()]

[('0.weight', torch.Size([8, 4])),
 ('0.bias', torch.Size([8])),
 ('2.weight', torch.Size([1, 8])),
 ('2.bias', torch.Size([1]))]

net.collect_params()

sequential0_ (
 Parameter dense0_weight (shape=(8, 4), dtype=float32)
 Parameter dense0_bias (shape=(8,), dtype=float32)
 Parameter dense1_weight (shape=(1, 8), dtype=float32)
 Parameter dense1_bias (shape=(1,), dtype=float32)
)

jax.tree_util.tree_map(lambda x: x.shape, params)

FrozenDict({
  params: {
    layers_0: {
      bias: (8,),
      kernel: (4, 8),
    },
    layers_2: {
      bias: (1,),
      kernel: (8, 1),
    },
  },
})

net.get_weights()

[array([[-0.42006454, 0.6094975 , -0.30087888, 0.42557293],
    [-0.26464057, -0.5518195 , 0.5476741 , 0.31728595],
    [-0.5571538 , -0.33794886, -0.05885679, 0.05435681],
    [ 0.28541476, 0.8276871 , -0.7665834 , 0.5791599 ]],
    dtype=float32),
 array([0., 0., 0., 0.], dtype=float32),
 array([[-0.52124995],
    [-0.22314149],
    [ 0.20780373],
    [ 0.6839919 ]], dtype=float32),
 array([0.], dtype=float32)]

6.2.2. 綁定參數

通常,我們希望跨多個層共享參數。讓我們看看如何優雅地做到這一點。下面我們分配一個全連接層,然后專門使用它的參數來設置另一層的參數。這里我們需要net(X)在訪問參數之前運行前向傳播。

# We need to give the shared layer a name so that we can refer to its
# parameters
shared = nn.LazyLinear(8)
net = nn.Sequential(nn.LazyLinear(8), nn.ReLU(),
          shared, nn.ReLU(),
          shared, nn.ReLU(),
          nn.LazyLinear(1))

net(X)
# Check whether the parameters are the same
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0, 0] = 100
# Make sure that they are actually the same object rather than just having the
# same value
print(net[2].weight.data[0] == net[4].weight.data[0])

tensor([True, True, True, True, True, True, True, True])
tensor([True, True, True, True, True, True, True, True])

net = nn.Sequential()
# We need to give the shared layer a name so that we can refer to its
# parameters
shared = nn.Dense(8, activation='relu')
net.add(nn.Dense(8, activation='relu'),
    shared,
    nn.Dense(8, activation='relu', params=shared.params),
    nn.Dense(10))
net.initialize()

X = np.random.uniform(size=(2, 20))

net(X)
# Check whether the parameters are the same
print(net[1].weight.data()[0] == net[2].weight.data()[0])
net[1].weight.data()[0, 0] = 100
# Make sure that they are actually the same object rather than just having the
# same value
print(net[1].weight.data()[0] == net[2].weight.data()[0])

[ True True True True True True True True]
[ True True True True True True True True]

# We need to give the shared layer a name so that we can refer to its
# parameters
shared = nn.Dense(8)
net = nn.Sequential([nn.Dense(8), nn.relu,
           shared, nn.relu,
           shared, nn.relu,
           nn.Dense(1)])

params = net.init(jax.random.PRNGKey(d2l.get_seed()), X)

# Check whether the parameters are different
print(len(params['params']) == 3)

True

# tf.keras behaves a bit differently. It removes the duplicate layer
# automatically
shared = tf.keras.layers.Dense(4, activation=tf.nn.relu)
net = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(),
  shared,
  shared,
  tf.keras.layers.Dense(1),
])

net(X)
# Check whether the parameters are different
print(len(net.layers) == 3)

True

這個例子表明第二層和第三層的參數是綁定的。它們不僅相等,而且由完全相同的張量表示。因此,如果我們改變其中一個參數,另一個參數也會改變。

您可能想知道,當參數綁定時梯度會發生什么變化?由于模型參數包含梯度,因此在反向傳播時將第二個隱藏層和第三個隱藏層的梯度相加。

You might wonder, when parameters are tied what happens to the gradients? Since the model parameters contain gradients, the gradients of the second hidden layer and the third hidden layer are added together during backpropagation.

You might wonder, when parameters are tied what happens to the gradients? Since the model parameters contain gradients, the gradients of the second hidden layer and the third hidden layer are added together during backpropagation.

6.2.3. 概括

我們有幾種方法來訪問和綁定模型參數。

6.2.4. 練習

使用第 6.1 節NestMLP中定義的模型 并訪問各個層的參數。

構造一個包含共享參數層的 MLP 并對其進行訓練。在訓練過程中,觀察每一層的模型參數和梯度。

為什么共享參數是個好主意?

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • pytorch
    +關注

    關注

    2

    文章

    809

    瀏覽量

    13794
收藏 人收藏

    評論

    相關推薦
    熱點推薦

    在Windows 10上安裝WICED Studio 6.2沒有足夠的可用磁盤空間

    disk space I am also encountered the same problem on version 6.2. There is more than 600GB free, so
    發表于 09-18 14:29

    Pytorch入門之的基本操作

    Pytorch入門之基本操作
    發表于 05-22 17:15

    PyTorch如何入門

    PyTorch 入門實戰(一)——Tensor
    發表于 06-01 09:58

    Pytorch AI語音助手

    想做一個Pytorch AI語音助手,有沒有好的思路呀?
    發表于 03-06 13:00

    如何安裝TensorFlow2 Pytorch?

    如何安裝TensorFlow2 Pytorch?
    發表于 03-07 07:32

    如何往星光2板子里裝pytorch

    如題,想先gpu版本的pytorch只安裝cpu版本的pytorch,pytorch官網提供了基于conda和pip兩種安裝方式。因為咱是risc架構沒對應的conda,而使用pip安裝提示也沒有
    發表于 09-12 06:30

    pytorch模型轉換需要注意的事項有哪些?

    什么是JIT(torch.jit)? 答:JIT(Just-In-Time)是一組編譯工具,用于彌合PyTorch研究與生產之間的差距。它允許創建可以在不依賴Python解釋器的情況下運行的模型
    發表于 09-18 08:05

    6.2億部設備采用 Red Bend 移動軟件管理客戶端

    6.2億部設備采用 Red Bend 移動軟件管理客戶端     馬薩諸塞州沃爾瑟姆2009年11月30日電 /美通社亞洲/ -- 移動軟件管理 (MSM) 領域的
    發表于 11-30 17:46 ?984次閱讀

    基于PyTorch的深度學習入門教程之PyTorch簡單知識

    本文參考PyTorch官網的教程,分為五個基本模塊來介紹PyTorch。為了避免文章過長,這五個模塊分別在五篇博文中介紹。 Part1:PyTorch簡單知識 Part2:PyTorch
    的頭像 發表于 02-16 15:20 ?2471次閱讀

    PyTorch教程6.2參數管理

    電子發燒友網站提供《PyTorch教程6.2參數管理.pdf》資料免費下載
    發表于 06-05 15:24 ?0次下載
    <b class='flag-5'>PyTorch</b>教程<b class='flag-5'>6.2</b>之<b class='flag-5'>參數</b><b class='flag-5'>管理</b>

    PyTorch教程13.7之參數服務器

    電子發燒友網站提供《PyTorch教程13.7之參數服務器.pdf》資料免費下載
    發表于 06-05 14:22 ?0次下載
    <b class='flag-5'>PyTorch</b>教程13.7之<b class='flag-5'>參數</b>服務器

    PyTorch教程19.1之什么是超參數優化

    電子發燒友網站提供《PyTorch教程19.1之什么是超參數優化.pdf》資料免費下載
    發表于 06-05 10:25 ?0次下載
    <b class='flag-5'>PyTorch</b>教程19.1之什么是超<b class='flag-5'>參數</b>優化

    PyTorch教程19.2之超參數優化API

    電子發燒友網站提供《PyTorch教程19.2之超參數優化API.pdf》資料免費下載
    發表于 06-05 10:27 ?0次下載
    <b class='flag-5'>PyTorch</b>教程19.2之超<b class='flag-5'>參數</b>優化API

    PyTorch教程19.4之多保真超參數優化

    電子發燒友網站提供《PyTorch教程19.4之多保真超參數優化.pdf》資料免費下載
    發表于 06-05 10:45 ?0次下載
    <b class='flag-5'>PyTorch</b>教程19.4之多保真超<b class='flag-5'>參數</b>優化

    pycharm如何調用pytorch

    引言 PyTorch是一個開源的機器學習庫,廣泛用于計算機視覺、自然語言處理等領域。PyCharm是一個流行的Python集成開發環境(IDE),提供了代碼編輯、調試、測試等功能。將PyTorch
    的頭像 發表于 08-01 15:41 ?1126次閱讀
    主站蜘蛛池模板: 午夜精品久久久久蜜桃 | 色视频在线观看 | 久久精品国产精品亚洲人人 | 成人精品视频一区二区三区 | 免费播放特黄特色毛片 | 么公的好大好硬好深好爽在线视频 | 国产精品欧美一区二区三区 | 色婷婷影院在线视频免费播放 | 蕾丝视频在线播放 | 美女视频网站色软件免费视频 | 99久久精品免费精品国产 | 欧美三级黄色 | 在线观看免费xx高清视频 | 白嫩美女在线啪视频观看 | 一级伦奸视频 | 色婷婷丁香六月 | 户外露出精品视频国产 | 三级黄色一级视频 | 女同久久| 一级做a爱片久久毛片 | 国产欧美另类第一页 | www.激情网.com | 欧美午夜精品一区二区三区 | 欧美大胆一级视频 | 久久奈| 操美女免费视频 | 男女爱爱是免费看 | 中韩日欧美电影免费看 | 欧美色综合高清视频在线 | 性大特级毛片视频 | 国产美女精品三级在线观看 | 久久精品波多野结衣 | 综合欧美一区二区三区 | 高清午夜线观看免费 | 欧美天堂视频 | 五月六月婷婷 | 夜夜操操操 | 性感美女逼 | 色爽爽爽| 亚洲开心激情网 | 亚洲一卡2卡3卡4卡5卡乱码 |