stat: trim wide backing vecs matrix during PCA

vecs is wide when a is wide, but vectors beyond n are not valid, so
clone the result view into vecs. This costs an allocation when it
happens, but potentially saves significant space - when n << d.
This commit is contained in:
kortschak
2016-03-06 09:52:29 +10:30
parent 91c2813441
commit aa29fc4604

16
pca.go
View File

@@ -57,9 +57,12 @@ func PrincipalComponents(a mat64.Matrix, weights []float64) (vecs *mat64.Dense,
return nil, nil, false
}
var v mat64.Dense
v.VFromSVD(&svd)
vecs = v.View(0, 0, d, min(n, d)).(*mat64.Dense)
vecs = &mat64.Dense{}
vecs.VFromSVD(&svd)
if n < d {
// Don't retain columns that are not valid direction vectors.
vecs.Clone(vecs.View(0, 0, d, n))
}
vars = svd.Values(nil)
var f float64
if weights == nil {
@@ -72,10 +75,3 @@ func PrincipalComponents(a mat64.Matrix, weights []float64) (vecs *mat64.Dense,
}
return vecs, vars, true
}
func min(a, b int) int {
if a < b {
return a
}
return b
}