GDA和Logistic方法的区别及相应的python代码

6160阅读 0评论2014-04-15 bl竹子
分类:大数据

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代码:

点击(此处)折叠或打开

  1. def GDA(dataIn, classLabel):
  2.     m = len(classLabel);
  3.     sum_1 = sum(classLabel);
  4.     q = sum_1/(float(m));
  5.     notLabel = ones((len(classLabel),),dtype=int)-array(classLabel);
  6.     row,col = shape(dataIn);
  7.     y0x = y1x = mat(zeros(col));
  8.     for i in range(m):
  9.         y0x += mat(dataIn[i])*notLabel[i];
  10.         y1x += mat(dataIn[i])*classLabel[i];
  11.     mean_0 = y0x/(m-sum_1);
  12.     mean_1 = y1x/sum_1;
  13.     correlation = 0;
  14.     for i in range(m):
  15.             correlation += (mat(dataIn[i]-mean_0)).T*(mat(dataIn[i]-mean_0))*notLabel[i] \
  16.             +(mat(dataIn[i]-mean_1)).T*(mat(dataIn[i]-mean_1))*classLabel[i];
  17.     correlation = correlation/m;
  18.     return q,mean_0,mean_1,correlation;
  19. def calculate_pxy0(x,n=2):
  20.     return ((2*math.pi)**(-n/2))*(linalg.det(correlation)**(-0.5))*exp(-0.5*(x-mean_0).T*correlation.I*(x-mean_0));
  21. def calculate_pxy1(n=2):
  22.     return ((2*math.pi)**(-n/2))*(linalg.det(correlation)**(-0.5))*exp(-0.5*(x-mean_1).T*correlation.I*(x-mean_1));
  23. def GDAClass(testPoint,dataIn,classLabel):
  24.     import math;
  25.     x = testPoint;
  26.     q,mean_0,mean_1,correlation = GDA(dataIn,classLabel);
  27.     n=shape(dataIn)[0];
  28.     py0 = 1-q;
  29.     py1 = q;
  30.     pxy0 = calculate_pxy0(x,n);
  31.     pxy1 = calculate_pxy1(x,n);
  32.     if pxy0*py0 > pxy1*py1:
  33.         return 0;
  34.     return 1;
二、Logistic模型的python代码

点击(此处)折叠或打开

  1. def sigmoid(w,x):
  2.     return 1/(1+exp(-w*x))

  3. def logisticRegression(xMat,yMat,maxCycles = 500):
  4.     '''
  5.         ones((m,n)): 产生m维的向量,且每个值为n
  6.     '''
  7.     col = shape(xMat)[1];
  8.     weight = ones((col,1));
  9.     alpha = 0.001;
  10.     for j in range(maxCycles):
  11.         h = sigmoid(weight,xMat);
  12.         err = (yMat-h);
  13.         weight += alpha*xMat.transpose*err;
  14.     return weight;
本文出处:http://blog.chinaunix.net/uid-28311809-id-4211362.html
上一篇:编程之美---格格取数问题的贪心解法
下一篇:Gnuplot功能总结