<jupyter_start><jupyter_text>Chapter2 PyTorchの基本 3. ニューラルネットワークの定義<jupyter_code># 必要なパッケージのインストール
!pip3 install torch==1.6.0+cu101
!pip3 install torchvision==0.7.0+cu101
!pip3 install numpy==1.18.5
!pip3 install matplotlib==3.2.2
!pip3 install scikit-learn==0.23.1
!pip3 install seaborn==0.11.0
# 必要なパッケージをインポート
import torch
from torch import nn
import torch.nn.functional as F<jupyter_output><empty_output><jupyter_text>3.1. nn.Sequentialを使う方法<jupyter_code># nn.Sequentialで定義
net = torch.nn.Sequential(
    nn.Conv2d(1, 6, 3),  # nn.Conv2d(入力チャネル, 出力チャネル, カーネルサイズ)
    nn.MaxPool2d((2, 2)),  # nn.MaxPool2d(カーネルサイズ)
    nn.ReLU(),
    nn.Conv2d(6, 16, 3),
    nn.MaxPool2d(2),  # nn.MaxPool2d((2,2))と同じ
    nn.ReLU()
)
print(net)<jupyter_output>Sequential(
  (0): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
  (1): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
  (2): ReLU()
  (3): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
  (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (5): ReLU()
)<jupyter_text>3.2. 自作のクラスを使う方法<jupyter_code># 自作のクラスを使って定義
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 3)
        self.conv2 = nn.Conv2d(6, 16, 3)

    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        return x

# ネットワークのロード
net = Net()
print(net)<jupyter_output>Net(
  (conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
)<jupyter_text>3.3. GPUを使う場合<jupyter_code>net = Net().to('cuda')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.18309037900874636, 'fraction_numerical': 0.07463556851311953, 'mean_word_length': 4.739130434782608, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '94214', 'license': 'MIT', 'n_tokens_mistral': 915, 'n_tokens_neox': 849, 'n_words': 137, 'path': 'Google_Colaboratory/Chapter2/Section2-3.ipynb', 'repo_name': 'Hexans/pytorchbook_samplecode', 'size': '1715'}