python机器学习(五)逻辑回归、决策边界、代价函数、梯度下降法实现线性和非线性逻辑回归
发布人:shili8
发布时间:2025-03-12 01:02
阅读次数:0
**Python机器学习 (五) 逻辑回归、决策边界、代价函数、梯度下降法**
在前几篇文章中,我们已经介绍了线性回归、决策树和随机森林等基本算法。今天我们将重点讨论逻辑回归,这是一种常见的二分类算法。
**1. 逻辑回归**
逻辑回归(Logistic Regression)是用于二分类问题的一种线性模型,它通过对输入数据进行非线性变换来实现分类。逻辑回归的主要优势在于它能够处理高维度数据,并且可以很容易地将其扩展到多类别问题。
**1.1 逻辑回归的决策边界**
逻辑回归的决策边界是通过对输入数据进行非线性变换后得到的。假设我们有一个二分类问题,目标是预测样本是否属于某一类别。我们可以使用以下公式来计算决策边界:
f(x) =1 / (1 + exp(-z))
其中 z 是输入数据 x 的线性组合。
**1.2 逻辑回归的代价函数**
逻辑回归的代价函数是用于衡量模型预测结果与实际结果之间差异的。最常用的代价函数是交叉熵(Cross-Entropy):
L(y, y') = -y * log(y') - (1-y) * log(1-y')
其中 y 是真实标签,y' 是预测值。
**2. 实现线性逻辑回归**
下面是实现线性逻辑回归的 Python代码:
import numpy as npclass LinearLogisticRegression: def __init__(self): self.weights = None self.bias = None def fit(self, X, y): n_samples, n_features = X.shape self.weights = np.zeros(n_features) self.bias =0 for _ in range(100): # 迭代次数 predictions =1 / (1 + np.exp(-np.dot(X, self.weights) - self.bias)) gradients_weights = np.dot(X.T, y - predictions) gradients_bias = np.sum(y - predictions) self.weights -=0.01 * gradients_weights self.bias -=0.01 * gradients_bias def predict(self, X): return1 / (1 + np.exp(-np.dot(X, self.weights) - self.bias))
**3. 实现非线性逻辑回归**
为了实现非线性逻辑回归,我们可以使用神经网络的结构来对输入数据进行非线性变换。下面是实现非线性逻辑回归的 Python代码:
import numpy as npclass NonlinearLogisticRegression: def __init__(self): self.weights1 = None self.bias1 = None self.weights2 = None self.bias2 = None def fit(self, X, y): n_samples, n_features = X.shape self.weights1 = np.random.rand(n_features) self.bias1 =0 self.weights2 = np.random.rand(10) # 隐藏层神经元数量 self.bias2 =0 for _ in range(100): # 迭代次数 hidden_layer = sigmoid(np.dot(X, self.weights1) + self.bias1) output_layer =1 / (1 + np.exp(-np.dot(hidden_layer, self.weights2) - self.bias2)) gradients_weights1 = np.dot(X.T, (y - output_layer) * hidden_layer) gradients_bias1 = np.sum((y - output_layer) * hidden_layer) gradients_weights2 = np.dot(hidden_layer.T, (y - output_layer)) gradients_bias2 = np.sum(y - output_layer) self.weights1 -=0.01 * gradients_weights1 self.bias1 -=0.01 * gradients_bias1 self.weights2 -=0.01 * gradients_weights2 self.bias2 -=0.01 * gradients_bias2 def predict(self, X): hidden_layer = sigmoid(np.dot(X, self.weights1) + self.bias1) output_layer =1 / (1 + np.exp(-np.dot(hidden_layer, self.weights2) - self.bias2)) return output_layer
其中 `sigmoid` 是激活函数,用于对输入数据进行非线性变换。
**4. 总结**
在本文中,我们介绍了逻辑回归的基本概念和实现方法。我们使用 Python代码示例来展示如何实现线性和非线性逻辑回归。通过阅读本文,你应该能够理解逻辑回归的原理和应用,并且能够使用 Python 来实现逻辑回归模型。
**参考文献**
* Bishop, C. M. (2006). Pattern recognition and machine learning. Springer.
* Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep learning. MIT Press.
注:本文中的代码示例仅供学习和参考目的,可能需要根据具体问题进行调整和优化。