LDA的实现

#!/usr/bin/python2
#-*-coding:UTF-8-*-

from numpy import *

#这里的posSet,negSet也是没有标签在末尾元素上的
def lda(posSet,negSet):    #The last element of one row is the label ! 0 or 1
    posMeanRow=mean(posSet,axis=0,keepdims=False)
    negMeanRow=mean(negSet,axis=0,keepdims=False)
    posSet-=posMeanRow;    negSet-=negMeanRow    #The rows of posSet and negSet are vectors which have been centralized !
    Sw=mat(posSet).T*mat(posSet)+mat(negSet).T*mat(negSet)
    U,S,VT=linalg.svd(Sw)    # S is kind of array which consists of singular values
    S=mat(diag(S))    # now S is of matrix type
    V=VT.T
    oppoS=S.I
    UT=U.T
    oppoSw=V*oppoS*UT    # Get the Sw^-1
    dfRow=posMeanRow-negMeanRow
    dfVecMat=mat(dfRow).T
    W=oppoSw*dfVecMat
    posCentVal=posMeanRow*W
    negCentVal=negMeanRow*W
    return W,posCentVal,negCentVal    #return the W,posMeanRow,negMeanRow

#W必须是矩阵类型
def ldaClassify(W,row,posCent,negCent):
    print "The shape of row : ",shape(row)
    print "The shape of W : ",shape(W)
    projectVal=row*W
    if abs(projectVal-posCent)<abs(projectVal-negCent):
        return 1    #离正样本的中心投影更近的话,认定为正样本,返回1作为测试样本的标签
    else:
        return 0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值