Logistic回归之梯度上升优化算法(三)

Logistic回归之梯度上升优化算法(三)

1、改进的随机梯度上升算法

前面两节讲了Logistic回归以及里面常用的梯度上升优化算法来找到最佳回归系数。但是梯度上升优化算法的计算量很大,每次更新回归系数时都需要遍历整个数据集。下面给出之前所讲的梯度上升算法:

def gradAscent(dataMatIn, classLables):
    dataMatrix = np.mat(dataMatIn)  #转换成numpy的mat
    # print(dataMatrix)
    labelMat =  np.mat(classLables).transpose() #转换成numpy的mat,并进行转置
    # print(labelMat)
    m, n =np.shape(dataMatrix)#返回dataMatrix的大小。m为行,n为列
    alpha = 0.001  #移动补偿,也就是学习速率,控制更新的幅度
    maxCycles = 500 #最大迭代次数
    weights = np.ones((n,1))
    # print(weights)
    for k in range(maxCycles):
        h = sigmoid(dataMatrix *weights) #梯度上升矢量公式
        # print(h)
        error = labelMat - h
        weights = weights + alpha * dataMatrix.transpose()*error
    return weights.getA()  #将矩阵转换为数组,返回权重数组

该算法在对一个100个样本的数据集处理时,dataMatrix是一个100*3的矩阵,每次计算h的时候,都要计算dataMatrix*weights这个矩阵乘法运算,要进行100*3次乘法运算和100*2次加法运算。在更新weights时也需要对整个数据集进行处理,对于大样本是不可取的,为此使用一种随机梯度上升算法来简化算法。

1.1、随机梯度上升算法

我们直接给出代码:

def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = np.shape(dataMatrix) #返回dataMatrix的大小 m为行数 n为列数
    weights = np.ones(n) #[1. 1. 1.] 初始化参数 类型是array所以注意dataMatrix类型也应该是np.array

    for j in range(numIter):
        dataIndex = list(range(m))  # [0,1,...99]
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.01 #降低alpha的大小,每次减小1/(j+i)
            randIndex = int(random.uniform(0,len(dataIndex)))#随机选取样本
            h = sigmoid(sum(dataMatrix[randIndex]*weights))#选择随机选取的一个样本,计算h。对应位置相乘求和
            error = classLabels[randIndex] - h
            weights = weights+ alpha* error*dataMatrix[randIndex]#更新回归系数
            del(dataIndex[randIndex])#删除已经使用的样本
    return weights

该算法主要是在以下两方面做了改进。第一,alpha在每次迭代的时候都会调整,随着迭代次数不断减小,但永远不会减小到0。这样做的原因是为了保证在多次迭代之后新数据仍然具有一定的影响。如果要处理的问题是动态变化的,那么可以适当加大上述常数项,来确保新的值获得更大的回归系数。而且在降低alpha的函数中,alpha每次减少1/(j+i),其中j是迭代次数,i是样本的下标。这样当j<<max(i)时,alpha就不是严格下降的。避免参数的严格下降也常见于模拟退火算法等其他优化算法中。第二,这里通过每次随机选取一个样本来更新回归系数。这种方法可以有效的减少周期性的波动。

代码如下:

import matplotlib.pyplot as plt
import numpy as np
import random
from matplotlib.font_manager import FontProperties
'''
函数说明:加载数据
Parameters:
    None
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  # 返回
'''
函数说明:绘制数据集
Parameters:
    None
Returns:
    None
'''
def plotDataSet(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: #1为正样本
            xcord1.append(dataMat[i][1])
            ycord1.append(dataMat[i][2])
            # xcord1.append(dataArr[i, 1]);ycord1.append(dataArr[i, 2])
        else:                     #0为负样本
            xcord2.append(dataMat[i][1])
            ycord2.append(dataMat[i][2])
            # xcord2.append(dataArr[i, 1]);ycord2.append(dataArr[i, 2])
    fig = plt.figure()
    ax = fig.add_subplot(111)   #添加subplot
    ax.scatter(xcord1,ycord1,s=20,c='red',marker = 's', alpha=.5,label ='1') #绘制正样本
    ax.scatter(xcord2,ycord2,s=20,c='green',marker = 's', alpha=.5,label ='0') #绘制正样本
    x = np.arange(-3.0,3.0,0.1)
    y = (-weights[0] - weights[1] * x) / weights[2]
    ax.plot(x,y)
    plt.title('DataSet') #绘制title
    plt.xlabel('x'); plt.ylabel('y') #绘制label
    plt.legend()
    plt.show()
'''
函数说明:sigmodi函数
Paremeters:
    inX - 数据
Returns:
    sigmoid函数
'''
def sigmoid(inX):
    return 1.0/(1 + np.exp(-inX))
'''
函数说明:梯度上升算法
Parameters:
    dataMatIn - 数据集
    classLables - 数据标签
Returns:
    weights.getA() - 求得的权重数组(最优参数)
'''
# def gradAscent(dataMatIn, classLables):
#     dataMatrix = np.mat(dataMatIn)  #转换成numpy的mat
#     # print(dataMatrix)
#     labelMat =  np.mat(classLables).transpose() #转换成numpy的mat,并进行转置
#     # print(labelMat)
#     m, n =np.shape(dataMatrix)#返回dataMatrix的大小。m为行,n为列
#     alpha = 0.001  #移动补偿,也就是学习速率,控制更新的幅度
#     maxCycles = 500 #最大迭代次数
#     weights = np.ones((n,1))
#     # print(weights)
#     for k in range(maxCycles):
#         h = sigmoid(dataMatrix *weights) #梯度上升矢量公式
#         # print(h)
#         error = labelMat - h
#         weights = weights + alpha * dataMatrix.transpose()*error
#     return weights.getA()  #将矩阵转换为数组,返回权重数组
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = np.shape(dataMatrix) #返回dataMatrix的大小 m为行数 n为列数
    weights = np.ones(n) #[1. 1. 1.] 初始化参数 类型是array所以注意dataMatrix类型也应该是np.array
    for j in range(numIter):
        dataIndex = list(range(m))  # [0,1,...99]
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.01 #降低alpha的大小,每次减小1/(j+i)
            randIndex = int(random.uniform(0,len(dataIndex)))#随机选取样本
            h = sigmoid(sum(dataMatrix[randIndex]*weights))#选择随机选取的一个样本,计算h。对应位置相乘求和
            error = classLabels[randIndex] - h
            weights = weights+ alpha* error*dataMatrix[randIndex]#更新回归系数
            del(dataIndex[randIndex])#删除已经使用的样本
    return weights
if __name__ == '__main__':
    np.set_printoptions(suppress=True)#关闭科学技术法
    dataMat,labelMat = loadDataSet()
    weights = stocGradAscent1(np.array(dataMat),labelMat)
    plotDataSet(weights)

代码运行结果:

1.2、回归系数与迭代次数的关系

可以看出随机梯度算法得到的回归系数与初始结果所差无几。接下来我们研究迭代次数和回归系数的关系。

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np
import random
'''
函数说明:加载数据
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 - 数据集
    classLables - 数据标签
Returns:
    weight.getA() -  求得的权重数组(最优参数)
    weight_array - 每次更新的回归系数
'''
def gradAscent(dataMatIn ,classLabels):
    dataMatrix = np.mat(dataMatIn) #转换成numpy的mat
    labelMat = np.mat(classLabels).transpose()#转换成numpy的mat并进行转置
    m,n = np.shape(dataMatrix)#获得dataMatrix的行列
    alpha = 0.01
    maxCycles = 500
    weights = np.ones((n,1))
    weights_array = np.array([])
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights)
        error = labelMat - h
        weights = weights + alpha * dataMatrix.transpose() * error
        weights_array = np.append(weights_array,weights)#把weights插入weights_array最后面
    weights_array = weights_array.reshape(maxCycles,n)
    return weights.getA(), weights_array#将矩阵转换为数组并返回
'''
函数说明:改进的随机梯度上升算法
Parameters:
    dataMatrix - 数据数组
    classLabels - 数据标签
Returns:
    weights - 求得的回归系数数组(最优参数)
    weights_array - 每次更新的回归系数
'''
def stocGradAscent1(dataMatrix ,classLabels,numIter=150):
    m,n = np.shape(dataMatrix)#返回dataMatrix的大小
    weights = np.ones(n) #参数初始化
    weights_array = np.array([]) #存储每次更新的回归系数
    for j in range(numIter):
        dataIndex = list(range(m))
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.01#降低alpha的大小
            randIndex = int(random.uniform(0,len(dataIndex)))#随机选取样本
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            weights_array = np.append(weights_array,weights,axis = 0)
            del(dataIndex[randIndex])
    weights_array = weights_array.reshape(numIter*m,n)
    return weights,weights_array
'''
函数说明:绘制回归系数与迭代次数的关系
Parameters:
    weights_array1 - 回归系数数组1
    weights_array2 - 回归系数数组2
Returns:
    None
'''
def plotWeihts(weights_array1,weights_array2):
    #设置汉子格式
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
    #将fig画布分割成1行1列,不共享x轴和y轴,fig画布的大小为(13,8)
    #讲nrow=3,nclos=2时,代表fig画布被分成6个区域,axs[0][0]表示第一行第一列
    fig,axs = plt.subplots(nrows=3,ncols=2,sharex=False,sharey=False,figsize=(20,10))
    x1 = np.arange(0,len(weights_array1))#等差数列
    #绘制w0与迭代次数的关系
    axs[0][0].plot(x1,weights_array1[:,0]) #每一行的第一个元素
    axs0_title_text = axs[0][0].set_title('梯度上升算法:回归系数与迭代次数关系',FontProperties=font)
    axs0_ylabel_text = axs[0][0].set_ylabel('W0',FontProperties=font)
    plt.setp(axs0_title_text,size=20,weight='bold',color = 'black')
    plt.setp(axs0_ylabel_text,size=20,weight='bold',color = 'black')
  #绘制w1与迭代次数的关系
    axs[1][0].plot(x1,weights_array1[:,1]) #每一行的第一个元素
    axs0_ylabel_text = axs[1][0].set_ylabel('W1',FontProperties=font)
    plt.setp(axs0_ylabel_text,size=20,weight='bold',color = 'black')
  #绘制w2与迭代次数的关系
    axs[2][0].plot(x1,weights_array1[:,2]) #每一行的第一个元素
    axs0_xlabel_text = axs[2][0].set_xlabel('迭代次数',FontProperties=font)
    axs0_ylabel_text = axs[2][0].set_ylabel('W2',FontProperties=font)
    plt.setp(axs0_xlabel_text,size=20,weight='bold',color = 'black')
    plt.setp(axs0_ylabel_text,size=20,weight='bold',color = 'black')

    x2 = np.arange(0, len(weights_array2))
    # 绘制w0与迭代次数的关系
    axs[0][1].plot(x2, weights_array2[:, 0])
    axs0_title_text = axs[0][1].set_title(u'改进的随机梯度上升算法:回归系数与迭代次数关系', FontProperties=font)
    axs0_ylabel_text = axs[0][1].set_ylabel(u'W0', FontProperties=font)
    plt.setp(axs0_title_text, size=20, weight='bold', color='black')
    plt.setp(axs0_ylabel_text, size=20, weight='bold', color='black')
    # 绘制w1与迭代次数的关系
    axs[1][1].plot(x2, weights_array2[:, 1])
    axs1_ylabel_text = axs[1][1].set_ylabel(u'W1', FontProperties=font)
    plt.setp(axs1_ylabel_text, size=20, weight='bold', color='black')
    # 绘制w2与迭代次数的关系
    axs[2][1].plot(x2, weights_array2[:, 2])
    axs2_xlabel_text = axs[2][1].set_xlabel(u'迭代次数', FontProperties=font)
    axs2_ylabel_text = axs[2][1].set_ylabel(u'W2', FontProperties=font)
    plt.setp(axs2_xlabel_text, size=20, weight='bold', color='black')
    plt.setp(axs2_ylabel_text, size=20, weight='bold', color='black')
    plt.show()
if __name__ == '__main__':
    dataMat , labelMat = loadDataSet()
    weights1,weights_array1 = gradAscent(dataMat,labelMat)
    weights2, weights_array2 = stocGradAscent1(np.array(dataMat), labelMat)
    plotWeihts(weights_array1,weights_array2)




运行结果如下:

由于改进的随机梯度上升算法,随机选取样本点,所以每次的运行结果有些不同但是大体趋势是一样的。从图中我们可以看出随机梯度上升算法的瘦脸效果更好。我们一共有100个样本点,改进的随机梯度上升算法迭代次数为150.而上图显示150000次迭代次数的原因是,使用一次样本就更新一下回归系数,要迭代150次。所以150*100=150000次。迭代150次,更新1.5万次回归参数。从右图我们可以知道基本迭代2000次即迭代20次回归系数已经收敛了,比初始算法收敛要更快一些。

参考文献:

猜你喜欢

转载自blog.csdn.net/qq_25174673/article/details/83962411
今日推荐