《机器学习》第三章——LDA
import numpy as np x=np.zeros((2,17)) y=np.zeros((1,17)) def dataload(filename): f=open(filename) ar=f.readlines() num=len(ar) ind=0 for line in ar: line.split('\n') linelist=line.split(' ') x[0:2,ind]=linelist[0:2] y[0:1,ind]=linelist[2:3] ind=ind+1 return dataload("1.txt") u0=np.zeros((2,1)) u1=np.zeros((2,1)) cnt0=0 cnt1=0 for i in range(17): for j in range(2): if(y[0,i]==1): u1[j,0]=u1[j,0]+x[j,i] cnt1=cnt1+1 else : u0[j,0]=u0[j,0]+x[j,i] cnt0=cnt0+1 for j in range(2): u1[j,0]=u1[j,0]/cnt1 u0[j,0]=u0[j,0]/cnt0 sigma0=np.zeros((2,2)) sigma1=np.zeros((2,2)) for i in range(17): tep=np.zeros((2,1)) for j in range(2): tep[j,0]=x[j,i] if(y[0,i]==1): sigma1=sigma1+np.dot((tep-u0),(tep-u0).T) else : sigma0=sigma0+np.dot((tep-u1),(tep-u1).T) Sw=np.zeros((2,2)) Sw=sigma0+sigma1 Sw=np.linalg.inv(Sw) w=np.dot(Sw,u0-u1) for i in range(17): tep=np.dot(w.T,x[:,i]) if(tep<=-0.01): print("1 ",y[0,i]) else : print("0 ",y[0,i])
额,这个数据集反正就是有几个特例,好气啊,欢迎指正错误!!