Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions mllib/src/main/scala/org/apache/spark/mllib/linalg/Vectors.scala
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,17 @@ object Vectors {
*/
def dense(values: Array[Double]): Vector = new DenseVector(values)

/**
* Creates a sparse vector providing its value array.
*
* @param values value array, must have the same length as indices.
*/
def sparse(values: Array[Double]): Vector = {
val size = values.length
val (result, indices) = values.zipWithIndex.filter(_._1 != 0.0).unzip
new SparseVector(size, indices.toArray, result.toArray)
}

/**
* Creates a sparse vector providing its index array and value array.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ class VectorsSuite extends FunSuite {
assert(vec.toArray === arr)
}

test("SPARK-7194 sparse to array") {
val vec = Vectors.sparse(arr).asInstanceOf[SparseVector]
assert(vec.toArray === arr)
}

test("vector equals") {
val dv1 = Vectors.dense(arr.clone())
val dv2 = Vectors.dense(arr.clone())
Expand Down