Monday, July 31, 2017

How to use gonum/matrix (Golang package)

When I started to learn about Golang, the first obstacle to use that for machine learning was matrix data manipulation. On Python, you can use numpy, pandas. On Go, on some machine learning package uses gonum/matrix. So I just checked how to use.

Overview

I make a summary about gonum/matrix’s basic usage.



What is gonum/matrix?

gonum/matrix is the package about matrix calculation, which uses BLAS and LAPACK.

How to install

go get github.com/gonum/matrix

How to use

Make matrix

You can make matrix by mat64.NewDense().
//all the elements are zero
zero := mat64.NewDense(3, 5, nil)

//change slice to matrix
data := make([]float64, 36)
for i := range data{
    data[i] = float64(i)
}
data_matrix := mat64.NewDense(6,6,data)
The first example of code above makes matrix with zero elements.
fmt.Println(zero)

&{{3 5 5 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]} 3 5}
Next example makes slice at first and changes it to matrix.
fmt.Println(data_matrix)

&{{6 6 6 [0 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]} 6 6}
You can make matrix with initial values or from slice.

How to acceess the elements

To get matrx’s elements, you can use At() function.
fmt.Println(data_matrix.At(0,1))

1
To get specific row, RowView() works.
fmt.Println(data_matrix.RowView(3))

&{{1 [18 19 20 21 22 23]} 6}

How to do matrix calculation

To get matrix calculation outcome, you need to make matrix which receives the outcome.
a_elements := []float64{1,2,3,4}
b_elements := []float64{5,6,7,8}
c_elements := make([]float64, 4)

a_matrix := mat64.NewDense(2,2,a_elements)
b_matrix := mat64.NewDense(2,2,b_elements)
c_matrix := mat64.NewDense(2,2,c_elements)

fmt.Println("a_matrix")
fmt.Println(a_matrix)
fmt.Println("b_matrix")
fmt.Println(b_matrix)

c_matrix.Add(a_matrix, b_matrix)
fmt.Println("a_matrix + b_matrix")
fmt.Println(c_matrix)

c_matrix.Sub(a_matrix, b_matrix)
fmt.Println("a_matrix - b_matrix")
fmt.Println(c_matrix)

c_matrix.Mul(a_matrix, b_matrix)
fmt.Println("a_matrix * b_matrix")
fmt.Println(c_matrix)
The outcome is below.
a_matrix
&{{2 2 2 [1 2 3 4]} 2 2}
b_matrix
&{{2 2 2 [5 6 7 8]} 2 2}
a_matrix + b_matrix
&{{2 2 2 [6 8 10 12]} 2 2}
a_matrix - b_matrix
&{{2 2 2 [-4 -4 -4 -4]} 2 2}
a_matrix * b_matrix
&{{2 2 2 [19 22 43 50]} 2 2}