GDA是壹種生成學習法,主要利用貝葉斯準則得到後驗分布律,然後通過最大後驗分布對輸入數據進行分類。簡單地說,也就是在給定某個特征情況下,擁有此特征的數據屬於哪個類的概率大 就屬於哪個類。GDA的優勢:由於有高斯分布的先驗信息,如果確實符合實際數據,則只需要少量的樣本就可以得到較好的模型。
Logistic是壹種判別想學習法,判別學習法通過建立輸入數據與輸出信息之間的映射關系學得p(y|x),這個與生成學習法是不同的。在生成學習法中首先要確定p(x|y)和p(y)。Logistic主要是通過sigmoid函數來確定輸入數據及是將如何進行分類的。Logistic的優勢:具有更高的魯棒性和對數據的分布不明感(不想GDA那樣需要特征服從高斯分布)。
下面是具體的python代碼:
壹、GDA模型的python代碼:
點擊(此處)折疊或打開
def GDA(dataIn, classLabel):
m = len(classLabel);
sum_1 = sum(classLabel);
q = sum_1/(float(m));
notLabel = ones((len(classLabel),),dtype=int)-array(classLabel);
row,col = shape(dataIn);
y0x = y1x = mat(zeros(col));
for i in range(m):
y0x += mat(dataIn[i])*notLabel[i];
y1x += mat(dataIn[i])*classLabel[i];
mean_0 = y0x/(m-sum_1);
mean_1 = y1x/sum_1;
correlation = 0;
for i in range(m):
correlation += (mat(dataIn[i]-mean_0)).T*(mat(dataIn[i]-mean_0))*notLabel[i] \
+(mat(dataIn[i]-mean_1)).T*(mat(dataIn[i]-mean_1))*classLabel[i];
correlation = correlation/m;
return q,mean_0,mean_1,correlation;
def calculate_pxy0(x,n=2):
return ((2*math.pi)**(-n/2))*(linalg.det(correlation)**(-0.5))*exp(-0.5*(x-mean_0).T*correlation.I*(x-mean_0));
def calculate_pxy1(n=2):
return ((2*math.pi)**(-n/2))*(linalg.det(correlation)**(-0.5))*exp(-0.5*(x-mean_1).T*correlation.I*(x-mean_1));
def GDAClass(testPoint,dataIn,classLabel):
import math;
x = testPoint;
q,mean_0,mean_1,correlation = GDA(dataIn,classLabel);
n=shape(dataIn)[0];
py0 = 1-q;
py1 = q;
pxy0 = calculate_pxy0(x,n);
pxy1 = calculate_pxy1(x,n);
if pxy0*py0 > pxy1*py1:
return 0;
return 1;
二、Logistic模型的python代碼:
點擊(此處)折疊或打開
def sigmoid(w,x):
return 1/(1+exp(-w*x))
def logisticRegression(xMat,yMat,maxCycles = 500):
'''
ones((m,n)): 產生m維的向量,且每個值為n
'''
col = shape(xMat)[1];
weight = ones((col,1));
alpha = 0.001;
for j in range(maxCycles):
h = sigmoid(weight,xMat);
err = (yMat-h);
weight += alpha*xMat.transpose*err;
return weight;