从 0 实现 logistic 回归

这篇博客介绍了如何使用PyTorch从零开始实现Logistic回归。首先,通过生成数据集,然后定义迭代器,接着初始化学习参数。接着,定义了线性判别、Logistic决策、交叉熵损失和梯度下降等关键函数。通过训练模型并计算每轮损失,逐步优化参数。最后输出了训练后的参数,并展示了训练过程中的损失与准确率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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)  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值