python实现逻辑回归的流程_逻辑回归原理及其python实现

September 28, 2018

7 min to read

逻辑回归原理及其python实现

原理

逻辑回归模型:

$h_{\theta}(x)=\frac{1}{1+e^{-{\theta}^{T}x}}$

逻辑回归代价函数:

$J(\theta)=\frac{1}{m}\sum_{i=1}^{m}Cost(h_{\theta}(x^{(i)}),y^{(i)})$

其中:

该式子合并后:

$Cost(h_{\theta}(x),y)=-ylog(h_{\theta}(x))-(1-y)log(1-h_{\theta}(x))$

即逻辑回归的代价函数:

$J(\theta)=-\frac{1}{m}[\sum_{i=1}^{m}y^{(i)}logh_{\theta}(x^{(i)})+(1-y^{(i)})log(1-h_{\theta}(x^{(i)}))]$

最小化代价函数,使用梯度下降法(gradient descent)。

Want $min_{\theta}J(\theta):$

Repeat {

$\theta_{j}=\theta_{j}-\alpha\frac{\partial}{\partial\theta_{j}}J(\theta)$

}  (simultaneously updata all $\theta_{j}$,$\alpha$为学习率)

即:

Repeat {

$\theta_{j}=\theta_{j}-\alpha\sum_{i=1}^{m}(h_{\theta}(x^{(i)})-y^{(i)})x_{j}^{(i)}$

}

正则化(Regularization)

如果我们有非常多的特征,我们通过学习得到的模型可能能够非常好地适应训练集,但是可能不能推广到新的数据集,我们把这种现象成为过拟合。

为防止过拟合,提升模型泛化能力,我们需要对所有特征参数(除$\theta_{0}$外)进行惩罚,即保留所有特征,减小参数$\theta$的值,当我们拥有很多不太有用的特征时,正则化会起到很好的作用。

$J(\theta)=-[\frac{1}{m}\sum_{i=1}^{m}(y^{(i)}log(h_{\theta}(x^{(i)}))+(1-y^{(i)})log(1-h_{\theta}(x^{(i)})))]+\frac{\lambda}{2m}\sum_{j=1}^{n}\theta_{j}^{2}$

梯度下降算法:

Repeat until convergence{

$\theta_{0}=\theta_{0}-\alpha\frac{1}{m}\sum_{i=1}^{m}((h_{\theta}(x^{(i)})-y^{(i)})\cdot x_{0}^{(i)})$

$\theta_{j}=\theta_{j}-\alpha\frac{1}{m}\sum_{i=1}^{m}((h_{\theta}(x^{(i)})-y^{(i)})\cdot x_{j}^{(i)}+\frac{\lambda}{m}\theta_{j})$    $for\hspace{1em}j=1,2,…n$

}

python实现

代码

# -*- coding:UTF-8 -*-import matplotlib.pyplot as plt

import numpy as np

"""

函数说明:梯度上升算法测试函数

求函数f(x) = -x^2 + 4x的极大值

Parameters:

Returns:

"""

def Gradient_Ascent_test():

def f_prime(x_old):#f(x)的导数return -2 * x_old + 4

x_old = -1#初始值,给一个小于x_new的值x_new = 0#梯度上升算法初始值,即从(0,0)开始alpha = 0.01#步长,也就是学习速率,控制更新的幅度presision = 0.00000001#精度,也就是更新阈值while abs(x_new - x_old) > presision:

x_old = x_new

x_new = x_old + alpha * f_prime(x_old)#上面提到的公式print(x_new)#打印最终求解的极值近似值

"""

函数说明:加载数据

Parameters:

Returns:

dataMat - 数据列表

labelMat - 标签列表

"""

def loadDataSet():

dataMat = []#创建数据列表labelMat = []#创建标签列表fr = open('testSet.txt')#打开文件for line in fr.readlines():#逐行读取lineArr = line.strip().split()#去回车,放入列表dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])#添加数据labelMat.append(int(lineArr[2]))#添加标签fr.close()#关闭文件return dataMat, labelMat#返回

"""

函数说明:sigmoid函数

Parameters:

inX - 数据

Returns:

sigmoid函数

"""

def sigmoid(inX):

return 1.0 / (1 + np.exp(-inX))

"""

函数说明:梯度上升算法

Parameters:

dataMatIn - 数据集

classLabels - 数据标签

Returns:

weights.getA() - 求得的权重数组(最优参数)

"""

def gradAscent(dataMatIn, classLabels):

dataMatrix = np.mat(dataMatIn)#转换成numpy的matlabelMat = np.mat(classLabels).transpose()#转换成numpy的mat,并进行转置m, n = np.shape(dataMatrix)#返回dataMatrix的大小。m为行数,n为列数。alpha = 0.001#移动步长,也就是学习速率,控制更新的幅度。maxCycles = 500#最大迭代次数weights = np.ones((n,1))

for k in range(maxCycles):

h = sigmoid(dataMatrix * weights)#梯度上升矢量化公式error = labelMat - h

weights = weights + alpha * dataMatrix.transpose() * error

return weights.getA()#将矩阵转换为数组,返回权重数组

"""

函数说明:绘制数据集

Parameters:

Returns:

"""

def plotDataSet():

dataMat, labelMat = loadDataSet()#加载数据集dataArr = np.array(dataMat)#转换成numpy的array数组n = np.shape(dataMat)[0]#数据个数xcord1 = []; ycord1 = []#正样本xcord2 = []; ycord2 = []#负样本for i in range(n):#根据数据集标签进行分类if int(labelMat[i]) == 1:

xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])#1为正样本else:

xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])#0为负样本fig = plt.figure()

ax = fig.add_subplot(111)#添加subplotax.scatter(xcord1, ycord1, s = 20, c = 'red', marker = 's',alpha=.5)#绘制正样本ax.scatter(xcord2, ycord2, s = 20, c = 'green',alpha=.5)#绘制负样本plt.title('DataSet')#绘制titleplt.xlabel('X1'); plt.ylabel('X2')#绘制labelplt.show()#显示

"""

函数说明:绘制数据集

Parameters:

weights - 权重参数数组

Returns:

"""

def plotBestFit(weights):

dataMat, labelMat = loadDataSet()#加载数据集dataArr = np.array(dataMat)#转换成numpy的array数组n = np.shape(dataMat)[0]#数据个数xcord1 = []; ycord1 = []#正样本xcord2 = []; ycord2 = []#负样本for i in range(n):#根据数据集标签进行分类if int(labelMat[i]) == 1:

xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])#1为正样本else:

xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])#0为负样本fig = plt.figure()

ax = fig.add_subplot(111)#添加subplotax.scatter(xcord1, ycord1, s = 20, c = 'red', marker = 's',alpha=.5)#绘制正样本ax.scatter(xcord2, ycord2, s = 20, c = 'green',alpha=.5)#绘制负样本x = np.arange(-3.0, 3.0, 0.1)

y = (-weights[0] - weights[1] * x) / weights[2]

ax.plot(x, y)

plt.title('BestFit')#绘制titleplt.xlabel('X1'); plt.ylabel('X2')#绘制labelplt.show()

if __name__ == '__main__':

dataMat, labelMat = loadDataSet()

weights = gradAscent(dataMat, labelMat)

plotBestFit(weights)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值