问题背景
Logistic回归算法是一种常用的机器学习算法,用于解决分类问题。它基于逻辑回归模型,通过对数据进行拟合来预测输入样本的类别。本文将详细介绍Logistic回归算法的原理、公式推导、计算步骤和Python代码示例。
算法原理
Logistic回归基于逻辑回归模型,该模型假设特征与类别之间存在一个线性关系,并使用sigmoid函数将线性输出映射到[0,1]之间。
更具体地说,给定输入特征向量$x$,Logistic回归模型的线性输出$z$可以表示为:
$$z = w_0 + w_1x_1 + w_2x_2 + … + w_nx_n$$
其中,$w$是模型的权重向量,$n$是特征的数量。将线性输出$z$通过sigmoid函数进行映射,得到属于类别1的概率$y$:
$$y = \frac{1}{1 + e^{-z}}$$
公式推导
为了推导出Logistic回归的代价函数和梯度下降的更新规则,我们需要定义代价函数和假设函数。
假设函数$h_\theta(x)$表示给定参数$\theta$时,输入特征$x$属于类别1的概率。它通过将线性输出$z$通过sigmoid函数进行映射得到:
$$h_\theta(x) = \frac{1}{1 + e^{-\theta^Tx}}$$
为了得到参数$\theta$的最优值,我们需要定义一个代价函数$J(\theta)$来衡量模型预测的偏差。常用的代价函数是交叉熵损失函数(cross-entropy loss)。
给定训练集$D$,包含$m$个样本,每个样本有输入特征$x$和真实类别$y$。给定假设函数$h_\theta(x)$,交叉熵损失函数可以定义为:
$$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)}))]$$
通过最小化代价函数$J(\theta)$,我们可以找到最优参数$\theta$。梯度下降是一种常用的优化算法,用于更新参数$\theta$,以减小代价函数$J(\theta)$。
计算步骤
- 初始化参数$\theta$为零向量或随机值。
- 计算假设函数$h_\theta(x)$的预测值。
- 计算代价函数$J(\theta)$的值。
- 计算代价函数$J(\theta)$对参数$\theta$的偏导数。
- 使用梯度下降更新参数$\theta$。
- 重复步骤2-5,直到收敛或达到迭代次数。
复杂Python代码示例 – 手写数字识别
本示例使用scikit-learn库的手写数字数据集,展示了如何使用Logistic回归算法实现手写数字识别。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 加载手写数字数据集
digits = load_digits()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=42)
# 特征归一化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 定义假设函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 初始化参数
theta = np.zeros(X_train.shape[1])
# 定义代价函数
def cost_func(X, y, theta):
m = len(y)
h = sigmoid(np.dot(X, theta))
cost = -np.sum(y artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls np.log(h) + (1 - y) artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls np.log(1 - h)) / m
return cost
# 定义梯度下降函数
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
costs = []
for i in range(num_iters):
h = sigmoid(np.dot(X, theta))
grad = np.dot(X.T, (h - y)) / m
theta -= alpha artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls grad
cost = cost_func(X, y, theta)
costs.append(cost)
return theta, costs
# 运行梯度下降算法
num_iters = 1000
alpha = 0.01
theta, costs = gradient_descent(X_train, y_train, theta, alpha, num_iters)
# 绘制代价函数的学习曲线
plt.plot(range(1, len(costs) + 1), costs)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.title('Cost Function - Learning Curve')
plt.show()
# 预测测试集
y_pred = sigmoid(np.dot(X_test, theta))
y_pred = np.where(y_pred >= 0.5, 1, 0)
# 计算准确率
accuracy = np.sum(y_pred == y_test) / len(y_test)
print("Test Accuracy: {:.2f}%".format(accuracy artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls 100))
代码细节解释
- 加载手写数字数据集,并划分为训练集和测试集。
- 对特征进行归一化,使用StandardScaler进行均值方差归一化处理。
- 定义sigmoid函数,用于将线性输出映射到[0,1]之间。
- 初始化参数$\theta$为零向量。
- 定义代价函数cost_func,计算交叉熵损失函数的值。
- 定义梯度下降函数gradient_descent,使用梯度下降算法更新参数$\theta$。
- 在指定的迭代次数内运行梯度下降算法,保存每次迭代的代价函数值。
- 绘制代价函数的学习曲线,观察模型的收敛情况。
- 预测测试集的类别,并计算准确率。
这就是Logistic回归算法的详细解决方案。通过科学地讲解算法原理和公式推导,以及使用复杂的Python代码示例,希望能帮助你理解该算法的工作原理和实际应用。
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/821806/
转载文章受原作者版权保护。转载请注明原作者出处!