Python  - PyTorch - Training a Net                                     Home : www.sharetechnote.com

 

 

 

 

PyTorch - Training a Net

 

 

    import torch

    from torch import nn, optim

    import matplotlib.pyplot as plt

    import numpy as np

     

    class LinearRegression_i1_o1(nn.Module):

        def __init__(self):

            super().__init__()

            self.linear = nn.Linear(1,1)

     

        def forward(self,x):

            o = self.linear(x)

            return o

     

    x_data = torch.Tensor([[1.0],[2.0],[3.0]]);

    y_data = torch.Tensor([[3.0],[5.0],[7.0]]);

     

    net = LinearRegression_i1_o1()

     

    criterion = nn.MSELoss(reduction='sum')

    optimizer = optim.SGD(net.parameters(), lr = 0.01)

     

    l = [];

    for epoch in range(100):

        y = net(x_data);

        loss = criterion(y,y_data);

        optimizer.zero_grad();

        loss.backward();

        optimizer.step();

        print('epoch = ',epoch, ',' , 'loss = ',loss.item());

        l.append(loss.item());

 

    epoch =  0 , loss =  107.59871673583984

    epoch =  1 , loss =  48.02556610107422

    epoch =  2 , loss =  21.50349235534668

    epoch =  3 , loss =  9.694835662841797

    ....

    epoch =  17 , loss =  0.18192727863788605

    epoch =  18 , loss =  0.17925120890140533

    epoch =  19 , loss =  0.17664769291877747

    .....

    epoch =  42 , loss =  0.12660643458366394

    epoch =  43 , loss =  0.12478689104318619

    epoch =  44 , loss =  0.12299361079931259

    .....

    epoch =  97 , loss =  0.057106103748083115

    epoch =  98 , loss =  0.056285560131073

    epoch =  99 , loss =  0.05547652766108513