Logistic回归(Logistic Regression)是一种用于分类问题的统计模型,特别适合用于二分类问题。它通过对输入特征的线性组合进行逻辑函数(sigmoid函数)转换,将输出映射到 ( (0, 1) ) 区间,从而得到预测的概率值。

本文将详细介绍Logistic回归的基本原理,并通过Python实现一个简单的逻辑回归模型。

1. Logistic回归的基本原理

1.1 Sigmoid函数

Logistic回归的核心是Sigmoid函数,它的数学表达式如下:

[
\sigma(z) = \frac{1}{1 + e^{-z}}
]

其中,( z ) 是输入特征的线性组合,( e ) 是自然对数的底数。

1.2 模型构建

逻辑回归的模型可以表示为:

[
h_\theta(x) = \sigma(\theta^T x)
]

其中,( \theta ) 是参数向量,( x ) 是特征向量。

1.3 损失函数

Logistic回归的损失函数使用交叉熵损失,公式如下:

[
J(\theta) = -\frac{1}{m} \sum_{i=1}^{m} [y^{(i)} \log(h_\theta(x^{(i)})) + (1 - y^{(i)}) \log(1 - h_\theta(x^{(i)}))]
]

其中,( m ) 是样本数量,( y^{(i)} ) 是实际标签。

2. Python实现Logistic回归

2.1 导入所需库

我们需要使用以下库:

  • numpy:用于数值计算。
  • pandas:用于数据处理。
  • matplotlib:用于可视化。
  • sklearn:用于数据集和模型评估。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

2.2 数据准备

我们将使用鸢尾花数据集(Iris dataset)中的两个特征(花萼长度和花萼宽度)来进行二分类。为了简化模型,我们将只使用其中的两种花(Setosa和Versicolor)。

# 加载数据集
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data[:100, :2]  # 只取前100个样本和前两个特征
y = iris.target[:100]     # 只取前100个样本的目标值

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

2.3 定义Logistic回归类

class LogisticRegression:
    def __init__(self, learning_rate=0.01, num_iterations=1000):
        self.learning_rate = learning_rate
        self.num_iterations = num_iterations
        self.theta = None

    def sigmoid(self, z):
        return 1 / (1 + np.exp(-z))

    def fit(self, X, y):
        m, n = X.shape
        self.theta = np.zeros(n)

        for _ in range(self.num_iterations):
            z = np.dot(X, self.theta)
            h = self.sigmoid(z)
            gradient = np.dot(X.T, (h - y)) / m
            self.theta -= self.learning_rate * gradient

    def predict(self, X):
        z = np.dot(X, self.theta)
        h = self.sigmoid(z)
        return [1 if i >= 0.5 else 0 for i in h]

2.4 训练模型

我们使用训练集训练逻辑回归模型。

# 训练模型
model = LogisticRegression(learning_rate=0.1, num_iterations=1000)
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估模型
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)

print("准确率:", accuracy)
print("混淆矩阵:\n", conf_matrix)

2.5 可视化结果

我们可以使用Matplotlib可视化训练集和测试集的结果。

# 可视化结果
plt.scatter(X_train[y_train == 0][:, 0], X_train[y_train == 0][:, 1], color='blue', label='Setosa')
plt.scatter(X_train[y_train == 1][:, 0], X_train[y_train == 1][:, 1], color='red', label='Versicolor')

# 绘制决策边界
x_values = np.linspace(4, 8, 100)
y_values = -(model.theta[0] * x_values) / model.theta[1]
plt.plot(x_values, y_values, color='green')

plt.xlabel('花萼长度')
plt.ylabel('花萼宽度')
plt.title('Logistic回归决策边界')
plt.legend()
plt.show()

3. 总结

Logistic回归是一种简单有效的分类模型,尤其适用于二分类问题。通过Python的实现,我们可以看到如何构建一个逻辑回归模型并进行训练和预测。尽管逻辑回归在处理复杂数据时可能表现不佳,但它是理解更复杂模型的基础。

在实际应用中,逻辑回归常用于医疗诊断、金融欺诈检测等领域。随着机器学习的进步,逻辑回归仍然是一个不可忽视的工具。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐