日B视频 亚洲,啪啪啪网站一区二区,91色情精品久久,日日噜狠狠色综合久,超碰人妻少妇97在线,999青青视频,亚洲一区二卡,让本一区二区视频,日韩网站推荐

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

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

3天內(nèi)不再提示

PyTorch教程-4.3. 基本分類(lèi)模型

jf_pJlTbmA9 ? 來(lái)源:PyTorch ? 作者:PyTorch ? 2023-06-05 15:43 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

您可能已經(jīng)注意到,在回歸的情況下,從頭開(kāi)始的實(shí)現(xiàn)和使用框架功能的簡(jiǎn)潔實(shí)現(xiàn)非常相似。分類(lèi)也是如此。由于本書(shū)中的許多模型都處理分類(lèi),因此值得添加專(zhuān)門(mén)支持此設(shè)置的功能。本節(jié)為分類(lèi)模型提供了一個(gè)基類(lèi),以簡(jiǎn)化以后的代碼。

import torch
from d2l import torch as d2l

from mxnet import autograd, gluon, np, npx
from d2l import mxnet as d2l

npx.set_np()

from functools import partial
import jax
import optax
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
from d2l import tensorflow as d2l

4.3.1. 類(lèi)Classifier_

我們?cè)谙旅娑xClassifier類(lèi)。在中,validation_step我們報(bào)告了驗(yàn)證批次的損失值和分類(lèi)準(zhǔn)確度。我們?yōu)槊總€(gè)批次繪制一個(gè)更新num_val_batches 。這有利于在整個(gè)驗(yàn)證數(shù)據(jù)上生成平均損失和準(zhǔn)確性。如果最后一批包含的示例較少,則這些平均數(shù)并不完全正確,但我們忽略了這一微小差異以保持代碼簡(jiǎn)單。

class Classifier(d2l.Module): #@save
  """The base class of classification models."""
  def validation_step(self, batch):
    Y_hat = self(*batch[:-1])
    self.plot('loss', self.loss(Y_hat, batch[-1]), train=False)
    self.plot('acc', self.accuracy(Y_hat, batch[-1]), train=False)

We define the Classifier class below. In the validation_step we report both the loss value and the classification accuracy on a validation batch. We draw an update for every num_val_batches batches. This has the benefit of generating the averaged loss and accuracy on the whole validation data. These average numbers are not exactly correct if the last batch contains fewer examples, but we ignore this minor difference to keep the code simple.

class Classifier(d2l.Module): #@save
  """The base class of classification models."""
  def validation_step(self, batch):
    Y_hat = self(*batch[:-1])
    self.plot('loss', self.loss(Y_hat, batch[-1]), train=False)
    self.plot('acc', self.accuracy(Y_hat, batch[-1]), train=False)

We define the Classifier class below. In the validation_step we report both the loss value and the classification accuracy on a validation batch. We draw an update for every num_val_batches batches. This has the benefit of generating the averaged loss and accuracy on the whole validation data. These average numbers are not exactly correct if the last batch contains fewer examples, but we ignore this minor difference to keep the code simple.

We also redefine the training_step method for JAX since all models that will subclass Classifier later will have a loss that returns auxiliary data. This auxiliary data can be used for models with batch normalization (to be explained in Section 8.5), while in all other cases we will make the loss also return a placeholder (empty dictionary) to represent the auxiliary data.

class Classifier(d2l.Module): #@save
  """The base class of classification models."""
  def training_step(self, params, batch, state):
    # Here value is a tuple since models with BatchNorm layers require
    # the loss to return auxiliary data
    value, grads = jax.value_and_grad(
      self.loss, has_aux=True)(params, batch[:-1], batch[-1], state)
    l, _ = value
    self.plot("loss", l, train=True)
    return value, grads

  def validation_step(self, params, batch, state):
    # Discard the second returned value. It is used for training models
    # with BatchNorm layers since loss also returns auxiliary data
    l, _ = self.loss(params, batch[:-1], batch[-1], state)
    self.plot('loss', l, train=False)
    self.plot('acc', self.accuracy(params, batch[:-1], batch[-1], state),
         train=False)

We define the Classifier class below. In the validation_step we report both the loss value and the classification accuracy on a validation batch. We draw an update for every num_val_batches batches. This has the benefit of generating the averaged loss and accuracy on the whole validation data. These average numbers are not exactly correct if the last batch contains fewer examples, but we ignore this minor difference to keep the code simple.

class Classifier(d2l.Module): #@save
  """The base class of classification models."""
  def validation_step(self, batch):
    Y_hat = self(*batch[:-1])
    self.plot('loss', self.loss(Y_hat, batch[-1]), train=False)
    self.plot('acc', self.accuracy(Y_hat, batch[-1]), train=False)

默認(rèn)情況下,我們使用隨機(jī)梯度下降優(yōu)化器,在小批量上運(yùn)行,就像我們?cè)诰€性回歸的上下文中所做的那樣。

@d2l.add_to_class(d2l.Module) #@save
def configure_optimizers(self):
  return torch.optim.SGD(self.parameters(), lr=self.lr)

@d2l.add_to_class(d2l.Module) #@save
def configure_optimizers(self):
  params = self.parameters()
  if isinstance(params, list):
    return d2l.SGD(params, self.lr)
  return gluon.Trainer(params, 'sgd', {'learning_rate': self.lr})

@d2l.add_to_class(d2l.Module) #@save
def configure_optimizers(self):
  return optax.sgd(self.lr)

@d2l.add_to_class(d2l.Module) #@save
def configure_optimizers(self):
  return tf.keras.optimizers.SGD(self.lr)

4.3.2. 準(zhǔn)確性

給定預(yù)測(cè)概率分布y_hat,每當(dāng)我們必須輸出硬預(yù)測(cè)時(shí),我們通常會(huì)選擇預(yù)測(cè)概率最高的類(lèi)別。事實(shí)上,許多應(yīng)用程序需要我們做出選擇。例如,Gmail 必須將電子郵件分類(lèi)為“主要”、“社交”、“更新”、“論壇”或“垃圾郵件”。它可能會(huì)在內(nèi)部估計(jì)概率,但最終它必須在類(lèi)別中選擇一個(gè)。

當(dāng)預(yù)測(cè)與標(biāo)簽 class 一致時(shí)y,它們是正確的。分類(lèi)準(zhǔn)確度是所有正確預(yù)測(cè)的分?jǐn)?shù)。盡管直接優(yōu)化精度可能很困難(不可微分),但它通常是我們最關(guān)心的性能指標(biāo)。它通常是基準(zhǔn)測(cè)試中的相關(guān)數(shù)量。因此,我們幾乎總是在訓(xùn)練分類(lèi)器時(shí)報(bào)告它。

準(zhǔn)確度計(jì)算如下。首先,如果y_hat是一個(gè)矩陣,我們假設(shè)第二個(gè)維度存儲(chǔ)每個(gè)類(lèi)別的預(yù)測(cè)分?jǐn)?shù)。我們使用argmax每行中最大條目的索引來(lái)獲取預(yù)測(cè)類(lèi)。然后我們將預(yù)測(cè)的類(lèi)別與真實(shí)的元素進(jìn)行比較y。由于相等運(yùn)算符== 對(duì)數(shù)據(jù)類(lèi)型敏感,因此我們轉(zhuǎn)換 的y_hat數(shù)據(jù)類(lèi)型以匹配 的數(shù)據(jù)類(lèi)型y。結(jié)果是一個(gè)包含條目 0(假)和 1(真)的張量。求和得出正確預(yù)測(cè)的數(shù)量。

@d2l.add_to_class(Classifier) #@save
def accuracy(self, Y_hat, Y, averaged=True):
  """Compute the number of correct predictions."""
  Y_hat = Y_hat.reshape((-1, Y_hat.shape[-1]))
  preds = Y_hat.argmax(axis=1).type(Y.dtype)
  compare = (preds == Y.reshape(-1)).type(torch.float32)
  return compare.mean() if averaged else compare

@d2l.add_to_class(Classifier) #@save
def accuracy(self, Y_hat, Y, averaged=True):
  """Compute the number of correct predictions."""
  Y_hat = Y_hat.reshape((-1, Y_hat.shape[-1]))
  preds = Y_hat.argmax(axis=1).astype(Y.dtype)
  compare = (preds == Y.reshape(-1)).astype(np.float32)
  return compare.mean() if averaged else compare

@d2l.add_to_class(d2l.Module) #@save
def get_scratch_params(self):
  params = []
  for attr in dir(self):
    a = getattr(self, attr)
    if isinstance(a, np.ndarray):
      params.append(a)
    if isinstance(a, d2l.Module):
      params.extend(a.get_scratch_params())
  return params

@d2l.add_to_class(d2l.Module) #@save
def parameters(self):
  params = self.collect_params()
  return params if isinstance(params, gluon.parameter.ParameterDict) and len(
    params.keys()) else self.get_scratch_params()

@d2l.add_to_class(Classifier) #@save
@partial(jax.jit, static_argnums=(0, 5))
def accuracy(self, params, X, Y, state, averaged=True):
  """Compute the number of correct predictions."""
  Y_hat = state.apply_fn({'params': params,
              'batch_stats': state.batch_stats}, # BatchNorm Only
              *X)
  Y_hat = Y_hat.reshape((-1, Y_hat.shape[-1]))
  preds = Y_hat.argmax(axis=1).astype(Y.dtype)
  compare = (preds == Y.reshape(-1)).astype(jnp.float32)
  return compare.mean() if averaged else compare

@d2l.add_to_class(Classifier) #@save
def accuracy(self, Y_hat, Y, averaged=True):
  """Compute the number of correct predictions."""
  Y_hat = tf.reshape(Y_hat, (-1, Y_hat.shape[-1]))
  preds = tf.cast(tf.argmax(Y_hat, axis=1), Y.dtype)
  compare = tf.cast(preds == tf.reshape(Y, -1), tf.float32)
  return tf.reduce_mean(compare) if averaged else compare

4.3.3. 概括

分類(lèi)是一個(gè)足夠普遍的問(wèn)題,它保證了它自己的便利功能。分類(lèi)中最重要的是 分類(lèi)器的準(zhǔn)確性。請(qǐng)注意,雖然我們通常主要關(guān)心準(zhǔn)確性,但出于統(tǒng)計(jì)和計(jì)算原因,我們訓(xùn)練分類(lèi)器以?xún)?yōu)化各種其他目標(biāo)。然而,無(wú)論在訓(xùn)練過(guò)程中哪個(gè)損失函數(shù)被最小化,有一個(gè)方便的方法來(lái)根據(jù)經(jīng)驗(yàn)評(píng)估我們的分類(lèi)器的準(zhǔn)確性是有用的。

4.3.4. 練習(xí)

表示為L(zhǎng)v驗(yàn)證損失,讓Lvq是通過(guò)本節(jié)中的損失函數(shù)平均計(jì)算的快速而骯臟的估計(jì)。最后,表示為lvb最后一個(gè)小批量的損失。表達(dá)Lv按照Lvq, lvb,以及樣本和小批量大小。

表明快速而骯臟的估計(jì)Lvq是公正的。也就是說(shuō),表明E[Lv]=E[Lvq]. 為什么你還想使用Lv反而?

給定多類(lèi)分類(lèi)損失,表示為l(y,y′) 估計(jì)的懲罰y′當(dāng)我們看到y(tǒng)并給出一個(gè)概率p(y∣x), 制定最佳選擇規(guī)則y′. 提示:表達(dá)預(yù)期損失,使用 l和p(y∣x).

聲明:本文內(nèi)容及配圖由入駐作者撰寫(xiě)或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問(wèn)題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • pytorch
    +關(guān)注

    關(guān)注

    2

    文章

    813

    瀏覽量

    14932
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評(píng)論

    相關(guān)推薦
    熱點(diǎn)推薦

    Pytorch模型訓(xùn)練實(shí)用PDF教程【中文】

    ?模型部分?還是優(yōu)化器?只有這樣不斷的通過(guò)可視化診斷你的模型,不斷的對(duì)癥下藥,才能訓(xùn)練出一個(gè)較滿(mǎn)意的模型。本教程內(nèi)容及結(jié)構(gòu):本教程內(nèi)容主要為在 PyTorch 中訓(xùn)練一個(gè)
    發(fā)表于 12-21 09:18

    pyhanlp文本分類(lèi)與情感分析

    關(guān)系如下:訓(xùn)練訓(xùn)練指的是,利用給定訓(xùn)練集尋找一個(gè)能描述這種語(yǔ)言現(xiàn)象的模型的過(guò)程。開(kāi)發(fā)者只需調(diào)用train接口即可,但在實(shí)現(xiàn)中,有許多細(xì)節(jié)。分詞目前,本系統(tǒng)中的分詞器接口一共有兩種實(shí)現(xiàn): 但文本分類(lèi)是否
    發(fā)表于 02-20 15:37

    TensorFlow的CNN文本分類(lèi)

    在TensorFlow中實(shí)現(xiàn)CNN進(jìn)行文本分類(lèi)(譯)
    發(fā)表于 10-31 09:27

    pytorch模型轉(zhuǎn)化為onxx模型的步驟有哪些

    首先pytorch模型要先轉(zhuǎn)化為onxx模型,然后從onxx模型轉(zhuǎn)化為rknn模型直接轉(zhuǎn)化會(huì)出現(xiàn)如下問(wèn)題,環(huán)境都是正確的,論壇詢(xún)問(wèn)后也沒(méi)給出
    發(fā)表于 05-09 16:36

    通過(guò)Cortex來(lái)非常方便的部署PyTorch模型

    ?你可以部署一個(gè) AlexNet 模型,使用 PyTorch 和 Cortex 來(lái)標(biāo)記圖像。那語(yǔ)言分類(lèi)器呢,比如 Chrome 用來(lái)檢測(cè)頁(yè)面不是用默認(rèn)語(yǔ)言寫(xiě)的那個(gè)?fastText 是這個(gè)任務(wù)的完美
    發(fā)表于 11-01 15:25

    基于PLSA主題模型的多標(biāo)記文本分類(lèi)_蔣銘初

    基于PLSA主題模型的多標(biāo)記文本分類(lèi)_蔣銘初
    發(fā)表于 01-08 10:40 ?0次下載

    textCNN論文與原理——短文本分類(lèi)

    前言 之前書(shū)寫(xiě)了使用pytorch進(jìn)行短文本分類(lèi),其中的數(shù)據(jù)處理方式比較簡(jiǎn)單粗暴。自然語(yǔ)言處理領(lǐng)域包含很多任務(wù),很多的數(shù)據(jù)向之前那樣處理的話未免有點(diǎn)繁瑣和耗時(shí)。在pytorch中眾所周知的數(shù)據(jù)處理包
    的頭像 發(fā)表于 12-31 10:08 ?3764次閱讀
    textCNN論文與原理——短文<b class='flag-5'>本分類(lèi)</b>

    結(jié)合BERT模型的中文文本分類(lèi)算法

    針對(duì)現(xiàn)有中文短文夲分類(lèi)算法通常存在特征稀疏、用詞不規(guī)范和數(shù)據(jù)海量等問(wèn)題,提出一種基于Transformer的雙向編碼器表示(BERT)的中文短文本分類(lèi)算法,使用BERT預(yù)訓(xùn)練語(yǔ)言模型對(duì)短文本進(jìn)行句子
    發(fā)表于 03-11 16:10 ?6次下載
    結(jié)合BERT<b class='flag-5'>模型</b>的中文文<b class='flag-5'>本分類(lèi)</b>算法

    融合文本分類(lèi)和摘要的多任務(wù)學(xué)習(xí)摘要模型

    文本摘要應(yīng)包含源文本中所有重要信息,傳統(tǒng)基于編碼器-解碼器架構(gòu)的摘要模型生成的摘要準(zhǔn)確性較低。根據(jù)文本分類(lèi)和文本摘要的相關(guān)性,提出一種多任務(wù)學(xué)習(xí)摘要模型。從文本分類(lèi)輔助任務(wù)中學(xué)習(xí)抽象信
    發(fā)表于 04-27 16:18 ?11次下載
    融合文<b class='flag-5'>本分類(lèi)</b>和摘要的多任務(wù)學(xué)習(xí)摘要<b class='flag-5'>模型</b>

    基于不同神經(jīng)網(wǎng)絡(luò)的文本分類(lèi)方法研究對(duì)比

    神經(jīng)網(wǎng)絡(luò)、時(shí)間遞歸神經(jīng)網(wǎng)絡(luò)、結(jié)構(gòu)遞歸神經(jīng)網(wǎng)絡(luò)和預(yù)訓(xùn)練模型等主流方法在文本分類(lèi)中應(yīng)用的發(fā)展歷程比較不同模型基于常用數(shù)據(jù)集的分類(lèi)效果,表明利用人工神經(jīng)網(wǎng)絡(luò)伂構(gòu)自動(dòng)獲取文本特征,可避免繁雜的
    發(fā)表于 05-13 16:34 ?49次下載

    基于LSTM的表示學(xué)習(xí)-文本分類(lèi)模型

    的關(guān)鍵。為了獲得妤的文本表示,提高文本分類(lèi)性能,構(gòu)建了基于LSTM的表示學(xué)習(xí)-文本分類(lèi)模型,其中表示學(xué)習(xí)模型利用語(yǔ)言模型為文
    發(fā)表于 06-15 16:17 ?18次下載

    基于注意力機(jī)制的新聞文本分類(lèi)模型

    基于注意力機(jī)制的新聞文本分類(lèi)模型
    發(fā)表于 06-27 15:32 ?30次下載

    PyTorch本分類(lèi)任務(wù)的基本流程

    本分類(lèi)是NLP領(lǐng)域的較為容易的入門(mén)問(wèn)題,本文記錄文本分類(lèi)任務(wù)的基本流程,大部分操作使用了**torch**和**torchtext**兩個(gè)庫(kù)。 ## 1. 文本數(shù)據(jù)預(yù)處理
    的頭像 發(fā)表于 02-22 14:23 ?2045次閱讀

    PyTorch教程4.3之基本分類(lèi)模型

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程4.3之基本分類(lèi)模型.pdf》資料免費(fèi)下載
    發(fā)表于 06-05 15:43 ?0次下載
    <b class='flag-5'>PyTorch</b>教程<b class='flag-5'>4.3</b>之基<b class='flag-5'>本分類(lèi)</b><b class='flag-5'>模型</b>

    雷達(dá)的基本分類(lèi)方法

    電子發(fā)燒友網(wǎng)站提供《雷達(dá)的基本分類(lèi)方法.pdf》資料免費(fèi)下載
    發(fā)表于 09-11 09:09 ?6次下載
    武义县| 青铜峡市| 德令哈市| 九龙县| 灌云县| 阳高县| 聂拉木县| 尖扎县| 宜良县| 澳门| 四子王旗| 开封市| 晋宁县| 和顺县| 泰和县| 当涂县| 五莲县| 应城市| 卢氏县| 来凤县| 永定县| 临城县| 沙坪坝区| 通州区| 新营市| 泰州市| 淅川县| 龙岩市| 桃园市| 贵港市| 东阿县| 卢湾区| 缙云县| 张家口市| 荔浦县| 中卫市| 安西县| 抚宁县| 清水河县| 吕梁市| 双辽市|