欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lesson-05-Logistic-Regression

程序员文章站 2022-03-17 14:15:03
...
import torch as tt
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
tt.manual_seed(10)
<torch._C.Generator at 0x6858f10>

机器学习模型训练步骤

迭代训练

  • 数据
  • 模型
  • loss_fn
  • optimizer
# step 1/5 生成数据
sample_nums = 100
mean_value = 1.7
bias = 1
n_data = tt.ones(sample_nums, 2)
x0 = tt.normal(mean_value * n_data, 1) + bias
# class 0 data shape(100,2)
y0 = tt.zeros(sample_nums)                         
# 类别0 标签 shape=(100, 1)
x1 = tt.normal(-mean_value * n_data, 1) + bias     
# 类别1 数据 shape=(100, 2)
y1 = tt.ones(sample_nums)                          
# 类别1 标签 shape=(100, 1)

train_x = tt.cat((x0, x1), 0)
train_y = tt.cat((y0, y1), 0)
# step 2/5 选择模型
class LR(nn.Module):
    def __init__(self):
        super(LR, self).__init__()
        self.features = nn.Linear(2,1)# y = f(wx + b)
        self.sig = nn.Sigmoid()# f(x) = 1/(1+exp(-x))
    def forward(self, x):
        x = self.features(x)
        x = self.sig(x)
        return x
    
lr_net = LR()
# step 3/5 选择损失函数
loss_fn = nn.BCELoss()
# step 4/5 选择优化器
lr = 0.01 # learning rate
optimizer = tt.optim.SGD(lr_net.parameters(), lr = lr, momentum = 0.9)
# step 5/5 模型训练
epoch = 1000

for iteration in range(epoch):
    # forward
    y_pred = lr_net(train_x)
    
    # calculate loss
    loss = loss_fn(y_pred.squeeze(), train_y)
    
    # backward
    loss.backward()
    
    # update parameters
    optimizer.step()
    
    # clear gradient
    optimizer.zero_grad()
    
    # plot
    
    if iteration % 50 ==0:
        
        mask = y_pred.ge(0.5).float().squeeze()
        # classify with threshold == 0.5
        correct = (mask == train_y).sum()
        # calculate correct number
        acc = correct.item() / train_y.size(0)
        # calculate accuracy
        
        plt.scatter(x0.data.numpy()[:, 0], x0.data.numpy()[:, 1], c='r', label='class 0')
        plt.scatter(x1.data.numpy()[:, 0], x1.data.numpy()[:, 1], c='b', label='class 1')        
        

        w0, w1 = lr_net.features.weight[0]
        w0, w1 = float(w0.item()), float(w1.item())
        plot_b = float(lr_net.features.bias[0].item())
        plot_x = np.arange(-6, 6, 0.1)
        plot_y = (-w0 * plot_x - plot_b) / w1
        
        plt.xlim(-5, 7)
        plt.ylim(-7, 7)
        plt.plot(plot_x, plot_y)

        plt.text(-5, 5, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
        plt.title("Iteration: {}\nw0:{:.2f} w1:{:.2f} b: {:.2f} accuracy:{:.2%}".format(iteration, w0, w1, plot_b, acc))
        plt.legend()

        plt.show()
        plt.pause(0.5)

        if acc > 0.99:
            break

lesson-05-Logistic-Regression
lesson-05-Logistic-Regression

相关标签: pytorch