如何使用逻辑回归从头开始创建分类器
ztj100 2024-11-10 13:14 16 浏览 0 评论
在本文中,我将简要描述如何使用逻辑回归从零开始创建分类器。在实践中,您可能会使用诸如scikit-learn或tensorflow之类的包来完成这项工作,但是理解基本的方程和算法对于机器学习非常有帮助。
本文中的所有代码使用Python,所以让我们导入所有需要Python库:
# Import packages
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# General plot parameters
mpl.rcParams['font.size'] = 18
mpl.rcParams['axes.linewidth'] = 2
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.labelpad'] = 10
mpl.rcParams['xtick.major.size'] = 10
mpl.rcParams['xtick.major.width'] = 2
mpl.rcParams['ytick.major.size'] = 10
mpl.rcParams['ytick.major.width'] = 2
离散预测
要理解预测算法,最好先选择一个数学函数,它的二进制输出是0或1。我们可以使用logistic或sigmoid函数,它的形式是:
我们可以用Python编写此函数并将其绘制如下:
def sigmoid(z):
"""Returns value of the sigmoid function."""
return 1/(1 + np.exp(-z))
# Calculate sigmoid
x = np.linspace(-10, 10, 100)
y = sigmoid(x)
# Create figure
fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot(111)
# Plot sigmoid
ax.plot(x, y, linewidth=2, color='#483d8b')
# Add grid
ax.grid(linestyle='--', linewidth=2, color='gray', alpha=0.2)
# Edit y-ticks
ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
# Edit axis labels
ax.set(xlabel='x', ylabel='y')
plt.show()
在x = 0附近,sigmoid函数的输出值迅速从0附近变为接近1。由于输出值在y = 0.5附近是对称的,我们可以将其作为决策阈值,其中y≥0.5输出1,y < 0.5输出0。
生成机器学习数据集
我们的场景如下所示:我们正在构建一个简单的电影推荐系统,该系统考虑到0到5之间的user score(所有用户)和0到5之间的critic score。然后,我们的模型应该根据输入数据生成一个决策边界,以预测当前用户是否会喜欢这部电影,并向他们推荐这部电影。
我们将为100部电影设置一组随机的user scores和critic scores:
# For reproducibility - will seed psuedorandom numbers at same point
np.random.seed(74837)
# Random user and critic scores
user_score = 5*np.random.random(size=100)
critic_score = 5*np.random.random(size=100)
现在,让我们生成分类:在这种情况下,用户可能喜欢这部电影(1),也可能不喜欢(0)。为此,我们将使用以下决策边界函数。我们将此方程的右侧设置为0,因为它定义了logistic函数等于0.5的情况:
y = np.zeros(len(user_score))
boundary = lambda x1, x2: 6 - x1 - 2*x2
# Set y = 1 above decision boundary
for i in range(len(y)):
if boundary(user_score[i], critic_score[i]) <= 0:
y[i] = 1
else:
y[i] = 0
注意,在实际数据集中,您不知道决策边界的函数形式是什么。在本教程中,我们定义了一个函数并添加了一些噪声。
现在,我们可以绘制我们的初始数据,其中一个橙色圆圈表示用户喜欢的电影,一个蓝色圆圈表示用户不喜欢的电影:
# Create figure
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
# Colors for scatter points
colors = ['#483d8b', '#cc8400']
colors_data = [colors[int(i)] for i in y]
# Plot sample data
ax.scatter(user_score, critic_score, color=colors_data, s=100, edgecolor='black', linewidth=2, alpha=0.7)
# Add grid
ax.grid(linestyle='--', linewidth=2, color='gray', alpha=0.2)
# Add axis labels
ax.set(xlabel='User Score', ylabel='Critic Score')
plt.show()
决策边界
为了确定我们的决策边界有多好,我们需要为错误预测定义一个惩罚,我们将通过创建一个成本函数来实现。我们的预测如下:
当P ≥0.5,我们输出1,当P <0.5,我们将输出0,其中W 0,W 1,W 2是需要优化的权重。
为了惩罚错误的分类,我们可以利用对数函数,因为log(1)= 0并且log(0)→-∞。我们可以使用它来创建两个惩罚(penalty)函数,如下所示:
我们可以将其可视化以更清楚地看到这些惩罚函数的效果:
利用输出(y)不是0就是1的事实,我们可以将这两个惩罚(penalty)函数结合在一个表达式中,这个表达式包含了这两种情况:
现在,当我们的输出是1,我们预测的结果接近于0(第一项)时,我们会遭受高惩罚。类似地,当我们的输出为0,我们预测的结果接近于1(第二项)时,也会发生相同的情况。
现在,我们可以采用惩罚函数并将其推广到m个训练实例中,第i个训练实例的标签由(i)表示。我们还将总成本除以m,以获得均值惩罚(就像线性回归中的均方误差一样)。该最终表达式也称为成本函数。我们将我们的两个特征(user score和critic score)称为x?和x?。
成本函数
为了找到最佳决策边界,我们必须最小化成本函数,这可以通过梯度下降算法来完成,该算法的本质是:(1)通过计算成本函数的梯度来找到最大减少的方向,(2)通过沿着这个梯度移动来更新权重值。为了更新权重,我们还提供了学习率(α),它确定了我们沿着该梯度移动了多少。选择学习率时需要权衡注意:学习率太小,我们的算法需要太长时间才能收敛;学习率太大,我们的算法实际上可能不会收敛到全局最优值。
最后一个难题是计算上面表达式中的偏导数。我们可以用微积分的链式法则把它分解为:
现在,我们可以把它们放在一起,得到以下梯度表达式和梯度下降更新规则:
初始化变量
首先,我们将变量初始化如下:
我们现在可以重写前面的函数下,其中上标T表示矩阵的转置:
我们的变量可以初始化如下(我们将所有权重设置为0):
X = np.concatenate((np.ones(shape=(len(user_score), 1)), user_score.reshape(len(user_score), 1),
critic_score.reshape(len(critic_score), 1)), axis=1)
y = y.reshape(len(y), 1)
w = np.zeros(shape=(3, 1))
训练模型
以下函数计算成本和梯度值:
def cost_function(X, y, w):
"""
Returns cost function and gradient
Parameters
X: m x (n+1) matrix of features
y: m x 1 vector of labels
w: (n+1) x 1 vector of weights
Returns
cost: value of cost function
grad: (n+1) x 1 vector of weight gradients
"""
m = len(y)
h = sigmoid(np.dot(X, w))
cost = (1/m)*(-np.dot(y.T, np.log(h)) - np.dot((1 - y).T, np.log(1 - h)))
grad = (1/m)*np.dot(X.T, h - y)
return cost, grad
在定义梯度下降函数时,我们必须添加一个称为num_iter的额外输入,它告诉算法在返回最终优化权重之前要进行的迭代次数。
def gradient_descent(X, y, w, alpha, num_iters):
"""
Uses gradient descent to minimize cost function.
Parameters
X: m x (n+1) matrix of features
y: m x 1 vector of labels
w: (n+1) x 1 vector of weights
alpha (float): learning rate
num_iters (int): number of iterations
Returns
J: 1 x num_iters vector of costs
w_new: (n+1) x 1 vector of optimized weights
w_hist: (n+1) x num_iters matrix of weights
"""
w_new = np.copy(w)
w_hist = np.copy(w)
m = len(y)
J = np.zeros(num_iters)
for i in range(num_iters):
cost, grad = cost_function(X, y, w_new)
w_new = w_new - alpha*grad
w_hist = np.concatenate((w_hist, w_new), axis=1)
J[i] = cost
return J, w_new, w_hist
现在,使用以下Python代码训练我们的机器学习模型!
J, w_train, w_hist = gradient_descent(X, y, w, 0.5, 2000)
在实际情况中,为了交叉验证和测试模型,我们需要拆分训练数据,但是本教程主要用于演示,我们将使用所有的训练数据。
为了确保实际上每次迭代都在降低成本函数的值,可视化图像的Python代码如下:
# Create figure
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
# Plot costs
ax.plot(range(len(J)), J, linewidth=2)
# Add axis labels
ax.set(xlabel='Iterations', ylabel='J(w)')
plt.show()
现在是关键时刻,我们可以绘制决策边界。我们将其覆盖到原始图上的方法是定义一个点网格,然后使用经过训练的权重计算sigmoid函数的预测值。
# Create figure
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
# Colors for scatter points
colors = ['#483d8b', '#cc8400']
colors_data = [colors[int(i)] for i in y]
# Plot decision boundary
x1_bound, x2_bound = np.meshgrid(np.linspace(0, 5, 50), np.linspace(0, 5, 50))
prob = sigmoid(w_train[0] + x1_bound*w_train[1] + x2_bound*w_train[2])
ax.contour(x1_bound, x2_bound, prob, levels=[0.5], colors='black')
# Plot sample data
ax.scatter(user_score, critic_score, color=colors_data, s=100, edgecolor='black', linewidth=2, alpha=0.7)
# Add grid
ax.grid(linestyle='--', linewidth=2, color='gray', alpha=0.2)
# Add axis labels
ax.set(xlabel='User Score', ylabel='Critic Score')
plt.show()
我们现在可以编写一个函数,根据这个训练好的模型做出预测:
def predict(X, w):
"""
Predicts classifiers based on weights
Parameters
X: m x n matrix of features
w: n x 1 vector of weights
Returns
predictions: m x 1 vector of predictions
"""
predictions = sigmoid(np.dot(X, w))
for i, val in enumerate(predictions):
if val >= 0.5:
predictions[i] = 1
else:
predictions[i] = 0
return predictions
现在,让我们对新实例进行预测:
X_new = np.asarray([[1, 3.4, 4.1], [1, 2.5, 1.7], [1, 4.8, 2.3]])
print(predict(X_new, w_train))
#[[1.] [0.] [1.]]
多类分类
现在我们已经完成了制作二元分类器的所有工作,将其扩展到多类上是相当简单的。我们将使用一个名为one-vs-all的分类策略,其中我们为每个不同的类训练一个二元分类器,并选择sigmoid函数返回的最大值对应的类。
让我们构建模型:这次用户可以给电影评分0星,1星或2星。
首先,我们再次生成数据并应用两个决策边界:
np.random.seed(7839374)
# Random user and critic scores
user_score = 5*np.random.random(size=100)
critic_score = 5*np.random.random(size=100)
y = np.zeros(len(user_score))
boundary_1 = lambda x1, x2: 6 - x1 - 2*x2
boundary_2 = lambda x1, x2: 4 + x1 - 2*x2
for i in range(len(y)):
if (boundary_1(user_score[i], critic_score[i]) + 0.5*np.random.normal() <= 0):
if (boundary_2(user_score[i], critic_score[i]) <= 0):
y[i] = 2
else:
y[i] = 1
else:
y[i] = 0
# Create figure
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
# Colors for scatter points
colors = ['#483d8b', '#cc8400', '#8b483d']
colors_data = [colors[int(i)] for i in y]
# Plot sample data
ax.scatter(user_score, critic_score, color=colors_data, s=100, edgecolor='black', linewidth=2, alpha=0.7)
# Add grid
ax.grid(linestyle='--', linewidth=2, color='gray', alpha=0.2)
# Add axis labels
ax.set(xlabel='User Score', ylabel='Critic Score')
plt.show()
我们的数据集如下所示,其中蓝色圆圈代表0星,橙色圆圈代表1星,红色圆圈代表2星:
对于我们训练的每个二进制分类器,我们将需要重新标记数据,以便将我们感兴趣的类的输出设置为1,并将所有其他标签设置为0。例如,如果我们有3组A(0) ,B(1)和C(2)—我们必须制作三个二进制分类器:
对于我们训练的每个二元分类器,我们需要重新标记数据,以便我们感兴趣的类的输出被设置为1,其他标签被设置为0。我们必须创建3个二元分类器:
(1)A设为1,B和C设为0
(2)B设为1,A和C设为0
(3)C设为1,A和B设为0
下面的函数为每个分类器重新标记我们的数据:
def relabel_data(y, label):
"""
Relabels data for one-vs-all classifier
Parameters
y: m x 1 vector of labels
label: which label to set to 1 (sets others to 0)
Returns
relabeled_data: m x 1 vector of relabeled data
"""
relabeled_data = np.zeros(len(y))
for i, val in enumerate(y):
if val == label:
relabeled_data[i] = 1
return relabeled_data.reshape(len(y), 1)
现在,我们进行模型训练:
# Initialize variables
X = np.concatenate((np.ones(shape=(len(user_score), 1)), user_score.reshape(len(user_score), 1),
critic_score.reshape(len(critic_score), 1)), axis=1)
y = y.reshape(len(y), 1)
w = np.zeros(shape=(3, 1))
y_class1 = relabel_data(y, 0)
_, w_class1, _ = gradient_descent(X, y_class1, w, 0.5, 2000)
y_class2 = relabel_data(y, 1)
_, w_class2, _ = gradient_descent(X, y_class2, w, 0.5, 2000)
y_class3 = relabel_data(y, 2)
_, w_class3, _ = gradient_descent(X, y_class3, w, 0.5, 2000)
绘制决策边界这一次稍微复杂一些。我们必须为每个经过训练的分类器计算网格中每个点的预测值。然后我们选择每个点的最大预测值,并根据导致该最大值的分类器为其分配相应的类。我们选择绘制的轮廓线为0.5(在0和1之间)和1.5(在1和2之间):
# Create figure
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
# Colors for scatter points
colors = ['#cc8400', '#483d8b', '#8b483d']
colors_data = [colors[int(i)] for i in y]
# Plot decision boundaries
x1_bound, x2_bound = np.meshgrid(np.linspace(-0.05, 5.05, 500), np.linspace(-0.05, 5.05, 500))
prob_0 = sigmoid(w_class1[0] + x1_bound*w_class1[1] + x2_bound*w_class1[2])
prob_1 = sigmoid(w_class2[0] + x1_bound*w_class2[1] + x2_bound*w_class2[2])
prob_2 = sigmoid(w_class3[0] + x1_bound*w_class3[1] + x2_bound*w_class3[2])
prob_max = np.zeros(shape=x1_bound.shape)
for i in range(prob_max.shape[0]):
for j in range(prob_max.shape[1]):
maximum = max(prob_0[i][j], prob_1[i][j], prob_2[i][j])
if maximum == prob_0[i][j]:
prob_max[i][j] = 0
elif maximum == prob_1[i][j]:
prob_max[i][j] = 1
else:
prob_max[i][j] = 2
ax.contour(x1_bound, x2_bound, prob_max, levels=[0.5, 1.5], colors='black', linewidths=2)
# Plot sample data
ax.scatter(user_score, critic_score, color=colors_data, s=100, edgecolor='black', linewidth=2, alpha=0.7)
# Add grid
ax.grid(linestyle='--', linewidth=2, color='gray', alpha=0.2)
# Add axis labels
ax.set(xlim=(-0.05, 5.05), ylim=(-0.05, 5.05), xlabel='User Score', ylabel='Critic Score')
plt.show()
这是我们训练过的决策边界!
最后,我们做一个预测函数。为此,我们将使用一个小技巧——我们将对每个实例中的每个分类器进行预测;接下来,我们将把每组预测作为一个新列附加到预测矩阵中;接下来通过遍历每一行并选择具有最大值的列索引,然后获得分类器标签!
def predict_multi(X, w):
"""
Predicts classifiers based on weights
Parameters
X: m x n matrix of features
w: array of n x 1 vectors of weights
Returns
predictions: m x 1 vector of predictions
"""
predictions = np.empty((X.shape[0], 0))
# Gather predictions for each classifier
for i in range(len(w)):
predictions = np.append(predictions, sigmoid(np.dot(X, w[i])), axis=1)
return np.argmax(predictions, axis=1).reshape(X.shape[0], 1)
X_new = np.array([[1, 1, 1], [1, 1, 4.2], [1, 4.5, 2.5]])
print(predict_multi(X_new, [w_class1, w_class2, w_class3]))
# [[0] [2] [1]]
相关推荐
- 再说圆的面积-蒙特卡洛(蒙特卡洛方法求圆周率的matlab程序)
-
在微积分-圆的面积和周长(1)介绍微积分方法求解圆的面积,本文使用蒙特卡洛方法求解圆面积。...
- python创建分类器小结(pytorch分类数据集创建)
-
简介:分类是指利用数据的特性将其分成若干类型的过程。监督学习分类器就是用带标记的训练数据建立一个模型,然后对未知数据进行分类。...
- matplotlib——绘制散点图(matplotlib散点图颜色和图例)
-
绘制散点图不同条件(维度)之间的内在关联关系观察数据的离散聚合程度...
- python实现实时绘制数据(python如何绘制)
-
方法一importmatplotlib.pyplotaspltimportnumpyasnpimporttimefrommathimport*plt.ion()#...
- 简单学Python——matplotlib库3——绘制散点图
-
前面我们学习了用matplotlib绘制折线图,今天我们学习绘制散点图。其实简单的散点图与折线图的语法基本相同,只是作图函数由plot()变成了scatter()。下面就绘制一个散点图:import...
- 数据分析-相关性分析可视化(相关性分析数据处理)
-
前面介绍了相关性分析的原理、流程和常用的皮尔逊相关系数和斯皮尔曼相关系数,具体可以参考...
- 免费Python机器学习课程一:线性回归算法
-
学习线性回归的概念并从头开始在python中开发完整的线性回归算法最基本的机器学习算法必须是具有单个变量的线性回归算法。如今,可用的高级机器学习算法,库和技术如此之多,以至于线性回归似乎并不重要。但是...
- 用Python进行机器学习(2)之逻辑回归
-
前面介绍了线性回归,本次介绍的是逻辑回归。逻辑回归虽然名字里面带有“回归”两个字,但是它是一种分类算法,通常用于解决二分类问题,比如某个邮件是否是广告邮件,比如某个评价是否为正向的评价。逻辑回归也可以...
- 【Python机器学习系列】拟合和回归傻傻分不清?一文带你彻底搞懂
-
一、拟合和回归的区别拟合...
- 推荐2个十分好用的pandas数据探索分析神器
-
作者:俊欣来源:关于数据分析与可视化...
- 向量数据库:解锁大模型记忆的关键!选型指南+实战案例全解析
-
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在...
- 用Python进行机器学习(11)-主成分分析PCA
-
我们在机器学习中有时候需要处理很多个参数,但是这些参数有时候彼此之间是有着各种关系的,这个时候我们就会想:是否可以找到一种方式来降低参数的个数呢?这就是今天我们要介绍的主成分分析,英文是Princip...
- 神经网络基础深度解析:从感知机到反向传播
-
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在...
- Python实现基于机器学习的RFM模型
-
CDA数据分析师出品作者:CDALevelⅠ持证人岗位:数据分析师行业:大数据...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)