回复 第2楼 的 nan.xiao:
代码有点长:
主程序:
</p>
<p>### test_lfda.r<br />
source("D:/lfda.r")</p>
<p>### 生成样本数据<br />
n1a=100<br />
n1b=100<br />
n2=100<br />
A=matrix(c(1,2),nrow=2)<br />
B=matrix(c(-6,0),nrow=2)<br />
C=matrix(c(6,0),nrow=2)<br />
D=matrix(c(0,0),nrow=2)</p>
<p>rand_1a=matrix(rnorm(2*n1a),2,n1a)<br />
rep_1a=matrix(rep(A,n1a),2,n1a,byrow=FALSE)<br />
rep_2a=matrix(rep(B,n1a),2,n1a,byrow=FALSE)<br />
X1a=rand_1a*rep_1a+rep_2a</p>
<p>rand_1b=matrix(rnorm(2*n1b),2,n1b)<br />
rep_1b=matrix(rep(A,n1b),2,n1b,byrow=FALSE)<br />
rep_2b=matrix(rep(C,n1b),2,n1b,byrow=FALSE)<br />
X1b=rand_1b*rep_1b+rep_2b</p>
<p>rand_2=matrix(rnorm(2*n2),2,n2)<br />
rep_2m=matrix(rep(A,n2),2,n2,byrow=FALSE)<br />
rep_2n=matrix(rep(D,n2),2,n2,byrow=FALSE)<br />
X2=rand_2*rep_2m+rep_2n</p>
<p>X=matrix(c(X1a,X1b,X2),2,n1a+n1b+n2,byrow=FALSE)<br />
Y=matrix(c(rep(1,n1a+n1b),rep(2,n2)))</p>
<p>### 调用lfda<br />
coords=lfda(X,Y,1,7)<br />
</p>
被调函数:
<br />
## lfda.r</p>
<p>lfda<-function(x,y,r,kNN){<br />
## x: data matrix, dimension*sample<br />
## y: class label matrix, sample*1</p>
<p>n=ncol(x) ## number of sample<br />
d=nrow(x) ## number of dimension</p>
<p>tSb=matrix(0,d,d) ##dimension * dimension<br />
tSw=matrix(0,d,d) ##dimension * dimension</p>
<p>for (c in unique(y)){<br />
xc=x[,y==c] # samples in the same class, dimension*sample<br />
nc=dim(xc)[2] # number of samples in the same class</p>
<p>##------------ Define classwise affinity matrix A ------------</p>
<p>A=matrix(0,nc,nc)</p>
<p>xc.distances=dist(xc)<br />
xc.distances=as.matrix(xc.distances)<br />
xc.sorted=apply(xc.distances,1,sort)<br />
kNNdist=xc.sorted[kNN+1,]<br />
sigma=kNNdist<br />
localscale=sigma%*%t(sigma)<br />
if(localscale!=0)<br />
{<br />
xc.distances2=xc.distances*xc.distances<br />
A=exp(-xc.distances2/localscale) ## A=exp((-||xi-xj||^2)/sigma^2)<br />
}</p>
<p>##------------ Within-class & between-class scatter matrix ---------</p>
<p>xc1=as.matrix(apply(xc,1,sum))</p>
<p>temp_A=as.matrix(apply(A,1,sum))<br />
An=kronecker(matrix(1,1,d),temp_A)<br />
G=xc%*%(An*t(xc))-xc%*%A%*%t(xc)<br />
tSb=tSb+G/n+xc%*%t(xc)*(1-nc/n)+xc1%*%t(xc1)/n<br />
tSw=tSw+G/nc<br />
}</p>
<p>x1=as.matrix(apply(x,1,sum))<br />
tSb=tSb-x1%*%t(x1)/n-tSw</p>
<p>tSb=(tSb+t(tSb))/2<br />
tSw=(tSw+t(tSw))/2</p>
<p>##------------ Egienevector ---------------------<br />
## AV=λBV <=> (B^(-1)*A)V=λV </p>
<p>tSw=solve(tSw)<br />
tS=tSw%*%tSb<br />
a=eigen(tS)$values<br />
b=eigen(tS)$vectors</p>
<p>b=b[,sort.list(a,decreasing=TRUE)]</p>
<p>coords=as.matrix(b[,1:r])</p>
<p>return(coords)</p>
<p>}<br />
</p>