2
1

More than 1 year has passed since last update.

Pytorchを理解したい。足し算をするだけのPytorchモデルをつくる。

Last updated at Posted at 2022-02-13

足し算をするPytorchモデルを作ります

baron007.jpeg

Pytorchを理解したい

機械学習モデルの多くはPytorchやTensorFlowで書かれています。
機械学習モデルに触れてみたいけど、Pytorchコードの部分がなんか「むにゃむにゃむにゃ。。。」という感じ。

シンプルなもので理解してみる

小学校の算数も、数を数えたり足し算をすることから始めた気がするので、
とりあえず、入力に1を足すモデルを作って理解してみます。

import torch.nn as nn 

device = "cuda" if torch.cuda.is_available() else "cpu"

class AdditionModel(nn.Module):
    def __init__(self):
        super(AdditionModel, self).__init__()
        self.y = 1

    def forward(self, x):
        x = torch.add(x,self.y)
        return x

model = AdditionModel().to(device)

init でモデルクラス自体を定義し、
forwardで入力を処理します。

モデルに入力してみます。

x = torch.Tensor([1])
x = model(x)
x

tensor([2.])

無事に入力の1とモデルの1が足されて2が出力されました。

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLやARKitを使ったアプリを作っています。
機械学習/AR関連の情報を発信しています。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1