好的,以下是利用 KaTeX 语法重新排版的逻辑回归详细图文教程。
一、逻辑回归概述
逻辑回归用于二分类问题,即输出是两个类别中的一个。它利用逻辑函数(sigmoid函数)将线性回归的输出映射到0和1之间的概率值。
1. 逻辑函数(Sigmoid函数)
逻辑函数的形式如下:
[ \sigma(z) = \frac{1}{1 + e^{-z}} ]
其中,( z ) 是线性回归的输出。
2. 二分类问题
假设我们要预测一个样本 ( x ) 属于类别1的概率 ( P(y=1|x) ),则:
[ P(y=1|x) = \sigma(z) = \frac{1}{1 + e^{-z}} ]
其中,( z = w^T x + b ),( w ) 是权重向量,( b ) 是偏置项。
二、模型训练
1. 损失函数
逻辑回归使用对数损失函数(Log Loss)来评估模型的性能:
[ L(y, \hat{y}) = - \frac{1}{m} \sum_{i=1}^{m} \left[ y^{(i)} \log(\hat{y}^{(i)}) + (1 - y^{(i)}) \log(1 - \hat{y}^{(i)}) \right] ]
其中,( \hat{y}^{(i)} ) 是第 ( i ) 个样本的预测概率,( y^{(i)} ) 是实际标签,( m ) 是样本总数。
2. 梯度下降
为了最小化损失函数,我们使用梯度下降算法。梯度下降的更新公式为:
[ w := w - \alpha \frac{\partial L}{\partial w} ] [ b := b - \alpha \frac{\partial L}{\partial b} ]
其中,( \alpha ) 是学习率,损失函数相对于 ( w ) 和 ( b ) 的梯度分别为:
[ \frac{\partial L}{\partial w} = \frac{1}{m} \sum_{i=1}^{m} ( \hat{y}^{(i)} - y^{(i)} ) x^{(i)} ] [ \frac{\partial L}{\partial b} = \frac{1}{m} \sum_{i=1}^{m} ( \hat{y}^{(i)} - y^{(i)} ) ]
三、实现步骤
下面是一个用Python实现逻辑回归的示例:
1. 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
2. 数据预处理
# 生成一些示例数据
np.random.seed(0)
num_observations = 500
x1 = np.random.multivariate_normal([0,0], [[1,0.75],[0.75,1]], num_observations)
x2 = np.random.multivariate_normal([1,4], [[1,0.75],[0.75,1]], num_observations)
features = np.vstack((x1, x2)).astype(np.float32)
labels = np.hstack((np.zeros(num_observations), np.ones(num_observations)))
plt.figure(figsize=(12,8))
plt.scatter(features[:, 0], features[:, 1], c=labels, alpha=0.4)
plt.show()
3. 定义辅助函数
# Sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 损失函数
def loss(h, y):
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
4. 训练模型
# 超参数
learning_rate = 0.1
num_steps = 300000
# 初始化参数
theta = np.zeros(features.shape[1])
bias = 0
for step in range(num_steps):
# 计算线性组合
z = np.dot(features, theta) + bias
h = sigmoid(z)
# 计算梯度
gradient = np.dot(features.T, (h - labels)) / labels.size
intercept_gradient = np.sum(h - labels) / labels.size
# 更新参数
theta -= learning_rate * gradient
bias -= learning_rate * intercept_gradient
# 每10000步打印一次损失
if step % 10000 == 0:
print(f'loss: {loss(h, labels)} \t')
5. 预测和评估
def predict_prob(features, theta, bias):
return sigmoid(np.dot(features, theta) + bias)
def predict(features, theta, bias, threshold=0.5):
return predict_prob(features, theta, bias) >= threshold
# 预测
preds = predict(features, theta, bias)
accuracy = (preds == labels).mean()
print(f'Accuracy: {accuracy}')
6. 可视化决策边界
plt.figure(figsize=(12,8))
plt.scatter(features[:, 0], features[:, 1], c=labels, alpha=0.4)
# 画决策边界
x_boundary = np.array([np.min(features[:, 0]), np.max(features[:, 0])])
y_boundary = -(bias + theta[0] * x_boundary) / theta[1]
plt.plot(x_boundary, y_boundary, 'k--')
plt.show()
以上就是逻辑回归的详细图文教程。如果你有任何问题或需要进一步的解释,请随时告诉我!
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:http://example.com/subject/article/98/
许可协议:署名-非商业性使用 4.0 国际许可协议