Esempio n. 1
0
def saveSparseMatrix(file: str,
                     matrix: csr_matrix,
                     colnames: Union[List[str], None] = None) -> None:
    """ Save sparse matrix to json file

        Args:
            ile:                                file name to store results, full or relative path
            matrix (M,N):                       sparse matrix of size (M,N)
            colnames, optional (1,N):           column names

        Returns:
            None
    """

    json_content = dict()

    if colnames is not None:
        json_content["features"] = colnames

    json_content["size"] = matrix.shape
    matrix = matrix.astype(float)

    keys = matrix.todok().keys()
    keys = [tuple(map(int, key)) for key in keys]

    vals = matrix.todok().values()
    vals = list(map(float, vals))

    json_content["positions"] = keys
    json_content["counts"] = vals

    with open(file, "w") as f:
        json.dump(json_content, f, indent=4)