机器学习笔记索引

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Logistic回归算法优缺点:

1.计算代价不高,易于理解和实现

2.容易欠拟合,分类精度可能不高

3.适用数据类型:数值型和标称型

算法思想:其实就我的理解来说,logistic回归实际上就是加了个sigmoid函数的线性回归,这个sigmoid函数的好处就在于,将结果归到了0到1这个区间里面了,并且sigmoid(0)=0.5,也就是说里面的线性部分的结果大于零小于零就可以直接计算到了。这里的求解方式是梯度上升法,具体我就不扯了,最推荐的资料还是Ng的视频,那里面的梯度下降就是啦,只不过一个是梯度上升的方向一个是下降的方向,做法什么的都一样。而梯度上升(准确的说叫做“批梯度上升”)的一个缺点就是计算量太大了,每一次迭代都需要把所有的数据算一遍,这样一旦训练集大了之后,那么计算量将非常大,所以这里后面还提出了随机梯度下降,思想就是每次只是根据一个data进行修正。这样得到的最终的结果可能会有所偏差但是速度却提高了很多,而且优化之后的偏差还是很小的。随机梯度上升的另一个好处是这是一个在线算法,可以根据新数据的到来不断处理函数:loadDataSet()

创建数据集,这里的数据集就是在一个文件中,这里面有三行,分别是两个特征和一个标签,但是我们在读出的时候还加了X0这个属性

sigmoid(inX)

sigmoid函数的计算,这个函数长这样的,基本坐标大点就和阶跃函数很像了

gradAscend(dataMatIn, classLabels)

梯度上升算法的实现,里面用到了numpy的数组,并且设定了迭代次数500次,然后为了计算速度都采取了矩阵计算,计算的过程中的公式大概是:w= w+alpha*(y-h)x[i](一直懒得写公式,见谅。。。)

gradAscendWithDraw(dataMatIn, classLabels)

上面的函数加强版,增加了一个weight跟着迭代次数的变化曲线

stocGradAscent0(dataMatrix, classLabels)

这里为了加快速度用来随机梯度上升,即每次根据一组数据调整(额,好吧,这个际没有随机因为那是线面那个函数)

stocGradAscentWithDraw0(dataMatrix, classLabels)

上面的函数加强版,增加了一个weight跟着迭代次数的变化曲线

stocGradAscent1(dataMatrix, classLabels, numIter=150)

这就真的开始随机了,随机的主要好处是减少了周期性的波动了。另外这里还加入了alpha的值随迭代变化,这样可以让alpha的值不断的变化,但是都不会减小到0。

stocGradAscentWithDraw1(dataMatrix, classLabels, numIter=150)

上面的函数加强版,增加了一个weight跟着迭代次数的变化曲线

plotBestFit(wei)

根据计算的weight值画出拟合的线,直观观察效果

运行效果分析:

1、梯度上升:

迭代变化趋势

分类结果:

2、随机梯度上升版本1

迭代变化趋势

分类结果:

这个速度虽然快了很多但是效果不太理想啊。不过这个计算量那么少,我们如果把这个迭代200次肯定不一样了,效果如下

果然好多了

3、随机梯度上升版本2

迭代变化趋势

分类结果:

恩,就是这样啦,效果还是不错的啦。代码的画图部分写的有点烂,见谅啦

1#coding=utf-82fromnumpyimport*34defloadDataSet():5dataMat =[]6labelMat =[]7fr = open('testSet.txt')8forlineinfr.readlines():9lineArr =line.strip().split()10dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])11labelMat.append(int(lineArr[2]))12returndataMat, labelMat1314defsigmoid(inX):15return1.0/(1+exp(-inX))1617defgradAscend(dataMatIn, classLabels):18dataMatrix =mat(dataMatIn)19labelMat =mat(classLabels).transpose()20m,n =shape(dataMatrix)21alpha = 0.00122maxCycle = 50023weight = ones((n,1))24forkinrange(maxCycle):25h = sigmoid(dataMatrix*weight)26error = labelMat -h27weight += alpha * dataMatrix.transpose() *error28#plotBestFit(weight)29returnweight3031defgradAscendWithDraw(dataMatIn, classLabels):32importmatplotlib.pyplot as plt33fig =plt.figure()34ax = fig.add_subplot(311,ylabel='x0')35bx = fig.add_subplot(312,ylabel='x1')36cx = fig.add_subplot(313,ylabel='x2')37dataMatrix =mat(dataMatIn)38labelMat =mat(classLabels).transpose()39m,n =shape(dataMatrix)40alpha = 0.00141maxCycle = 50042weight = ones((n,1))43wei1 =[]44wei2 =[]45wei3 =[]46forkinrange(maxCycle):47h = sigmoid(dataMatrix*weight)48error = labelMat -h49weight += alpha * dataMatrix.transpose() *error50wei1.extend(weight[0])51wei2.extend(weight[1])52wei3.extend(weight[2])53ax.plot(range(maxCycle), wei1)54bx.plot(range(maxCycle), wei2)55cx.plot(range(maxCycle), wei3)56plt.xlabel('iter_num')57plt.show()58returnweight5960defstocGradAscent0(dataMatrix, classLabels):61m,n =shape(dataMatrix)6263alpha = 0.00164weight =ones(n)65foriinrange(m):66h = sigmoid(sum(dataMatrix[i]*weight))67error = classLabels[i] -h68weight = weight + alpha * error *dataMatrix[i]69returnweight7071defstocGradAscentWithDraw0(dataMatrix, classLabels):72importmatplotlib.pyplot as plt73fig =plt.figure()74ax = fig.add_subplot(311,ylabel='x0')75bx = fig.add_subplot(312,ylabel='x1')76cx = fig.add_subplot(313,ylabel='x2')77m,n =shape(dataMatrix)7879alpha = 0.00180weight =ones(n)81wei1 =array([])82wei2 =array([])83wei3 =array([])84numIter = 20085forjinrange(numIter):86foriinrange(m):87h = sigmoid(sum(dataMatrix[i]*weight))88error = classLabels[i] -h89weight = weight + alpha * error *dataMatrix[i]90wei1 =append(wei1, weight[0])91wei2 =append(wei2, weight[1])92wei3 =append(wei3, weight[2])93ax.plot(array(range(m*numIter)), wei1)94bx.plot(array(range(m*numIter)), wei2)95cx.plot(array(range(m*numIter)), wei3)96plt.xlabel('iter_num')97plt.show()98returnweight99100defstocGradAscent1(dataMatrix, classLabels, numIter=150):101m,n =shape(dataMatrix)102103#alpha = 0.001104weight =ones(n)105forjinrange(numIter):106dataIndex =range(m)107foriinrange(m):108alpha = 4/ (1.0+j+i) +0.01109randIndex =int(random.uniform(0,len(dataIndex)))110h = sigmoid(sum(dataMatrix[randIndex]*weight))111error = classLabels[randIndex] -h112weight = weight + alpha * error *dataMatrix[randIndex]113del(dataIndex[randIndex])114returnweight115116defstocGradAscentWithDraw1(dataMatrix, classLabels, numIter=150):117importmatplotlib.pyplot as plt118fig =plt.figure()119ax = fig.add_subplot(311,ylabel='x0')120bx = fig.add_subplot(312,ylabel='x1')121cx = fig.add_subplot(313,ylabel='x2')122m,n =shape(dataMatrix)123124#alpha = 0.001125weight =ones(n)126wei1 =array([])127wei2 =array([])128wei3 =array([])129forjinrange(numIter):130dataIndex =range(m)131foriinrange(m):132alpha = 4/ (1.0+j+i) +0.01133randIndex =int(random.uniform(0,len(dataIndex)))134h = sigmoid(sum(dataMatrix[randIndex]*weight))135error = classLabels[randIndex] -h136weight = weight + alpha * error *dataMatrix[randIndex]137del(dataIndex[randIndex])138wei1 =append(wei1, weight[0])139wei2 =append(wei2, weight[1])140wei3 =append(wei3, weight[2])141ax.plot(array(range(len(wei1))), wei1)142bx.plot(array(range(len(wei2))), wei2)143cx.plot(array(range(len(wei2))), wei3)144plt.xlabel('iter_num')145plt.show()146returnweight147148defplotBestFit(wei):149importmatplotlib.pyplot as plt150weight =wei151dataMat,labelMat =loadDataSet()152dataArr =array(dataMat)153n =shape(dataArr)[0]154xcord1 =[]155ycord1 =[]156xcord2 =[]157ycord2 =[]158foriinrange(n):159ifint(labelMat[i]) == 1:160xcord1.append(dataArr[i,1])161ycord1.append(dataArr[i,2])162else:163xcord2.append(dataArr[i,1])164ycord2.append(dataArr[i,2])165fig =plt.figure()166ax = fig.add_subplot(111)167ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')168ax.scatter(xcord2, ycord2, s=30, c='green')169x = arange(-3.0, 3.0, 0.1)170y = (-weight[0] - weight[1]*x)/weight[2]171ax.plot(x,y)172plt.xlabel('X1')173plt.ylabel('X2')174plt.show()175176defmain():177dataArr,labelMat =loadDataSet()178#w = gradAscendWithDraw(dataArr,labelMat)179w =stocGradAscentWithDraw0(array(dataArr),labelMat)180plotBestFit(w)181182if__name__=='__main__':183main()

机器学习笔记索引

来自为知笔记(Wiz)

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航