逻辑回归(Logistic Regression)是一种常见的二分类模型,虽然名字中带有“回归”二字,但它实际上用于解决分类问题。本篇文章将指导您如何使用Python来实现一个简单的逻辑回归模型,并通过实际代码进行操作。
在开始之前,请确保您的环境中已经安装了以下库:
numpy
:用于数值计算。pandas
:用于数据处理。sklearn
:机器学习库,其中包含许多常用的算法和工具。matplotlib
和 seaborn
:用于数据可视化。您可以通过运行以下命令来安装这些依赖项:
pip install numpy pandas scikit-learn matplotlib seaborn
我们使用一个简单的二分类问题作为示例,即是否购买某种产品(0或1)。假设我们有一组关于潜在客户的特征,包括年龄、收入等信息。我们将数据存储在一个CSV文件中。
import pandas as pd
# 加载数据
data = pd.read_csv('customer_data.csv')
# 显示前几行数据
print(data.head())
接下来,我们需要将数据分为特征(X)和标签(y),然后对数据进行训练集和测试集的分割。
from sklearn.model_selection import train_test_split
# 选择特征列
features = data[['age', 'income']]
# 定义目标变量
target = data['bought']
# 划分训练集与测试集
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.25, random_state=42)
现在我们来实现逻辑回归模型。这可以通过sklearn.linear_model.LogisticRegression
类完成。
from sklearn.linear_model import LogisticRegression
# 初始化逻辑回归模型
log_reg = LogisticRegression()
# 训练模型
log_reg.fit(X_train, y_train)
接下来,我们将使用测试集来评估我们训练的模型,并计算准确率。
from sklearn.metrics import accuracy_score
# 使用模型进行预测
y_pred = log_reg.predict(X_test)
# 计算准确度
accuracy = accuracy_score(y_test, y_pred)
print(f'模型准确率为: {accuracy:.2f}')
最后,我们将通过绘制决策边界来可视化逻辑回归的结果。
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
# 为绘图准备数据
x_min, x_max = X_test.iloc[:, 0].min() - 1, X_test.iloc[:, 0].max() + 1
y_min, y_max = X_test.iloc[:, 1].min() - 1, X_test.iloc[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, .02),
np.arange(y_min, y_max, .02))
Z = log_reg.predict_proba(np.c_[xx.ravel(), yy.ravel()])
Z = Z[:, 1].reshape(xx.shape)
# 绘制预测结果
plt.contourf(xx, yy, Z, alpha=0.8)
plt.scatter(X_test.iloc[y_test == 0, 0], X_test.iloc[y_test == 0, 1])
plt.scatter(X_test.iloc[y_test == 1, 0], X_test.iloc[y_test == 1, 1])
# 添加标题
plt.title('Decision Boundary of Logistic Regression')
plt.xlabel('Age')
plt.ylabel('Income')
# 显示图形
plt.show()
通过以上步骤,我们成功地使用Python实现了逻辑回归模型,并对一个简单的二分类问题进行了训练和评估。希望这篇指南能够帮助您更好地理解如何在实际项目中应用逻辑回归算法。