1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pytorchで書かれたモデルのパラメータ数を数える

Last updated at Posted at 2023-03-15

パラメータの数を数える

OpenNMTでtrain.pyしたときにパラメータ数が出てきたのがなんかカッコよかったので自分もやってみる

import torch.nn as nn
import torch.nn.functional as F

# テキトーなモデルを作る
class SampleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
        self.fc1 = nn.Linear(16 * 8 * 8, 100)
        self.fc2 = nn.Linear(100, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2)
        x = x.view(-1, 16 * 8 * 8)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# インスタンス作る
model = SampleModel()

# パラメータ数を数える関数
def count_parameters(model):
    return sum(param.numel() for param in model.parameters() if param.requires_grad)

# 表示
print(f"Total trainable parameters: {count_parameters(model)}")

これで学習可能なパラメータ(requires_grad=Trueになっているパラメータ)を数えてくれます。

ちな実行結果は以下

Total trainable parameters: 103958
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?