1. 程式人生 > >機器學習-RBF高斯核函式處理

機器學習-RBF高斯核函式處理

SVM高斯核函式-RBF優化
重要了解數學的部分:
協方差矩陣,高斯核函式公式。
個人建議具體的求法還是看下面的核心程式碼吧,更好理解,反正就我個人而言,煩躁的公式,還不如一段程式碼來的實際。本來想用java的一個叫jblas的矩陣包,但是想了想,還是自己動手寫一下吧。加深一下自己理解。實現的語言用的是java孿生兄弟scala。我想應該不難懂。矩陣變換用二位陣列將就。
以下程式碼建議用scala命令列除錯

核心程式碼

def TransposedMatrix(a:Array[Array[Double]]):Array[Array[Double]]={//返回轉置矩陣
    val length=a.length
    val width=a(0
).length var TransposedM =Array.ofDim[Double](width,length) for(i <- 0 to length-1) for(j <- 0 to width-1) { TransposedM(j)(i) = a(i)(j) } TransposedM } def R1(i:Int,j:Int,M:Array[Array[Double]]):Double={//R(i,j)=(第i列-第j列)*[(第i列-第j列)轉置] var sum:Double=0 for
(x <- 0 to M.length-1) sum+=Math.pow((M(x)(i)-M(x)(j)),2) sum } def RowAverage(a:Array[Array[Double]]):Array[Double]={//返回列的均值,返回一個列矩陣 val length=a.length val width=a(0).length var b=new Array[Double](width) for(i <- 0 to width-1) for(j <- 0 to length-1) b(i) += a(j)(i) for
(i <- 0 to width-1) b(i)=b(i)/length b } def sumOfRow(a:Array[Array[Double]]):Array[Double]={//返回矩陣列的和,返回一個列矩陣 val length=a.length val width=a(0).length var b=new Array[Double](width) for(i <- 0 to width-1) for(j <- 0 to length-1) b(i) += a(j)(i) for(i <- 0 to width-1) b(i)=b(i) b } def sum(i:Int,j:Int,a:Array[Array[Double]]):Double={//i列乘j列的轉置 var result:Double=0 for(x<- 0 to a.length-1) result +=(a(x)(i)*a(x)(j)) result } def cov(a:Array[Array[Double]]):Array[Array[Double]]={//將特徵矩陣作為引數,返回協方差矩陣 val m1=TransposedMatrix(a) val m2=RowAverage(m1) val m3=datasort(m1,m2)//將矩陣中心化 val width=m3(0).length var b =Array.ofDim[Double](width,width) for(i <- 0 to width-1) for(j <- 0 to width-1) b(i)(j)=sum(i,j,m3) b } def datasort(a:Array[Array[Double]],b:Array[Double]):Array[Array[Double]]={//矩陣中心化,將每列減去列的均值 for(i <- 0 to a(0).length-1) for(j <- 0 to a.length-1) a(j)(i) -= b(i) a } def gaussMatrix(a:Array[Array[Double]],delta:Array[Double]):Array[Array[Double]]={//a為特徵矩陣,delta為協方差矩陣列之和,返回高斯核函式矩陣 val b=TransposedMatrix(a) val length=b(0).length var R =Array.ofDim[Double](length,length) for(i <- 0 to length-1) for(j <- 0 to length-1) R(i)(j)=Math.exp(-R1(i,j,b)/delta(j)) R } val test=Array(Array(2.0, 8.0), Array(3.0, 6.0), Array(9.0, 2.0)) val test2=cov(test) val rowOfsum=sumOfRow(res65) gaussMatrix(test,rowOfsum)

歡迎各位看官大爺批評指教。