1.逻辑回归概述
逻辑回归(Logistic Regression)是一种适用于分类问题的机器学习算法。该算法的主要目的是用于预测一个特定事件的发生概率。逻辑回归的输出是一个介于0和1之间的概率值,表示某样本属于某个类别的概率大小。
逻辑回归常用于二分类问题的预测,比如判断邮件是否为垃圾邮件、肿瘤是恶性还是良性等,也可以通过构建多个二分类模型来解决多分类问题。
2.logistic回归原理
2.1 线性模型与回归
线性模型一般形式:
f ( x )= w1x1+w2x2+...+wnxn + b
向量形式:
2.2 最小二乘法与参数求解
分别对w和b求导,可得:
得到:
2.3 Sigmoid函数
Sigmoid函数是logistic回归模型中使用的一种特殊类型的函数。它被用来将输入的线性组合转换成0到1之间的概率值,通常用于二元分类问题中作为逻辑回归模型的激活函数。在logistic回归中,Sigmoid函数被应用到线性模型的预测值上,将其转换为表示正类别的概率。在训练过程中,通过最大化对数似然函数的方法,模型利用数据优化Sigmoid函数的参数,使得模型对样本的分类结果更加准确。
3 logistic回归的实现
import numpy as np
class LogisticRegression:
def __init__(self, learning_rate=0.01, num_iterations=1000):
self.learning_rate = learning_rate
self.num_iterations = num_iterations
self.weights = None
self.bias = None
def fit(self, X, y):
# Initialize weights and bias
num_samples, num_features = X.shape
self.weights = np.zeros(num_features)
self.bias = 0
# Gradient descent training
for _ in range(self.num_iterations):
linear_model = np.dot(X, self.weights) + self.bias
y_predicted = self._sigmoid(linear_model)
dw = (1/num_samples) * np.dot(X.T, (y_predicted - y))
db = (1/num_samples) * np.sum(y_predicted - y)
self.weights -= self.learning_rate * dw
self.bias -= self.learning_rate * db
def predict(self, X):
linear_model = np.dot(X, self.weights) + self.bias
y_predicted = self._sigmoid(linear_model)
y_predicted_cls = [1 if i > 0.5 else 0 for i in y_predicted]
return y_predicted_cls
def _sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# Test
if __name__ == "__main__":
np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
y = np.array([0]*20 + [1]*20)
model = LogisticRegression()
model.fit(X, y)
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis', edgecolors='k', s=50)
plt.xlabel('X1')
plt.ylabel('X2')
xx, yy = np.mgrid[-5:5:.01, -5:5:.01]
grid = np.c_[xx.ravel(), yy.ravel()]
pred = np.array(model.predict(grid)).reshape(xx.shape)
plt.contourf(xx, yy, pred, alpha=0.3, cmap='viridis')
plt.title('Logistic Regression Decision Boundary')
plt.show()
运行结果
4 总结
logistic回归的优缺点:
优点: 简单而有效,logistic回归是一种线性分类器,简单易于实现和理解。相对于高复杂度的模型如神经网络,logistic回归对于训练数据量较小的情况下往往不容易发生过拟合。logistic回归能够进行特征选择,处理不相关的特征。
缺点: 由于logistic回归是一个线性分类器,所以它可能无法很好地处理非线性分类问题。 对异常值敏感logistic回归对异常值比较敏感,有可能影响模型的性能。不能处理复杂关系:logistic回归受限于线性决策面,无法很好地处理复杂的分类关系。