當前位置:編程學習大全網 - 源碼下載 - GDA和Logistic方法的區別及相應的python代碼

GDA和Logistic方法的區別及相應的python代碼

GDA方法與Logistic方法的主要區別在於這兩個模型的假設不同:GDA方法假設p(x|y)服從多元高斯分布,並且輸入特征是連續的;Logistic方法並沒有GDA那麽強的假設,它既沒有要求p(x|y)服從多元高斯分布,也沒有要求輸入特征是連續的。因此Logistic的適用範圍比GDA更加廣泛。例如:如果輸入特征符合泊松分布,則Logistic得到的結果會比GDA更加準確。如果輸入特征滿足GDA的要求時,既可以用Logistic方法也可以用GDA,但是在這種情況下GDA得到的結果會比Logistic方法得到的結果準確些。下面給出GDA和Logistic方法的簡要說明,最後給出相應的 python代碼。

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;

  • 上一篇:Android模塊化設計方案之使用代理模式解耦
  • 下一篇:SecurityContextHolder.getContext().getAuthentication()為什麽Security3.1和2.0執行上面語句結果不同?
  • copyright 2024編程學習大全網