动手实现Logistic回归

本文记录动手实现Logistic回归,本人刚刚接触深度学习,有错误的地方恳请各位大佬指正。在实现的过程中参考了下面两篇的思路:
Pytorch实验一:从零实现Logistic回归和Softmax回归
pytorch实现 logistic 回归

从0实现 logistic 回归

import torch
import matplotlib.pyplot as plt 
import torch.nn as nn
import numpy as np
import random

生成数据

随机生成实验所需要的二分类数据集 𝑥1 和 𝑥2 ,分别对应的标签 𝑦1 和 𝑦2
torch.normal返回一个张量,包含从给定参数means,std的离散正态分布中抽取随机数。 均值means是一个张量,包含每个输出元素相关的正态分布的均值。

n_data = torch.ones(50, 2) # 数据的基本形态
x1 = torch.normal(2 * n_data, 1) # shape=(50, 2)
y1 = torch.zeros(50) # 类型0 shape=(50, 1)
x2 = torch.normal(-2 * n_data, 1) # shape=(50, 2)
y2 = torch.ones(50) # 类型1 shape=(50, 1)
# 注意 x, y 数据的数据形式一定要像下面一样 (torch.cat 是合并数据),这样就构建出来一个分类特征明显的数据集
features = torch.cat((x1, x2), 0).type(torch.FloatTensor)
label = torch.cat((y1, y2), 0).type(torch.FloatTensor)

◼ 使用matplotlib将所构造的数据可视化

#x.data.numpy()[:, 0], x.data.numpy()[:, 1]表示输入x的两列
plt.scatter(features.data.numpy()[:, 0], features.data.numpy()[:, 1], c=label.data.numpy(), s=100, lw=0, 
cmap='RdYlGn')
plt.show()

在这里插入图片描述

读取数据

在模型训练的时候,需要遍历数据集并不断读取小批量的数据样本。这里本实验定义
一个函数 𝐝𝐚𝐭𝐚_𝐢𝐭𝐞𝐫() 它每次返回 𝒃𝒂𝒕𝒄𝒉_𝒔𝒊𝒛𝒆 (批量大小)个随机样本的特征和标签。

def data_iter(batch_size, features, label):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices) # 样本的读取顺序是随机的
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # 最后一次可能不足一个batch
        yield features.index_select(0, j), label.index_select(0, j)

参数初始化

注意这里,w为大小为2的向量,分别对应x1和x2的系数,b的初始值为0,为标量
w采用非标准的整体分布,可以增加初始预测分布的不确定性,否则的话,可能第一把预测的概率就是100%


                
### 从零实现 Logistic 回归模型并进行实验结果分析 Logistic 回归是一种广泛用于二分类问题的统计模型。其核心思想是通过 **Sigmoid 函数** 将线性回归的输出映射到 [0, 1] 区间,从而表示样本属于某一类别的概率。模型的输出公式如下: $$ P(y=1|x) = \sigma(w^T x + b) = \frac{1}{1 + e^{-(w^T x + b)}} $$ 其中,$ \sigma $ 是 Sigmoid 函数,$ w $ 是权重向量,$ b $ 是偏置项,$ x $ 是输入特征向量。 #### 1. 模型实现 以下是一个从零实现 Logistic 回归模型的 Python 示例: ```python import numpy as np class LogisticRegression: def __init__(self, learning_rate=0.01, n_iterations=1000): self.learning_rate = learning_rate self.n_iterations = n_iterations self.weights = None self.bias = None def fit(self, X, y): n_samples, n_features = X.shape self.weights = np.zeros(n_features) self.bias = 0 for _ in range(self.n_iterations): linear_model = np.dot(X, self.weights) + self.bias y_pred = self._sigmoid(linear_model) # 计算梯度 dw = (1 / n_samples) * np.dot(X.T, (y_pred - y)) db = (1 / n_samples) * np.sum(y_pred - y) # 更新参数 self.weights -= self.learning_rate * dw self.bias -= self.learning_rate * db def predict(self, X): linear_model = np.dot(X, self.weights) + self.bias y_pred_prob = self._sigmoid(linear_model) y_pred = (y_pred_prob >= 0.5).astype(int) return y_pred def _sigmoid(self, z): return 1 / (1 + np.exp(-z)) ``` #### 2. 实验设置 为了验证模型的有效性,可以使用 `scikit-learn` 提供的乳腺癌数据集进行实验: ```python from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score # 加载数据 data = load_breast_cancer() X, y = data.data, data.target # 标准化 scaler = StandardScaler() X = scaler.fit_transform(X) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 训练模型 model = LogisticRegression(learning_rate=0.1, n_iterations=3000) model.fit(X_train, y_train) # 预测与评估 y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy:.4f}") ``` #### 3. 实验结果分析 - **准确率**:在测试集上,模型的准确率通常能达到 90% 以上,表明模型具有良好的分类能力。 - **收敛性**:随着迭代次数的增加,损失函数逐渐减小并趋于稳定。 - **学习率影响**:学习率过大可能导致模型无法收敛,而学习率过小则会增加训练时间。 - **特征标准化**:由于 Logistic 回归对特征尺度敏感,标准化可以显著提升模型性能。 #### 4. 模型优化方向 - **正则化**:引入 L1 或 L2 正则化可以防止过拟合。 - **交叉验证**:使用交叉验证选择最优的超参数(如学习率、迭代次数)。 - **特征工程**:通过特征选择或降维技术(如 PCA)提升模型泛化能力。 ---
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江鸟阁长

你的支持是我更新的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值