一.基於Logistic迴歸和Sigmoid函數的分類
優點:計算代價不高,易於理解和實現
缺點:容易欠擬合,分類精度可能不高
適用數據類型:數值型和標稱型數據
1.1邏輯斯諦分佈
分佈函數爲:
密度函數爲:
其中,
邏輯斯諦分佈的密度函數
邏輯斯諦函數的分佈函數是一條S形曲線(sigmoid curve),該曲線以點
曲線在中心附近增長速度較快,在兩端增長速度較慢,形狀參數
1.2基於最優化方法的最佳迴歸係數確定
sigmoid函數的輸入記爲z,則sigmoid函數爲:
其中
1.3二項邏輯斯諦迴歸模型
二項邏輯斯諦迴歸模型(binomial logistic regression model)是一種分類模型,由條件概率
定義(邏輯斯諦迴歸模型)二項邏輯斯諦迴歸模型是如下的條件概率分佈:
這裏,
一個事件的機率(odds)是指該事件發生的概率與該事件不發生的概率的比值。如果
也就是說,在邏輯斯諦迴歸模型中,輸出
1.4模型參數估計
邏輯斯諦迴歸模型學習時,對於給定的訓練數據集
似然函數爲:
1.3梯度算法
利用梯度算法的迭代公式
利用偏微分公式給係數
1.4 訓練算法:使用梯度算法求最佳參數
給出100個樣本點,每個點包含兩個數值型特徵,每個迴歸係數初始化爲1
重複R次:
計算整個數據集的梯度
使用
返回迴歸係數
1.5 Python算法
創建logRegres.py文件
from numpy import *
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]))
return dataMat,labelMat
def sigmoid(inX):
return 1.0/(1+exp(-inX))
def gradAscent(dataMatIn,classLabels):
dataMatrix=mat(dataMatIn)
labelMat=mat(classLabels).transpose()
m,n=shape(dataMatrix)
alpha=0.001
maxCycles=500
weights=ones((n,1))
for k in range(maxCycles):
h=sigmoid(dataMatrix*weights)
error=(labelMat-h)
weights=weights+alpha*dataMatrix.transpose()*error
return weights
在python提示符下,敲入下面的代碼:
>>>import logRegres
>>>dataAr,labelMat=logRegres.loadDataSet()
>>>logRegres.gradAscent(dataArr,labelMat)
結果爲
matrix([[4.12414349],
[0.48007329],
[-0.6168482]])
def plotBestFit(wei):
import matplotlib.pyplot as plt
weights=wei.getA()
dataMat,labelMat=loadDataSet()
dataArr=array(dataMat)
n=shape(dataArr)[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])
else:
xcord2.append(dataArr[i,1])
ycord2.append(dataArr[i,2])
fig=plt.figure()
ax=fig.add_subplot(111)
ax.scatter(xcord1,ycord1,s=30,c='red',marker='s')
ax.scatter(xcord2,ycord2,s=30,c='green')
x=arange(-3.0,3.0,0.1)
y=(-weights[0]-weights[1]*x)/weights[2]
ax.plot(x,y)
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
1.6 C++算法
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <stdio.h>
#include <algorithm>
#include <cmath>
using namespace std;
void loadDataset(vector<vector<double>> &dataMat,vector<int> &labelMat,const string &filename)
{
ifstream file(filename);
string line;
while(getline(file,line))
{
vector<double> data;
double x1,x2;
int label;
sscanf(line.c_str(),"%lf %lf %d",&x1,&x2,&label);
data.push_back(1);
data.push_back(x1);
data.push_back(x2);
dataMat.push_back(data);
labelMat.push_back(label);
}
}
double scalarProduct(vector<double> &w,vector<double> &x)
{
double ret=0;
for(int i=0;i<w.size();i++)
ret+=w[i]*x[i];
return ret;
}
double sigmoid(double z)
{
return exp(z)/(1+exp(z));
}
vector<vector<double>> matTranspose(vector<vector<double>> &dataMat)
{
vector<vector<double>> ret(dataMat[0].size(),vector<double>(dataMat.size(),0));
for(int i=0;i<ret.size();i++)
for(int j=0;j<ret[0].size();j++)
ret[i][j]=dataMat[j][i];
return ret;
}
void gradAscent(vector<double> &weight,
vector<vector<double>> &dataMat,vector<int> &labelMat)
{
int maxCycles=500;
double alpha=0.001;
vector<vector<double>> dataMatT=matTranspose(dataMat);
while(maxCycles>0)
{
vector<double> h;
vector<double> error;
for(auto &data:dataMat)
h.push_back(sigmoid(scalarProduct(data,weight)));
for(int i=0;i<labelMat.size();i++)
error.push_back(labelMat[i]-h[i]);
for(int i=0;i<weight.size();i++)
weight[i]+=alpha*scalarProduct(dataMatT[i],error);
maxCycles--;
}
}
int main()
{
vector<vector<double>> dataMat;
vector<int> labelMat;
string filename("testSet.txt");
loadDataset(dataMat,labelMat,filename);
vector<double> weight(dataMat[0].size(),1);
gradAscent(weight,dataMat,labelMat);
for(auto v:weight)
cout<<v<<endl;
}
1.7 隨機梯度
梯度算法在每次更新迴歸係數時需要遍歷整個數據集,如果樣本數和特徵數太多,則該方法的計算複雜度就太高了,一種改進方法是一次僅用一個樣本點來更新迴歸係數,該方法稱爲隨機梯度上升算法,由於可以在新樣本到來時對分類器進行增量式更新,因而隨機梯度上升算法是一個在線學習算法,與“在線學習相對應”,一次處理所有數據被稱作是“批處理”
隨機梯度上升算法:
所有迴歸係數初始化爲1
對數據集中每個樣本
計算該樣本的梯度
使用
返回迴歸係數
1.8 隨機梯度上升算法的Python實現
1.8.1 未優化的隨機梯度算法
def stocGradAscent0(dataMatrix,classLabels):
m,n=shape(dataMatrix)
alpha=0.01
weights=ones(n)
for i in range(m):
h=sigmoid(sum(dataMatrix[i]*weights))
error=classLabels[i]-h
weights=weights+alpha*error*dataMatrix[i]
return weights
分類效果:
可以看到,分類的效果並不像前面那麼完美,但前者是在整個數據集上迭代了500次纔得到的,而此算法只是遍歷了一遍訓練數據。
一個判斷優化算法優劣的可靠方法是看它是否收斂,我們對上述的梯度上升算法進行修改,使其在整個數據集上運行50次即可發現分類效果大幅度改進
1.8.2 一種改進措施
def stocGradAscent1(dataMatrix,classLabels,numIter=150):
m,n=shape(dataMatrix)
weights=ones(n)
for j in range(numIter):
dataIndex=range(m)
for i in range(m):
alpha=4/(1.0+j+i)+0.01
randIndex=int(random.uniform(0,len(dataIndex)))
h=sigmoid(sum(dataMatrix[randIndex]*weights))
error=classLabels[randIndex]-h
weights=weights+alpha*error*dataMatrix[randIndex]
del(dataIndex[randIndex])
return weights
第一處改進是alpha在每次迭代的時候都會調整,可以避免數據波動。
第二處改進是隨機選取樣本來更新迴歸係數,這種方法可以減少週期性的波動
1.9 隨機梯度算法的C++實現
void stocGradAscent(vector<double> &weight,
vector<vector<double>> &dataMat,vector<int> &labelMat,int numIter=150)
{
double alpha=0.01;
double h=0.0;
int i=0;
int j=0;
double error=0.0;
vector<int> randIndex;
for(i=0;i<dataMat.size();i++)
randIndex.push_back(i);
for(int k=0;k<numIter;k++)
{
random_shuffle(randIndex.begin(),randIndex.end());
for(i=0;i<dataMat.size();i++)
{
alpha=4/(1+k+i)+0.01;
h=sigmoid(scalarProduct(dataMat[randIndex[i]],weight));
error=labelMat[randIndex[i]]-h;
for(j=0;j<weight.size();j++)
{
weight[j]+=alpha*error*dataMat[randIndex[i]][j];
}
}
}
}
2.0訓練數據
-0.017612 14.053064 0
-1.395634 4.662541 1
-0.752157 6.538620 0
-1.322371 7.152853 0
0.423363 11.054677 0
0.406704 7.067335 1
0.667394 12.741452 0
-2.460150 6.866805 1
0.569411 9.548755 0
-0.026632 10.427743 0
0.850433 6.920334 1
1.347183 13.175500 0
1.176813 3.167020 1
-1.781871 9.097953 0
-0.566606 5.749003 1
0.931635 1.589505 1
-0.024205 6.151823 1
-0.036453 2.690988 1
-0.196949 0.444165 1
1.014459 5.754399 1
1.985298 3.230619 1
-1.693453 -0.557540 1
-0.576525 11.778922 0
-0.346811 -1.678730 1
-2.124484 2.672471 1
1.217916 9.597015 0
-0.733928 9.098687 0
-3.642001 -1.618087 1
0.315985 3.523953 1
1.416614 9.619232 0
-0.386323 3.989286 1
0.556921 8.294984 1
1.224863 11.587360 0
-1.347803 -2.406051 1
1.196604 4.951851 1
0.275221 9.543647 0
0.470575 9.332488 0
-1.889567 9.542662 0
-1.527893 12.150579 0
-1.185247 11.309318 0
-0.445678 3.297303 1
1.042222 6.105155 1
-0.618787 10.320986 0
1.152083 0.548467 1
0.828534 2.676045 1
-1.237728 10.549033 0
-0.683565 -2.166125 1
0.229456 5.921938 1
-0.959885 11.555336 0
0.492911 10.993324 0
0.184992 8.721488 0
-0.355715 10.325976 0
-0.397822 8.058397 0
0.824839 13.730343 0
1.507278 5.027866 1
0.099671 6.835839 1
-0.344008 10.717485 0
1.785928 7.718645 1
-0.918801 11.560217 0
-0.364009 4.747300 1
-0.841722 4.119083 1
0.490426 1.960539 1
-0.007194 9.075792 0
0.356107 12.447863 0
0.342578 12.281162 0
-0.810823 -1.466018 1
2.530777 6.476801 1
1.296683 11.607559 0
0.475487 12.040035 0
-0.783277 11.009725 0
0.074798 11.023650 0
-1.337472 0.468339 1
-0.102781 13.763651 0
-0.147324 2.874846 1
0.518389 9.887035 0
1.015399 7.571882 0
-1.658086 -0.027255 1
1.319944 2.171228 1
2.056216 5.019981 1
-0.851633 4.375691 1
-1.510047 6.061992 0
-1.076637 -3.181888 1
1.821096 10.283990 0
3.010150 8.401766 1
-1.099458 1.688274 1
-0.834872 -1.733869 1
-0.846637 3.849075 1
1.400102 12.628781 0
1.752842 5.468166 1
0.078557 0.059736 1
0.089392 -0.715300 1
1.825662 12.693808 0
0.197445 9.744638 0
0.126117 0.922311 1
-0.679797 1.220530 1
0.677983 2.556666 1
0.761349 10.693862 0
-2.168791 0.143632 1
1.388610 9.341997 0
0.317029 14.739025 0