Pytorch-implementing-first-neural-network

提供:Dev Guides
移動先:案内検索

PyTorch-最初のニューラルネットワークの実装

PyTorchには、ニューラルネットワークを作成および実装する特別な機能が含まれています。 この章では、1つの隠れ層が単一の出力ユニットを開発する単純なニューラルネットワークを作成します。

私たちは次の手順を使用して、PyTorchを使用して最初のニューラルネットワークを実装します-

ステップ1

まず、以下のコマンドを使用してPyTorchライブラリをインポートする必要があります-

import torch
import torch.nn as nn

ステップ2

以下に示すように、すべてのレイヤーとバッチサイズを定義して、ニューラルネットワークの実行を開始します-

# Defining input size, hidden layer size, output size and batch size respectively
n_in, n_h, n_out, batch_size = 10, 5, 1, 10

ステップ3

ニューラルネットワークには、それぞれの出力データを取得するための入力データの組み合わせが含まれているため、以下に示すのと同じ手順に従います-

# Create dummy input and target tensors (data)
x = torch.randn(batch_size, n_in)
y = torch.tensor([[Step 4

Create a sequential model with the help of in-built functions. Using the below lines of code, create a sequential model −

[source,prettyprint,notranslate]

#モデルの作成model = nn.Sequential(nn.Linear(n_in、n_h)、nn.ReLU()、nn.Linear(n_h、n_out)、nn.Sigmoid())

=== Step 5

Construct the loss function with the help of Gradient Descent optimizer as shown below −

[source,prettyprint,notranslate]

損失関数の条件を構築する= torch.nn.MSELoss()#オプティマイザーを構築する(この場合は確率的勾配降下)オプティマイザー= torch.optim.SGD(model.parameters()、lr = 0.01)

=== Step 6

Implement the gradient descent model with the iterating loop with the given lines of code −

[source,prettyprint,notranslate]

#range(50)のエポックの勾配降下:#フォワードパス:モデルにxを渡すことで予測yを計算y_pred = model(x)

#損失損失を計算して印刷する= criteria(y_pred、y)print( 'epoch:'、epoch、 'loss:'、loss.item())

#勾配をゼロにし、後方パスを実行し、重みを更新します。 optimizer.zero_grad()

#後方パス(backpropagation)loss.backward()を実行します

#パラメーターoptimizer.step()を更新します

=== Step 7

The output generated is as follows −

[source,prettyprint,notranslate]

エポック:0損失:0.2545787990093231エポック:1損失:0.2545052170753479エポック:2損失:0.254431813955307エポック:3損失:0.25435858964920044エポック:4損失:0.2542854845523834エポック:5損失:0.25421255826950073エポック:6損失:0.25413978099823エポック:損失8損失:0.2539947032928467エポック:9損失:0.25392240285873413エポック:10損失:0.25385022163391113エポック:11損失:0.25377824902534485エポック:12損失:0.2537063956260681エポック:13損失:0.2536346912384033エポック:14損失:0.25356316566467285 epoch:917損失:エポック:0.25342053174972534エポック:17損失:0.2533493936061859エポック:18損失:0.2532784342765808エポック:19損失:0.25320762395858765エポック:20損失:0.2531369626522064エポック:21損失:0.25306645035743713エポック:22損失:0.252996027469635 epエポック:25損失:0.25278574228286743エポック:26損失:0.25271597504615784エポック:27損失:0.25264623761177063エポック:28損失:0.2 5257670879364014エポック:29損失:0.2525072991847992エポック:30損失:0.2524380087852478エポック:31損失:0.2523689270019531エポック:32損失:0.25229987502098083エポック:33損失:0.25223103165626526エポック:34損失:0.25216227769851685エポック:0.25202 :37損失:0.2519568204879761エポック:38損失:0.251888632774353エポック:39損失:0.25182053446769714エポック:40損失:0.2517525553703308エポック:41損失:0.2516847252845764エポック:42損失:0.2516169846057892エポック:43損失:0.2515493929386283エポック:45損失損失:0.25141456723213196エポック:46損失:0.2513473629951477エポック:47損失:0.2512802183628082エポック:48損失:0.2512132525444031エポック:49損失:0.2511464059352875