• 从 0 实现 logistic 回归


      0 实现 logistic 回归:

    1)导入所需要的包

    1. import torch  
    2. from IPython import display  
    3. from matplotlib import pyplot as plt  
    4. import numpy as np  
    5. import random  

    2)生成数据集

    1. #生成数据集  
    2. n_data = torch.ones(50, 2)  
    3. x1 = torch.normal(2 * n_data, 1)  
    4. y1 = torch.zeros(50)  
    5. x2 = torch.normal(-2 * n_data, 1)  
    6. y2 = torch.ones(50)  
    7. x = torch.cat((x1, x2), 0).type(torch.FloatTensor)  
    8. y = torch.cat((y1, y2), 0).type(torch.FloatTensor) 

    3)定义迭代器

    1. #定义迭代器  
    2. def data_iter(batch_size, features, labels):  
    3.     num_examples = len(features)  
    4.     indices = list(range(num_examples))  
    5.     random.shuffle(indices)  
    6.     for i in range(0, num_examples, batch_size):  
    7.         j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)])  
    8.         yield features.index_select(0, j), labels.index_select(0, j)  

    4)初始化学习参数

    1. #初始化学习参数  
    2. w = torch.tensor(np.random.normal(0, 0.01, (2, 1)), dtype=torch.float32)  
    3. b = torch.zeros(1, dtype=torch.float32)  
    4. w.requires_grad_(requires_grad=True)  
    5. b.requires_grad_(requires_grad=True)  

    5)定义模型中的函数

    1. #定义线性判别函数  
    2. def linreg(X, w, b):  
    3.     return torch.mm(X, w) + b  
    4. #定义Logistic决策函数  
    5. def logistic(x,w,b):  
    6.     return 1/(1+torch.exp(-1*torch.mm(x,w)+b))  
    7. #定义交叉熵损失函数  
    8. def bce_loss(y_hat,y):  
    9.     return -1 * (y.view(len(y_hat),-1) * torch.log10(y_hat) + (1 - y.view(len(y_hat),-1)) * torch.log10(1 - y_hat))  
    10. #定义平方和损失函数  
    11. def squared_loss(y_hat, y):   
    12.     return (y_hat - y.view(y_hat.size())) ** 2 / 2  
    13. #定义梯度下降优化函数  
    14. def sgd(params, lr, batch_size):  
    15.     for param in params:  
    16.         param.data -= lr * param.grad / batch_size

    6)开始训练并计算每轮损失

    1. #开始训练并计算每轮损失  
    2. lr = 0.03  
    3. num_epochs = 20  
    4. batch_size = 10  
    5. net = logistic  
    6. #loss = torch.nn.BCELoss()  
    7. loss = bce_loss  
    8. for epoch in range(num_epochs):  
    9.     for X, Y in data_iter(batch_size, x, y):  
    10.         l = loss(net(X, w, b), Y).sum()  
    11.         l.backward()  
    12.         sgd([w, b], lr, batch_size)  
    13.         w.grad.data.zero_()  
    14.         b.grad.data.zero_()  
    15.     train_l = loss(net(x, w, b), y)  
    16.     print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))#第一次训练后全部训练集的损失的均值  
    17.     acc_sum = (net(x, w, b).ge(0.5).float().view(-1, 1) == y.view(-1, 1)).float().sum().item()  
    18.     print('accuracy %f' % (acc_sum / y.shape[0]))  

    7)输出优化后的参数

    1. print('\n', w)  
    2. print('\n', b)  
  • 相关阅读:
    JavaScript基础 JavaScript第二天 2. 语句
    flutter 常用组件:列表ListView
    ​力扣解法汇总1413-逐步求和得到正数的最小值
    Springboot整合mybatis
    【scikit-learn基础】--『监督学习』之 支持向量机回归
    如何用WiFi实现无线定位
    基于Dockerfile创建镜像
    《宝塔面板教程1》:宝塔面板安装命令及安装要求
    SpringBoot_整合PageHelper
    Java连接池详解
  • 原文地址:https://blog.csdn.net/ccyyll1/article/details/126020600