欢迎关注微信公众号:数据科学与艺术
逻辑回归模型
逻辑回归是一种经典的二分类模型,用于预测某个事件发生的概率。它的核心思想是将特征通过一个线性回归模型与sigmoid函数结合,将连续的线性函数映射为[0,1]之间的概率值。
在逻辑回归模型中,假设函数(hypothesis)由以下公式表示:
hθ(x) = g(θ^T * x)
其中,hθ(x)表示事件x发生的概率,θ为模型的参数,x是特征向量,g(·)是sigmoid函数。
sigmoid函数的定义为:
g(z) = 1 / (1 + e^(-z))
接下来,我们可以使用最大似然估计来估计参数θ。假设训练集为{(x1, y1), (x2, y2), …, (xm, ym)},其中xi表示特征向量,yi是对应的标签(0或1)。对于每个样本,其对应的似然函数为:
L(θ) = ∏(hθ(xi))^yi * (1 - hθ(xi))^(1-yi)
为了最大化似然函数,我们可以使用梯度下降算法来优化参数。最终,我们可以得到一个逻辑回归模型,可以用于预测新样本的标签。
下面是一个使用Python实现逻辑回归模型的代码:
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.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)
predictions = np.round(h)
return predictions
# 使用示例
X_train = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y_train = np.array([0, 0, 1, 1])
X_test = np.array([[2, 3], [4, 5]])
lr_model = LogisticRegression()
lr_model.fit(X_train, y_train)
predictions = lr_model.predict(X_test)
print(predictions)
这个使用逻辑回归模型进行二分类预测。在这代码中,使用了梯度下降算法来优化模型的参数,并使用sigmoid函数将线性函数转换为概率值。最后,将模型应用于新样本并预测其标签。