spark-reviews mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dusenberrymw <...@git.apache.org>
Subject [GitHub] spark pull request: [SPARK-6485] [MLlib] [Python] Add CoordinateMa...
Date Sun, 02 Aug 2015 19:16:14 GMT
Github user dusenberrymw commented on a diff in the pull request:

    https://github.com/apache/spark/pull/7554#discussion_r36046440
  
    --- Diff: python/pyspark/mllib/linalg/distributed.py ---
    @@ -0,0 +1,513 @@
    +#
    +# Licensed to the Apache Software Foundation (ASF) under one or more
    +# contributor license agreements.  See the NOTICE file distributed with
    +# this work for additional information regarding copyright ownership.
    +# The ASF licenses this file to You under the Apache License, Version 2.0
    +# (the "License"); you may not use this file except in compliance with
    +# the License.  You may obtain a copy of the License at
    +#
    +#    http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +#
    +
    +"""
    +MLlib utilities for distributed linear algebra.
    +"""
    +
    +import sys
    +
    +if sys.version >= '3':
    +    long = int
    +
    +from py4j.java_gateway import JavaObject
    +
    +from pyspark import RDD, SparkContext
    +from pyspark.mllib.common import callJavaFunc, callMLlibFunc, JavaModelWrapper
    +from pyspark.mllib.linalg import _convert_to_vector
    +
    +
    +__all__ = ['DistributedMatrix', 'RowMatrix', 'IndexedRow',
    +           'IndexedRowMatrix', 'MatrixEntry', 'CoordinateMatrix']
    +
    +
    +def _create_from_java(java_matrix):
    +    """
    +    Create a PySpark distributed matrix from a Java distributed matrix.
    +
    +    >>> # RowMatrix
    +    >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6]])
    +    >>> mat = RowMatrix(rows)
    +
    +    >>> mat_diff = RowMatrix(rows)
    +    >>> (mat_diff._java_matrix_wrapper._java_model ==
    +    ...     mat._java_matrix_wrapper._java_model)
    +    False
    +
    +    >>> mat_same = _create_from_java(mat._java_matrix_wrapper._java_model)
    +    >>> (mat_same._java_matrix_wrapper._java_model ==
    +    ...     mat._java_matrix_wrapper._java_model)
    +    True
    +
    +
    +    >>> # IndexedRowMatrix
    +    >>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]),
    +    ...                        IndexedRow(1, [4, 5, 6])])
    +    >>> mat = IndexedRowMatrix(rows)
    +
    +    >>> mat_diff = IndexedRowMatrix(rows)
    +    >>> (mat_diff._java_matrix_wrapper._java_model ==
    +    ...     mat._java_matrix_wrapper._java_model)
    +    False
    +
    +    >>> mat_same = _create_from_java(mat._java_matrix_wrapper._java_model)
    +    >>> (mat_same._java_matrix_wrapper._java_model ==
    +    ...     mat._java_matrix_wrapper._java_model)
    +    True
    +
    +
    +    >>> # CoordinateMatrix
    +    >>> entries = sc.parallelize([MatrixEntry(0, 0, 1.2),
    +    ...                           MatrixEntry(6, 4, 2.1)])
    +    >>> mat = CoordinateMatrix(entries)
    +
    +    >>> mat_diff = CoordinateMatrix(entries)
    +    >>> (mat_diff._java_matrix_wrapper._java_model ==
    +    ...     mat._java_matrix_wrapper._java_model)
    +    False
    +
    +    >>> mat_same = _create_from_java(mat._java_matrix_wrapper._java_model)
    +    >>> (mat_same._java_matrix_wrapper._java_model ==
    +    ...     mat._java_matrix_wrapper._java_model)
    +    True
    +    """
    +    if isinstance(java_matrix, JavaObject):
    +        class_name = java_matrix.getClass().getSimpleName()
    +        if class_name == "RowMatrix":
    +            rows = callJavaFunc(SparkContext._active_spark_context, getattr(java_matrix,
"rows"))
    +            return RowMatrix(rows, java_matrix=java_matrix)
    +        elif class_name == "IndexedRowMatrix":
    +            # We use DataFrames for serialization of IndexedRows from
    +            # Java, so we first convert the RDD of rows to a DataFrame
    +            # on the Scala/Java side. Then we map each Row in the
    +            # DataFrame back to an IndexedRow on this side.
    +            rows_df = callMLlibFunc("getIndexedRows", java_matrix)
    +            rows = rows_df.map(lambda row: IndexedRow(row[0], row[1]))
    +            return IndexedRowMatrix(rows, java_matrix=java_matrix)
    +        elif class_name == "CoordinateMatrix":
    +            # We use DataFrames for serialization of MatrixEntry entries
    +            # from Java, so we first convert the RDD of entries to a
    +            # DataFrame on the Scala/Java side. Then we map each Row in
    +            # the DataFrame back to a MatrixEntry on this side.
    +            entries_df = callMLlibFunc("getMatrixEntries", java_matrix)
    +            entries = entries_df.map(lambda row: MatrixEntry(row[0], row[1], row[2]))
    +            return CoordinateMatrix(entries, java_matrix=java_matrix)
    +        else:
    +            raise TypeError("Cannot create distributed matrix from Java %s" % class_name)
    +    else:
    +        raise TypeError("java_matrix should be JavaObject, got %s" % type(java_matrix))
    +
    +
    +class DistributedMatrix(object):
    +    """
    +    Represents a distributively stored matrix backed by one or
    +    more RDDs.
    +
    +    """
    +    def numRows(self):
    +        """Get or compute the number of rows."""
    +        raise NotImplementedError
    +
    +    def numCols(self):
    +        """Get or compute the number of cols."""
    +        raise NotImplementedError
    +
    +
    +class RowMatrix(DistributedMatrix):
    +    """
    +    .. note:: Experimental
    +
    +    Represents a row-oriented distributed Matrix with no meaningful
    +    row indices.
    +
    +    :param rows: An RDD of vectors.
    +    :param numRows: Number of rows in the matrix. A non-positive
    +                    value means unknown, at which point the number
    +                    of rows will be determined by the number of
    +                    records in the `rows` RDD.
    +    :param numCols: Number of columns in the matrix. A non-positive
    +                    value means unknown, at which point the number
    +                    of columns will be determined by the size of
    +                    the first row.
    +    """
    +    def __init__(self, rows, numRows=0, numCols=0, java_matrix=None):
    +        """Create a wrapper over a Java RowMatrix."""
    +        if not isinstance(rows, RDD):
    +            raise TypeError("rows should be an RDD of vectors, got %s" % type(rows))
    +        rows = rows.map(_convert_to_vector)
    +
    +        if not (isinstance(java_matrix, JavaObject)
    +                and java_matrix.getClass().getSimpleName() == "RowMatrix"):
    +            java_matrix = callMLlibFunc("createRowMatrix", rows, long(numRows), int(numCols))
    +
    +        self._java_matrix_wrapper = JavaModelWrapper(java_matrix)
    +        self._rows = rows
    +
    +    @property
    +    def rows(self):
    +        """Rows of the RowMatrix stored as an RDD of vectors."""
    +        return self._rows
    +
    +    def numRows(self):
    +        """
    +        Get or compute the number of rows.
    +
    +        >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6],
    +        ...                        [7, 8, 9], [10, 11, 12]])
    +
    +        >>> rm = RowMatrix(rows)
    +        >>> print(rm.numRows())
    +        4
    +
    +        >>> rm = RowMatrix(rows, 7, 6)
    +        >>> print(rm.numRows())
    +        7
    +        """
    +        return self._java_matrix_wrapper.call("numRows")
    +
    +    def numCols(self):
    +        """
    +        Get or compute the number of cols.
    +
    +        >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6],
    +        ...                        [7, 8, 9], [10, 11, 12]])
    +
    +        >>> rm = RowMatrix(rows)
    +        >>> print(rm.numCols())
    +        3
    +
    +        >>> rm = RowMatrix(rows, 7, 6)
    +        >>> print(rm.numCols())
    +        6
    +        """
    +        return self._java_matrix_wrapper.call("numCols")
    +
    +
    +class IndexedRow(object):
    +    """
    +    .. note:: Experimental
    +
    +    Represents a row of an IndexedRowMatrix.
    +
    +    Just a wrapper over a (long, vector) tuple.
    +
    +    :param index: The index for the given row.
    +    :param vector: The row in the matrix at the given index.
    +    """
    +    def __init__(self, index, vector):
    +        self.index = long(index)
    +        self.vector = _convert_to_vector(vector)
    +
    +    def __repr__(self):
    +        return "IndexedRow(%s, %s)" % (self.index, self.vector)
    +
    +
    +def _convert_to_indexed_row(row):
    +    if isinstance(row, IndexedRow):
    +        return row
    +    elif isinstance(row, tuple) and len(row) == 2:
    +        return IndexedRow(*row)
    +    else:
    +        raise TypeError("Cannot convert type %s into IndexedRow" % type(row))
    +
    +
    +class IndexedRowMatrix(DistributedMatrix):
    +    """
    +    .. note:: Experimental
    +
    +    Represents a row-oriented distributed Matrix with indexed rows.
    +
    +    :param rows: An RDD of IndexedRows or (long, vector) tuples.
    +    :param numRows: Number of rows in the matrix. A non-positive
    +                    value means unknown, at which point the number
    +                    of rows will be determined by the max row
    +                    index plus one.
    +    :param numCols: Number of columns in the matrix. A non-positive
    +                    value means unknown, at which point the number
    +                    of columns will be determined by the size of
    +                    the first row.
    +    """
    +    def __init__(self, rows, numRows=0, numCols=0, java_matrix=None):
    +        """Create a wrapper over a Java IndexedRowMatrix."""
    --- End diff --
    
    Okay, I can update that, although the PEP 8 & 257 convention is to use docstrings
even in the `def __init__(..)` methods.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Mime
View raw message