从 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)  
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要从零开始实现逻辑回归,你需要以下步骤: 1. 准备数据集:将数据集划分为特征矩阵 X 和目标变量向量 y。 2. 初始化参数:初始化权重向量 w 和偏置 b。 3. 定义sigmoid函数:sigmoid函数将实数映射到0和1之间的概率值。 4. 定义损失函数:使用对数似然损失函数来度量预测概率与实际标签之间的差异。 5. 计算梯度:通过计算损失函数对参数 w 和 b 的偏导数来得到梯度。 6. 更新参数:使用梯度下降法来更新参数,减小损失函数的值。 7. 训练模型:使用训练集进行多次迭代,不断更新参数以优化模型。 8. 预测:使用训练好的参数进行预测。 下面是一个简单的示例代码来实现逻辑回归: ```python import numpy as np # 定义sigmoid函数 def sigmoid(x): return 1 / (1 + np.exp(-x)) # 定义损失函数 def loss_function(y_pred, y_true): return -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred)) # 初始化参数 def initialize_parameters(dim): w = np.zeros((dim, 1)) b = 0 return w, b # 计算梯度 def compute_gradient(X, y, y_pred): m = X.shape[1] dw = np.dot(X, (y_pred - y).T) / m db = np.mean(y_pred - y) return dw, db # 更新参数 def update_parameters(w, b, dw, db, learning_rate): w = w - learning_rate * dw b = b - learning_rate * db return w, b # 训练模型 def train(X, y, num_iterations, learning_rate): w, b = initialize_parameters(X.shape[0]) for i in range(num_iterations): # 前向传播 y_pred = sigmoid(np.dot(w.T, X) + b) # 计算损失 loss = loss_function(y_pred, y) # 计算梯度 dw, db = compute_gradient(X, y, y_pred) # 更新参数 w, b = update_parameters(w, b, dw, db, learning_rate) # 每100次迭代打印一次损失 if i % 100 == 0: print(f"Loss after iteration {i}: {loss}") return w, b # 预测 def predict(w, b, X): y_pred = sigmoid(np.dot(w.T, X) + b) y_pred = np.round(y_pred) return y_pred # 示例数据 X = np.array([[1, 2, 3], [4, 5, 6]]) y = np.array([[0, 1, 1]]) # 训练模型 w, b = train(X, y, num_iterations=1000, learning_rate=0.01) # 预测 y_pred = predict(w, b, X) print("Predictions:", y_pred) ``` 请注意,这只是一个简单的实现,实际的逻辑回归模型可能会有更多的步骤和复杂性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值