File: pca_example_test.go

package info (click to toggle)
golang-gonum-v1-gonum 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,792 kB
  • sloc: asm: 6,252; fortran: 5,271; sh: 377; ruby: 211; makefile: 98
file content (62 lines) | stat: -rw-r--r-- 1,469 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright ©2016 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package stat_test

import (
	"fmt"

	"gonum.org/v1/gonum/mat"
	"gonum.org/v1/gonum/stat"
)

func ExamplePC() {
	// iris is a truncated sample of the Fisher's Iris dataset.
	n := 10
	d := 4
	iris := mat.NewDense(n, d, []float64{
		5.1, 3.5, 1.4, 0.2,
		4.9, 3.0, 1.4, 0.2,
		4.7, 3.2, 1.3, 0.2,
		4.6, 3.1, 1.5, 0.2,
		5.0, 3.6, 1.4, 0.2,
		5.4, 3.9, 1.7, 0.4,
		4.6, 3.4, 1.4, 0.3,
		5.0, 3.4, 1.5, 0.2,
		4.4, 2.9, 1.4, 0.2,
		4.9, 3.1, 1.5, 0.1,
	})

	// Calculate the principal component direction vectors
	// and variances.
	var pc stat.PC
	ok := pc.PrincipalComponents(iris, nil)
	if !ok {
		return
	}
	fmt.Printf("variances = %.4f\n\n", pc.VarsTo(nil))

	// Project the data onto the first 2 principal components.
	k := 2
	var proj mat.Dense
	var vec mat.Dense
	pc.VectorsTo(&vec)
	proj.Mul(iris, vec.Slice(0, d, 0, k))

	fmt.Printf("proj = %.4f", mat.Formatted(&proj, mat.Prefix("       ")))

	// Output:
	// variances = [0.1666 0.0207 0.0079 0.0019]
	//
	// proj = ⎡-6.1686   1.4659⎤
	//        ⎢-5.6767   1.6459⎥
	//        ⎢-5.6699   1.3642⎥
	//        ⎢-5.5643   1.3816⎥
	//        ⎢-6.1734   1.3309⎥
	//        ⎢-6.7278   1.4021⎥
	//        ⎢-5.7743   1.1498⎥
	//        ⎢-6.0466   1.4714⎥
	//        ⎢-5.2709   1.3570⎥
	//        ⎣-5.7533   1.6207⎦
}