gonum.org/v1/gonum@v0.14.0/stat/pca_example_test.go (about) 1 // Copyright ©2016 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package stat_test 6 7 import ( 8 "fmt" 9 10 "gonum.org/v1/gonum/mat" 11 "gonum.org/v1/gonum/stat" 12 ) 13 14 func ExamplePC() { 15 // iris is a truncated sample of the Fisher's Iris dataset. 16 n := 10 17 d := 4 18 iris := mat.NewDense(n, d, []float64{ 19 5.1, 3.5, 1.4, 0.2, 20 4.9, 3.0, 1.4, 0.2, 21 4.7, 3.2, 1.3, 0.2, 22 4.6, 3.1, 1.5, 0.2, 23 5.0, 3.6, 1.4, 0.2, 24 5.4, 3.9, 1.7, 0.4, 25 4.6, 3.4, 1.4, 0.3, 26 5.0, 3.4, 1.5, 0.2, 27 4.4, 2.9, 1.4, 0.2, 28 4.9, 3.1, 1.5, 0.1, 29 }) 30 31 // Calculate the principal component direction vectors 32 // and variances. 33 var pc stat.PC 34 ok := pc.PrincipalComponents(iris, nil) 35 if !ok { 36 return 37 } 38 fmt.Printf("variances = %.4f\n\n", pc.VarsTo(nil)) 39 40 // Project the data onto the first 2 principal components. 41 k := 2 42 var proj mat.Dense 43 var vec mat.Dense 44 pc.VectorsTo(&vec) 45 proj.Mul(iris, vec.Slice(0, d, 0, k)) 46 47 fmt.Printf("proj = %.4f", mat.Formatted(&proj, mat.Prefix(" "))) 48 49 // Output: 50 // variances = [0.1666 0.0207 0.0079 0.0019] 51 // 52 // proj = ⎡-6.1686 1.4659⎤ 53 // ⎢-5.6767 1.6459⎥ 54 // ⎢-5.6699 1.3642⎥ 55 // ⎢-5.5643 1.3816⎥ 56 // ⎢-6.1734 1.3309⎥ 57 // ⎢-6.7278 1.4021⎥ 58 // ⎢-5.7743 1.1498⎥ 59 // ⎢-6.0466 1.4714⎥ 60 // ⎢-5.2709 1.3570⎥ 61 // ⎣-5.7533 1.6207⎦ 62 }