Skip to content

Commit ab48f6e

Browse files
committed
RowMatrix.scala
* numCols(): Added check for numRows = 0, with error message. * computeCovariance(): Added check for numRows <= 1, with error message.
1 parent 65e4ebc commit ab48f6e

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

mllib/src/main/scala/org/apache/spark/mllib/linalg/distributed/RowMatrix.scala

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,14 @@ class RowMatrix(
5353
/** Gets or computes the number of columns. */
5454
override def numCols(): Long = {
5555
if (nCols <= 0) {
56-
// Calling `first` will throw an exception if `rows` is empty.
57-
nCols = rows.first().size
56+
try {
57+
// Calling `first` will throw an exception if `rows` is empty.
58+
nCols = rows.first().size
59+
} catch {
60+
case err: UnsupportedOperationException =>
61+
sys.error("Cannot determine the number of cols because it is not specified in the " +
62+
"constructor and the rows RDD is empty.")
63+
}
5864
}
5965
nCols
6066
}
@@ -293,6 +299,10 @@ class RowMatrix(
293299
(s1._1 + s2._1, s1._2 += s2._2)
294300
)
295301

302+
if (m <= 1) {
303+
sys.error(s"RowMatrix.computeCovariance called on matrix with only $m rows." +
304+
" Cannot compute the covariance of a RowMatrix with <= 1 row.")
305+
}
296306
updateNumRows(m)
297307

298308
mean :/= m.toDouble

mllib/src/test/scala/org/apache/spark/mllib/stat/CorrelationSuite.scala

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,12 @@ class CorrelationSuite extends FunSuite with LocalSparkContext {
4242
test("corr(x, y) pearson, 1 value in data") {
4343
val x = sc.parallelize(Array(1.0))
4444
val y = sc.parallelize(Array(4.0))
45-
assert(Statistics.corr(x, y, "pearson").isNaN)
46-
assert(Statistics.corr(x, y, "spearman").isNaN)
45+
intercept[RuntimeException] {
46+
Statistics.corr(x, y, "pearson")
47+
}
48+
intercept[RuntimeException] {
49+
Statistics.corr(x, y, "spearman")
50+
}
4751
}
4852

4953
test("corr(x, y) default, pearson") {

0 commit comments

Comments
 (0)