Github user mengxr commented on a diff in the pull request:

    https://github.com/apache/spark/pull/7554#discussion_r36032328
  
    --- 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):
    --- End diff --
    
    We shouldn't expose `java_matrix` in the public API. I suggest the 
following logic:
    
    1. If `rows` is an Python RDD, convert it to DataFrame and create a Java 
`RowMatrix` object using `numRows` and `numCols`, only keep the reference to 
the java object.
    2. if `rows` is a Java `RowMatrix`, keep the reference directly. (Do not 
document it in public API.)


---
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 [email protected] or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to