PyTorch 自定义model简单示例

PyTorch 自定义model简单示例

环境:python3.8
Pytorch介绍
Pytorch中文文档

import torch
import numpy as np

def test():
    x_data = torch.Tensor([[2,2,1],[1,1,2],[-1,0,1],[-1,1,-1]])
    y_data = torch.Tensor([[5,1],[4,2],[0,0],[-1,-3]])
    # 对应关系为x [[1,1],
    #            [1,-1]
    #            [1,1]] = y

    class MyModule(torch.nn.Module):
        def __init__(self):
            # 第一句话,调用父类的构造函数
            super(MyModule, self).__init__()
            # 对应x和y的特征数量
            self.mylayer = MyLayer(len(x_data.data[0]),len(y_data.data[0]))

        def forward(self, x):
            x = self.mylayer(x)
            return x

    # y = w1*x1 + w2*x2 + w3*x3 + b
    class MyLayer(torch.nn.Module):
        def __init__(self, in_features, out_features, bias=True, weight=True):
            # 和自定义模型一样,第一句话就是调用父类的构造函数
            super(MyLayer, self).__init__()
            self.in_features = in_features
            self.out_features = out_features
            # 由于weights是可以训练的,所以使用Parameter来定义
            self.weight = torch.nn.Parameter(torch.Tensor(in_features, out_features))
            self.bias = torch.nn.Parameter(torch.Tensor(in_features))

        def forward(self, x):
            y = torch.matmul(x, self.weight)
            # 求当前均值
            avg = 0
            for i in self.bias.data:
                avg += i
            avg /= len(self.bias.data)
            # 填充到所有
            bias = torch.DoubleTensor(len(y.data),len(y.data[0])).fill_(avg)
            y += bias
            return y

    model = MyModule()
    # 均方误差损失
    criterion = torch.nn.MSELoss(reduction='sum')
    optimizer = torch.optim.SGD(model.parameters(), lr=0.001)

    # 训练
    print("loop -------------")
    train_time = 1000
    pre_loss = 0
    for epoch in range(train_time):
        y_pred = model(x_data)
        # 误差越来越小
        loss = criterion(y_pred, y_data)
        if np.isinf(loss.item()):
            print("loss is inf")
            break

        # 设置训练中断
        if abs(pre_loss-loss) < 1e-5:
            break

        print(epoch, loss.item())
        pre_loss = loss
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    print('w = ', model.mylayer.weight)
    print('b = ', model.mylayer.bias)
    x_test = torch.Tensor([[3.0, 4.0, 5.0]])
    y_test = model(x_test)
    print('y_pred = ', y_test.data[0])

if __name__ == "__main__":
    test()

结果图:
预测结果
调整训练次数10000和中断条件1e-10后可以达到:
预测结果2

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch自定义网络模型结构图可以通过使用PyTorch内置的`torchsummary`模块来生成。这个模块可以帮助我们快速地展示模型的参数数量、每一层的输出形状等重要信息。 以下是一个简单示例,展示了如何使用`torchsummary`模块来生成自定义网络模型的结构图: ``` python import torch import torch.nn as nn from torchsummary import summary class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1) self.pool = nn.MaxPool2d(kernel_size=2, stride=2) self.fc1 = nn.Linear(64 * 8 * 8, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = nn.functional.relu(x) x = self.pool(x) x = self.conv2(x) x = nn.functional.relu(x) x = self.pool(x) x = x.view(-1, 64 * 8 * 8) x = self.fc1(x) x = nn.functional.relu(x) x = self.fc2(x) return x model = MyModel() summary(model, input_size=(3, 32, 32)) ``` 运行以上代码,就可以得到如下的输出: ``` ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 32, 32, 32] 896 MaxPool2d-2 [-1, 32, 16, 16] 0 Conv2d-3 [-1, 64, 16, 16] 18,496 MaxPool2d-4 [-1, 64, 8, 8] 0 Linear-5 [-1, 128] 524,416 Linear-6 [-1, 10] 1,290 ================================================================ Total params: 545,098 Trainable params: 545,098 Non-trainable params: 0 ---------------------------------------------------------------- Input size (MB): 0.01 Forward/backward pass size (MB): 0.75 Params size (MB): 2.08 Estimated Total Size (MB): 2.85 ---------------------------------------------------------------- ``` 可以看到,`summary`函数生成了一个包含每一层输出形状、参数数量等信息的表格,以及估计的模型大小。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值