Skip to content

Commit ac673bd

Browse files
committed
More safeguards against numerical ridiculousness.
1 parent c288b6a commit ac673bd

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

mllib/src/main/scala/org/apache/spark/mllib/optimization/NNLSbyPCG.scala

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,18 @@ object NNLSbyPCG {
3939
def steplen(dir: DoubleMatrix, resid: DoubleMatrix): Double = {
4040
val top = SimpleBlas.dot(dir, resid)
4141
SimpleBlas.gemv(1.0, ata, dir, 0.0, scratch)
42-
top / SimpleBlas.dot(scratch, dir)
42+
// Push the denominator upward very slightly to avoid infinities and silliness
43+
top / (SimpleBlas.dot(scratch, dir) + 1e-20)
4344
}
4445

4546
// stopping condition
4647
def stop(step: Double, ndir: Double, nx: Double): Boolean = {
47-
((step != step)
48-
|| (step < 1e-6)
49-
|| (ndir < 1e-12 * nx))
48+
((step != step) // NaN
49+
|| (step < 1e-6) // too small or negative
50+
|| (step > 1e40) // too small; almost certainly numerical problems
51+
|| (ndir < 1e-12 * nx) // gradient relatively too small
52+
|| (ndir < 1e-32) // gradient absolutely too small; numerical issues may lurk
53+
)
5054
}
5155

5256
val grad = new DoubleMatrix(n, 1)
@@ -134,5 +138,4 @@ object NNLSbyPCG {
134138
}
135139
x.data
136140
}
137-
138141
}

0 commit comments

Comments
 (0)