在 Python 中实现逻辑回归算法(Logistic Regression)可以使用纯 Python 编写,也可以利用 sklearn
等机器学习库。下面我会展示一个简单的手写实现和使用 sklearn
库的实现。
1. 手写实现逻辑回归算法
我们可以从零开始实现逻辑回归。逻辑回归是通过最大化似然函数来进行参数优化,通常使用梯度下降来寻找最佳参数。
import numpy as np
# Sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 计算损失函数(对数损失)
def compute_cost(X, y, theta):
m = len(y)
h = sigmoid(np.dot(X, theta)) # 预测值
cost = -(1/m) * (np.dot(y.T, np.log(h)) + np.dot((1 - y).T, np.log(1 - h)))
return cost
# 梯度下降
def gradient_descent(X, y, theta, learning_rate, iterations):
m = len(y)
cost_history = []
for i in range(iterations):
gradient = (1/m) * np.dot(X.T, (sigmoid(np.dot(X, theta)) - y))
theta -= learning_rate * gradient # 更新theta
cost_history.append(compute_cost(X, y, theta)) # 记录每次迭代的损失
return theta, cost_history
# 逻辑回归训练函数
def logistic_regression(X, y, learning_rate=0.01, iterations=1000):
m, n = X.shape
X = np.c_[np.ones(m), X] # 添加偏置项(X的第一列为1)
theta = np.zeros(n + 1) # 初始化theta
theta, cost_history = gradient_descent(X, y, theta, learning_rate, iterations)
return theta, cost_history
# 预测函数
def predict(X, theta):
X = np.c_[np.ones(X.shape[0]), X] # 添加偏置项
probabilities = sigmoid(np.dot(X, theta))
predictions = [1 if prob >= 0.5 else 0 for prob in probabilities]
return np.array(predictions)
2. 使用 sklearn
库实现逻辑回归
如果你希望使用现成的库来实现逻辑回归,可以用 sklearn
的 LogisticRegression
类来完成。sklearn
提供了优化好的算法,且接口简洁易用。
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 生成一个二分类数据集
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
# 切分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 使用sklearn的LogisticRegression
model = LogisticRegression(max_iter=1000) # 设置最大迭代次数
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型准确率: {accuracy * 100:.2f}%")
解释
手写实现:
- 使用了梯度下降来优化逻辑回归的参数。
sigmoid
函数将线性回归的输出映射到 [0, 1] 区间,表示为概率值。compute_cost
计算的是对数损失(log loss),这是逻辑回归常用的损失函数。gradient_descent
通过梯度下降法不断调整参数来最小化损失函数。
使用
sklearn
实现:- 通过
LogisticRegression
类提供的接口,直接完成了模型的训练、预测和评估,极大简化了代码。
- 通过
你可以根据自己的需求选择手写实现或使用 sklearn
的实现。如果你有其他问题或者想了解更多细节,可以随时告诉我!