Skip to content

Commit

Permalink
Construct scipy.sparse matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
Lewuathe committed May 15, 2015
1 parent c345a44 commit 5d555b1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
9 changes: 9 additions & 0 deletions python/pyspark/mllib/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import array as pyarray

from numpy import array, array_equal, zeros, inf
import scipy.sparse as sp
from py4j.protocol import Py4JJavaError

if sys.version_info[:2] <= (2, 6):
Expand Down Expand Up @@ -832,6 +833,14 @@ def test_append_bias_with_vector(self):
self.assertEqual(ret[3], 1.0)
self.assertEqual(type(ret), list)

def test_append_bias_with_sp_vector(self):
data = Vectors.sparse(3, {0: 2.0, 2: 2.0})
# Returned value must be scipy.sparse matrix
ret = MLUtils.appendBias(data)
self.assertEqual(ret.shape, (1, 4))
self.assertEqual(ret.toarray()[0][3], 1.0)
self.assertEqual(type(ret), sp.csc_matrix)

def test_load_vectors(self):
import shutil
data = [
Expand Down
7 changes: 5 additions & 2 deletions python/pyspark/mllib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@

import sys
import numpy as np
import scipy.sparse as sp
import warnings

if sys.version > '3':
xrange = range

from pyspark.mllib.common import callMLlibFunc, inherit_doc
from pyspark.mllib.linalg import Vector, Vectors, SparseVector, _convert_to_vector
from pyspark.mllib.linalg import Vector, Vectors, DenseVector, SparseVector, _convert_to_vector


class MLUtils(object):
Expand Down Expand Up @@ -176,7 +177,9 @@ def appendBias(data):
the end of the input vector.
"""
vec = _convert_to_vector(data)
if isinstance(vec, Vector):
if isinstance(vec, SparseVector):
return sp.csc_matrix(np.append(vec.toArray(), 1.0))
elif isinstance(vec, Vector):
vec = vec.toArray()
return np.append(vec, 1.0).tolist()

Expand Down

0 comments on commit 5d555b1

Please sign in to comment.