// modelMean calculates the mean between all points in a model and a centroid. func modelMean(points, centroid *matrix.DenseMatrix) *matrix.DenseMatrix { prows, pcols := points.GetSize() pdist := matrix.Zeros(prows, pcols) for i := 0; i < prows; i++ { diff := matrix.Difference(centroid, points.GetRowVector(i)) pdist.SetRowVector(diff, i) } return pdist.MeanCols() }
// CalcDist finds the Euclidean distance between points. func (ed EuclidDist) CalcDist(p, q *matrix.DenseMatrix) float64 { diff := matrix.Difference(q, p) diff.Sqrm() // square each value in the matrix in place // To avoid allocating a new matrix the sum is placed in the // first column of each row. N.B. this modifies the matrix directly. diff.SumRowsM() // Each point coordinate consists of 1 row and M cols. So, // the sum will be at [0, 0] s := diff.Get(0, 0) return math.Sqrt(s) }
// CalcDist finds the Euclidean distance between a centroid // and a point in the data set. Arguments are 1x2 matrices. // All intermediary l-values except s are matricies. The functions that // operate on them can all take nXn matricies as arguments. func (ed EuclidDist) CalcDist(centroid, point *matrix.DenseMatrix) (dist float64, err error) { err = nil diff := matrix.Difference(centroid, point) //square the resulting matrix sqr := diff.Pow(2) // sum of 1x2 matrix sum := sqr.SumRows() // n X 1 matrix // square root of sum s := sum.Get(0, 0) dist = math.Sqrt(s) return }