官术网_书友最值得收藏!

  • Machine Learning With Go
  • Daniel Whitenack
  • 382字
  • 2021-07-08 10:37:31

Matrices

Matrices and linear algebra may seem complicated to many people, but simply put, matrices are just rectangular organizations of numbers, and linear algebra dictates the rules associated with their manipulation. For example, a matrix A with numbers arranged on a 4 x 3 rectangle may look like this:

The components of A (a11, a12, and so on) are the individual numbers that we are arranging into a matrix, and the subscripts indicate the location of the components within the matrix. The first index is the row index and the second index is the column index. More generally, A could have any shape/size with M rows and N columns:

To form a matrix like this with gonum.org/v1/gonum/mat, we need to create a slice of float64 values that is a flat representation of all the matrix components. For instance, in our example, we want to form the following matrix:

We would need to create a slice of float64 values as follows:

// Create a flat representation of our matrix.
components := []float64{1.2, -5.7, -2.4, 7.3}

Then, we can supply this, along with dimension information, to gonum.org/v1/gonum/mat to form a new mat.Dense matrix value:

// Form our matrix (the first argument is the number of
// rows and the second argument is the number of columns).
a := mat.NewDense(2, 2, data)

// As a sanity check, output the matrix to standard out.
fa := mat.Formatted(a, mat.Prefix(" "))
fmt.Printf("mat = %v\n\n", fa)

Note that we have also used the nice formatting logic in gonum.org/v1/gonum/mat to print the matrix as a sanity check. When you run this, you should see the following:

$ go build
$ ./myprogram
A = [ 1.2 -5.7]
[-2.4 7.3]

We can then access and modify certain values within A via built-in methods:

// Get a single value from the matrix.
val := a.At(0, 1)
fmt.Printf("The value of a at (0,1) is: %.2f\n\n", val)

// Get the values in a specific column.
col := mat.Col(nil, 0, a)
fmt.Printf("The values in the 1st column are: %v\n\n", col)

// Get the values in a kspecific row.
row := mat.Row(nil, 1, a)
fmt.Printf("The values in the 2nd row are: %v\n\n", row)

// Modify a single element.
a.Set(0, 1, 11.2)

// Modify an entire row.
a.SetRow(0, []float64{14.3, -4.2})

// Modify an entire column.
a.SetCol(0, []float64{1.7, -0.3})
主站蜘蛛池模板: 萍乡市| 苗栗县| 五河县| 镇康县| 永胜县| 安阳市| 杨浦区| 宕昌县| 罗平县| 潍坊市| 梅河口市| 滦平县| 普格县| 永定县| 宁晋县| 图片| 泸水县| 新蔡县| 文安县| 青铜峡市| 平凉市| 镇原县| 永德县| 肇州县| 和平县| 锡林浩特市| 长治县| 靖西县| 阿拉善盟| 江北区| 井陉县| 本溪市| 安阳县| 广州市| 洛川县| 彰化县| 平山县| 江津市| 剑河县| 海原县| 九龙城区|