Instantly share code, notes, and snippets.

# r9y9/nmf.go Created Feb 16, 2014

What would you like to do?
Non-negative Matrix Factorization (NMF) in Golang
 package main import ( "fmt" . "github.com/r9y9/go.matrix" ) // Minimize |Y - HU|^2 st H, U > 0 func NMFEuclid(Y *DenseMatrix, numBasis, numIter int) (*DenseMatrix, *DenseMatrix) { H := Numbers(Y.Rows(), numBasis, 1.0) U := Numbers(numBasis, Y.Cols(), 1.0) epsiron1 := Numbers(numBasis, Y.Cols(), 1.0e-7) epsiron2 := Numbers(Y.Rows(), numBasis, 1.0e-7) for iter := 0; iter < numIter; iter++ { objectiveMat, _ := Y.MinusDense(Product(H, U)) objective := objectiveMat.TwoNorm() fmt.Println("Objective function: ", objective) // Update U t1, _ := H.Transpose().TimesDense(Y) numerU, _ := U.ElementMultDense(t1) denomU := Product(H.Transpose(), H, U) denomU.Add(epsiron1) U, _ = numerU.ElementDivDense(denomU) // Update H t2, _ := Y.TimesDense(U.Transpose()) numerH, _ := H.ElementMultDense(t2) denomH := Product(H, U, U.Transpose()) denomH.Add(epsiron2) H, _ = numerH.ElementDivDense(denomH) } return H, U } func main() { A := Numbers(5, 5, 50.0) fmt.Println("The original matrix: \n", A) H, U := NMFEuclid(A, 2, 10) fmt.Println("Basis: \n", H) fmt.Println("Activity: \n", U) }
Owner

### r9y9 commented Feb 16, 2014

 結果はっとく The original matrix: {50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50} Objective function: 240 Objective function: 3.999964803824696e-09 Objective function: 4.000035858098272e-09 Objective function: 4.000000330961484e-09 Objective function: 3.999964803824696e-09 Objective function: 4.000035858098272e-09 Objective function: 4.000000330961484e-09 Objective function: 4.000035858098272e-09 Objective function: 4.000000330961484e-09 Objective function: 3.999929276687908e-09 Basis: {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Activity: {25, 25, 25, 25, 25, 25, 25, 25, 25, 25}