sjwhitworth/golearn

KNN classifier `euclidean` broken

sugarme opened this issue · 0 comments

I am facing issue where running examples/knnclassifier/knnclassifier_iris.go evokes panic due to gonum/dense package does not allow to create new zero matrix anymore while pairwise/euclidean does so

subVector := mat.NewDense(0, 0, nil)

subVector := mat.NewDense(0, 0, nil)

My quick fix would be creating a 1x1 matrix then reset to zero:

// InnerProduct computes a Eucledian inner product.
func (e *Euclidean) InnerProduct(vectorX *mat.Dense, vectorY *mat.Dense) float64 {
	// subVector := mat.NewDense(0, 0, nil) // <-- new zero dense matrix causes panic
	subVector := mat.NewDense(1, 1, nil) // <-- create 1x1 new dense
	subVector.Reset()                    // <-- then, reset to zero
	subVector.MulElem(vectorX, vectorY)
	result := mat.Sum(subVector)

	return result
}

// Distance computes Euclidean distance (also known as L2 distance).
func (e *Euclidean) Distance(vectorX *mat.Dense, vectorY *mat.Dense) float64 {
	// subVector := mat.NewDense(0, 0, nil) // <-- new zero dense matrix causes panic
	subVector := mat.NewDense(1, 1, nil) // <-- create 1x1 new dense
	subVector.Reset()                    // <-- then, reset to zero
	subVector.Sub(vectorX, vectorY)

	result := e.InnerProduct(subVector, subVector)

	return math.Sqrt(result)
}