Perform the bin_dense procedure for sparse matrices. Remaining rows
    and cols are lumped with the rest at the end.

def bin_sparse(M, subsampling_factor=3):
    """Perform the bin_dense procedure for sparse matrices. Remaining rows
    and cols are lumped with the rest at the end.
    """

    try:
        from scipy.sparse import coo_matrix
    except ImportError as e:
        print(str(e))
        print("I am peforming dense binning by default.")
        return bin_dense(M.todense())

    N = M.tocoo()
    n, m = N.shape
    row, col, data = N.row, N.col, N.data

    # Divide row and column indices - duplicate coordinates are added in
    # sparse matrix construction

    binned_row = row // subsampling_factor
    binned_col = col // subsampling_factor
    binned_n = n // subsampling_factor
    binned_m = m // subsampling_factor

    # Attach remaining columns and rows to the last one

    binned_row[binned_row >= binned_n] -= n % subsampling_factor
    binned_col[binned_col >= binned_m] -= m % subsampling_factor

    result = coo_matrix((data, (binned_row, binned_col)),
                        shape=(binned_n, binned_m))
    return result