def j_sparse_vector_wrapper_to_scipy_spmatrix(j_obj: JavaObject): """ Convert a Java object of `SparseVectorWrapper` to a scipy sparse matrix whose number of rows is 1. `j_obj.getSize()` must return a positive number. NOTE: - To access i-th element, use `A[0, i]` rather than `A[i]`. - To convert the sparse matrix to a numpy.ndarray, use `A.todense()`. - For other usages, please refer to scipy documents. TODO: find a better type to represent `SparseVector` in Python side. :param j_obj: a Java object of `SparseVectorWrapper` :return: a scipy sparse matrix """ indices = np.frombuffer(j_obj.getIndicesBytes(), dtype="<i4") values = np.frombuffer(j_obj.getValuesBytes(), dtype="<f8") size = j_obj.getSize() indptr = np.array([0, indices.shape[0]], dtype=np.int32) return csr_matrix((values, indices, indptr), shape=(1, size), dtype=np.float64).todok()
def j_dense_vector_wrapper_to_np_array(j_obj: JavaObject): buffer, size = j_obj.getBytes(), j_obj.getSize() arr = np.frombuffer(buffer, dtype="<f8").reshape([size]) return arr