基于Python的Logistic回归模型

本文介绍了Python中的Logistic回归模型的原理,包括Logistic函数和最大似然函数估计。通过使用Sklearn库,作者展示了如何划分数据集、进行特征标准化以及训练和评估模型。尽管测试集的R方值表明模型效果一般,但提出了优化方法,如调整数据划分和尝试不同模型。最后,文章提供了散点图来可视化预测结果。
本文是基于Python的logistic回归模型的建模和分析

一、Logistic原理

1.logistic函数

Logistic函数是讲数据映射到0-1区间的概率值,数据中包含分类的数据(即不连续的数据,如:0,1数据等),表达式如下:

其中,是数据变量,是变量的系数。

2.最大似然函数估计

我们将上式中变量部分定义为,这就是转换为一个线性方程,然后我们就可以通过极大似然估计法对变量系数进行估计和计算,可参考

一元线性回归模型(保姆级)_数据小师弟的博客-CSDN博客

二、代码例子

  1. 数据集

数据集如下图,我只截取了部分的数据展示:

2.代码实现

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

X = df.iloc[:, [1,2,3]].values
y = df.iloc[:, 0].values
#划分训练集和测试集,训练集:测试集=8:2
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)
#对数据进行特征提取,进行数据标准化
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)

#Logistic拟合模型
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, y_train)
#打印参数结果
print("Logistic参数结果:",classifier.intercept_,classifier.coef_)

y_pred = classifier.predict(X_test)
#计算R方
cm = accuracy_score(y_test, y_pred)

print("测试集的R方:",cm)

结果如下:

第一个系数是,剩下三个参数是变量x1,x2,x3的系数

Logistic参数结果: [-0.21588339] [[-0.80772308 -0.15407737 -0.01698285]]

测试集的R方: 0.4444444444444444

从R方的结果来看,效果并不是很好,我们可以从数据记得划分、改变模型等方法进行优化提高R方数值。

然后画图观察数据的情况,如下:

#设置图表中允许显示中文
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] =False #减号unicode编码

fig, ax = plt.subplots(figsize=(10, 6))
plt.title("测试y与预测y散点图")
plt.xlabel("点数")#x轴标签
plt.ylabel("预测y与测试y")#y轴标签
ax.plot(y_test, 'o',c = '#00CED1', label='y_test',markersize=8)
ax.plot(y_pred,'o', c = '#DC143C',label='y_pred',markersize=4)
plt.legend()
print("测试结果:",y_test)
print("预测结果:",y_pred)

结果如下:

测试结果: [0 0 0 1 0 1 1 1 1 1 0 1 0 0]

预测结果: [1 0 1 0 1 1 1 1 0 1 1 0 0 0]

三、参考资料

sklearn文档
Logistic公式推导

### Python实现Logistic回归模型教程 #### 1. 模型简介 Logistic回归是一种用于解决二分类问题的有效工具。它不仅能够给出类别预测结果,还能提供样本属于某一类别的概率估计[^2]。 #### 2. 数学基础 对于给定输入向量\( \mathbf{x} \),Logistic回归计算线性组合 \( z=\beta_0+\sum_{i=1}^{n}\beta_ix_i\) 的值,并将其传递给Sigmoid函数\[ P(y=1|\mathbf{x})=\frac{1}{1+e^{-z}}\] 。当输出大于等于0.5时,则认为该实例应归属于正类;反之则归属负类[^5]。 #### 3. 参数优化 采用梯度下降法最小化损失函数以获得最优权重参数。随着迭代次数增加,成本函数逐渐趋于稳定,表明模型已经找到了较好的拟合效果[^4]。 #### 4. 编码实践 下面展示了一个完整的Python代码片段,展示了如何创建一个简单的逻辑回归分类器: ```python import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report # 创建模拟数据集 X, y = make_classification(n_samples=1000, n_features=20, n_informative=2, n_redundant=10, random_state=42) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=.25, random_state=42) def sigmoid(z): """定义sigmoid激活函数""" return 1 / (1 + np.exp(-z)) class CustomLogisticRegression: def __init__(self, learning_rate=0.01, num_iterations=1000): self.learning_rate = learning_rate self.num_iterations = num_iterations def fit(self, X, y): m, n = X.shape # 初始化参数 w = np.zeros((n, 1)) b = 0 costs = [] for i in range(self.num_iterations): A = sigmoid(np.dot(X, w) + b) cost = (-1/m)*np.sum(y*np.log(A)+(1-y)*np.log(1-A)) dw = (1/m)*np.dot(X.T,(A - y)) db = (1/m)*np.sum(A - y) w -= self.learning_rate * dw b -= self.learning_rate * db if i % 100 == 0: costs.append(cost) self.w = w self.b = b def predict_proba(self, X): proba = sigmoid(np.dot(X, self.w)+self.b) return proba def predict(self, X, threshold=0.5): predictions = self.predict_proba(X)>threshold return predictions.astype(int).ravel() model = CustomLogisticRegression() model.fit(X_train.reshape(-1, 1), y_train.reshape(-1, 1)) y_pred = model.predict(X_test) print(f'Accuracy Score: {accuracy_score(y_test,y_pred)}') print(classification_report(y_test, y_pred)) ``` 此段程序首先导入必要的库文件,接着生成一组随机分布的数据作为实验素材。随后定义了自定义版本的`CustomLogisticRegression` 类来进行模型训练与预测操作。最后利用准确率评分及分类报告评估性能表现[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DL11007

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值