第3章回帰のための線形ニューラルネットワーク
3.2. Object-Oriented Design for Implementation3.2 実装のためのオブジェクト指向設計
In our introduction to linear regression, we walked through various components including the data, the model, the loss function, and the optimization algorithm. Indeed, linear regression is one of the simplest machine learning models. Training it, however, uses many of the same components that other models in this book require. Therefore, before diving into the implementation details it is worth designing some of the APIs that we use throughout. Treating components in deep learning as objects, we can start by defining classes for these objects and their interactions. This object-oriented design for implementation will greatly streamline the presentation and you might even want to use it in your projects.
英語のヒント
線形回帰の紹介では、データ、モデル、損失関数、最適化アルゴリズムなど、さまざまな構成要素を順に見てきた。確かに線形回帰は最も単純な機械学習モデルの一つである。しかし、その訓練には、この本のほかのモデルが必要とするのと同じ構成要素の多くを使う。したがって、実装の細部に飛び込む前に、本全体を通じて使うAPIのいくつかを設計しておく価値がある。深層学習の構成要素をオブジェクトとして扱えば、それらのオブジェクトと相互作用のためのクラスを定義することから始められる。この実装のためのオブジェクト指向設計は、説明を大いにすっきりさせ、あなたも自分のプロジェクトで使いたくなるかもしれない。
Inspired by open-source libraries such as PyTorch Lightning, at a high level we wish to have three classes: (i)
Module contains models, losses, and optimization methods; (ii) DataModule provides data loaders for training and validation; (iii) both classes are combined using the Trainer class, which allows us to train models on a variety of hardware platforms. Most code in this book adapts Module and DataModule. We will touch upon the Trainer class only when we discuss GPUs, CPUs, parallel training, and optimization algorithms.英語のヒント
PyTorch Lightningのようなオープンソースのライブラリに着想を得て、大まかには三つのクラスをもちたい。(i)
Moduleは、モデル、損失、最適化の手法を含む。(ii)DataModuleは、訓練と検証のためのデータローダーを提供する。(iii)両方のクラスはTrainerクラスを使って組み合わされ、さまざまなハードウェアプラットフォームでモデルを訓練できるようにする。この本のコードのほとんどは、ModuleとDataModuleを適合させて使う。Trainerクラスに触れるのは、GPU、CPU、並列訓練、最適化アルゴリズムを論じるときだけである。import time
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l