当前位置: 首页>>代码示例>>Python>>正文


Python sparse.spmatrix方法代码示例

本文整理汇总了Python中scipy.sparse.spmatrix方法的典型用法代码示例。如果您正苦于以下问题:Python sparse.spmatrix方法的具体用法?Python sparse.spmatrix怎么用?Python sparse.spmatrix使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.sparse的用法示例。


在下文中一共展示了sparse.spmatrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: rmatvec_nd

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def rmatvec_nd(lin_op, x):
    """
    Project a 1D or 2D numpy or sparse array using rmatvec. This is different from rmatvec
    because it applies rmatvec to each row and column. If x is n x n and lin_op is n x k,
    the result will be k x k.

    :param LinearOperator lin_op: The linear operator to apply to x
    :param np.ndarray|sp.spmatrix x: array/matrix to be projected
    :return: the projected array
    :rtype: np.ndarray|sp.spmatrix
    """
    if x is None or lin_op is None:
        return x
    if isinstance(x, sp.spmatrix):
        y = x.toarray()
    elif np.isscalar(x):
        y = np.array(x, ndmin=1)
    else:
        y = np.copy(x)
    proj_func = lambda z: lin_op.rmatvec(z)
    for j in range(y.ndim):
        if y.shape[j] == lin_op.shape[0]:
            y = np.apply_along_axis(proj_func, j, y)
    return y 
开发者ID:Knewton,项目名称:edm2016,代码行数:26,代码来源:linear_operators.py

示例2: __init__

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def __init__(self, dim=None, mean=None, precision=None, mean_lin_op=None, support=None):
        """
        :param int dim: dimensionality of the distribution. If None, inferred from mean or precision
        :param float|np.ndarray|None mean: the mean, float or 1D array. If not supplied on init or
            call-time, assumed to be 0.  If scalar, assumes the mean is the same for all dimensions.
        :param float|np.ndarray|sp.spmatrix|None precision: the precision matrix.  If not supplied
            on init or at call-time, assumed to be the identity.
            If 1D, assumes that the diagonal of the precision matrix is passed in; if scalar
            and CPD dimensionality > 1, assumes that the precision matrix is precision * identity
            matrix.
        :param None|IndexOperator mean_lin_op: linear transform operator for the mean parameter,
            whose is shape is (dim, len(mean_vector))
        :param tuple(float) support: Defines the support for the probability distribution. Passed
            to solver pars updater to prevent the parameter from being set outside the range of the
            supports.
        """
        mean, precision, const = self._validate_args(dim=dim, mean=mean, precision=precision)
        self.mean = mean.ravel() if self.dim > 1 else mean
        self.precision = precision
        self.hessian_cache = None
        self.hessian_mean_cache = None
        self.const = const
        self.mean_lin_op = mean_lin_op
        self.support = support 
开发者ID:Knewton,项目名称:edm2016,代码行数:26,代码来源:gaussian.py

示例3: hessian_wrt_mean

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def hessian_wrt_mean(self):
        """ The Hessian of the multivariate Gaussian w.r.t. its mean, potentially including the
        linear projection.

        :return: The Hessian w.r.t. the mean
        :rtype: float|np.ndarray|sp.spmatrix
        """
        if self.hessian_mean_cache is None:
            hessian = self.hessian
            if self.mean_lin_op is not None:
                if np.isscalar(hessian) and isinstance(self.mean_lin_op, IndexOperator):
                    # index operator preserves diagonality
                    hessian = sp.diags(self.mean_lin_op.rmatvec(hessian * np.ones(self.dim)), 0)
                elif np.isscalar(hessian):
                    hessian = hessian * np.eye(self.dim)
                    hessian = rmatvec_nd(self.mean_lin_op, hessian)
                else:
                    hessian = rmatvec_nd(self.mean_lin_op, hessian)
            self.hessian_mean_cache = hessian
        return self.hessian_mean_cache 
开发者ID:Knewton,项目名称:edm2016,代码行数:22,代码来源:gaussian.py

示例4: get_dependent_vars

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def get_dependent_vars(self, var_idx):
        """ Given the indices of the query variables, var_idx, returns the set of dependent
        variables (including var_idx); i.e., the smallest set S containing var_idx for which
        (complement of S) indep of (S).  This is done by finding all non-zero columns of the
        `var_idx` rows of the precision matrix.

        :param np.ndarray[int]|np.ndarray[bool] var_idx: indices of the query variables
        :return: indices of the dependent variables
        :rtype: np.ndarray[int]
        """
        if isinstance(self.precision, sp.spmatrix):
            prec = self.precision.tocsr()
        elif np.isscalar(self.precision):
            return var_idx
        else:
            prec = self.precision
        return np.unique(np.nonzero(prec[var_idx, :])[1]) 
开发者ID:Knewton,项目名称:edm2016,代码行数:19,代码来源:gaussian.py

示例5: sparse_feeder

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def sparse_feeder(M):
    """
    Prepares the input matrix into a format that is easy to feed into tensorflow's SparseTensor

    Parameters
    ----------
    M : scipy.sparse.spmatrix
        Matrix to be fed

    Returns
    -------
    indices : array-like, shape [n_edges, 2]
        Indices of the sparse elements
    values : array-like, shape [n_edges]
        Values of the sparse elements
    shape : array-like
        Shape of the matrix
    """
    M = sp.coo_matrix(M)
    return np.vstack((M.row, M.col)).T, M.data, M.shape 
开发者ID:abojchevski,项目名称:graph2gauss,代码行数:22,代码来源:utils.py

示例6: sparse_mean_variance_axis

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def sparse_mean_variance_axis(mtx: sparse.spmatrix, axis: int):
    """
    This code and internal functions are based on sklearns
    `sparsefuncs.mean_variance_axis`.

    Modifications:
    * allow deciding on the output type, which can increase accuracy when calculating the mean and variance of 32bit floats.
    * This doesn't currently implement support for null values, but could.
    * Uses numba not cython
    """
    assert axis in (0, 1)
    if isinstance(mtx, sparse.csr_matrix):
        ax_minor = 1
        shape = mtx.shape
    elif isinstance(mtx, sparse.csc_matrix):
        ax_minor = 0
        shape = mtx.shape[::-1]
    else:
        raise ValueError("This function only works on sparse csr and csc matrices")
    if axis == ax_minor:
        return sparse_mean_var_major_axis(
            mtx.data, mtx.indices, mtx.indptr, *shape, np.float64
        )
    else:
        return sparse_mean_var_minor_axis(mtx.data, mtx.indices, *shape, np.float64) 
开发者ID:theislab,项目名称:scanpy,代码行数:27,代码来源:_utils.py

示例7: _eval_aux_operators

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def _eval_aux_operators(self, wavefn, threshold: float = 1e-12) -> np.ndarray:
        values = []  # type: List[Tuple[float, int]]
        for operator in self._aux_operators:
            if operator is None:
                values.append(None)
                continue
            value = 0.0
            if operator.coeff != 0:
                mat = operator.to_spmatrix()
                # Terra doesn't support sparse yet, so do the matmul directly if so
                # This is necessary for the particle_hole and other chemistry tests because the
                # pauli conversions are 2^12th large and will OOM error if not sparse.
                if isinstance(mat, scisparse.spmatrix):
                    value = mat.dot(wavefn).dot(np.conj(wavefn))
                else:
                    value = StateFn(operator, is_measurement=True).eval(wavefn)
                value = value.real if abs(value.real) > threshold else 0.0
            values.append((value, 0))
        return np.asarray(values) 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:21,代码来源:numpy_eigen_solver.py

示例8: __init__

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def __init__(self,
                 quadratic_program: Any, name: str,
                 linear: Union[ndarray, spmatrix, List[float], Dict[Union[str, int], float]],
                 sense: ConstraintSense,
                 rhs: float
                 ) -> None:
        """
        Args:
            quadratic_program: The parent quadratic program.
            name: The name of the constraint.
            linear: The coefficients specifying the linear constraint.
            sense: The sense of the constraint.
            rhs: The right-hand-side of the constraint.
        """
        super().__init__(quadratic_program, name, sense, rhs)
        self._linear = LinearExpression(quadratic_program, linear) 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:18,代码来源:linear_constraint.py

示例9: minimize

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def minimize(self,
                 constant: float = 0.0,
                 linear: Union[ndarray, spmatrix, List[float], Dict[Union[str, int], float]] = None,
                 quadratic: Union[ndarray, spmatrix, List[List[float]],
                                  Dict[Tuple[Union[int, str], Union[int, str]], float]] = None
                 ) -> None:
        """Sets a quadratic objective to be minimized.

        Args:
            constant: the constant offset of the objective.
            linear: the coefficients of the linear part of the objective.
            quadratic: the coefficients of the quadratic part of the objective.

        Returns:
            The created quadratic objective.
        """
        self._objective = QuadraticObjective(self, constant, linear, quadratic,
                                             QuadraticObjective.Sense.MINIMIZE) 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:20,代码来源:quadratic_program.py

示例10: maximize

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def maximize(self,
                 constant: float = 0.0,
                 linear: Union[ndarray, spmatrix, List[float], Dict[Union[str, int], float]] = None,
                 quadratic: Union[ndarray, spmatrix, List[List[float]],
                                  Dict[Tuple[Union[int, str], Union[int, str]], float]] = None
                 ) -> None:
        """Sets a quadratic objective to be maximized.

        Args:
            constant: the constant offset of the objective.
            linear: the coefficients of the linear part of the objective.
            quadratic: the coefficients of the quadratic part of the objective.

        Returns:
            The created quadratic objective.
        """
        self._objective = QuadraticObjective(self, constant, linear, quadratic,
                                             QuadraticObjective.Sense.MAXIMIZE) 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:20,代码来源:quadratic_program.py

示例11: __init__

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def __init__(self, quadratic_program: Any,
                 coefficients: Union[ndarray, spmatrix, List[List[float]],
                                     Dict[Tuple[Union[int, str], Union[int, str]], float]]) -> None:
        """Creates a new quadratic expression.

        The quadratic expression can be defined via an array, a list, a sparse matrix, or a
        dictionary that uses variable names or indices as keys and stores the values internally as a
        dok_matrix. We stores values in a compressed way, i.e., values at symmetric positions are
        summed up in the upper triangle. For example, {(0, 1): 1, (1, 0): 2} -> {(0, 1): 3}.

        Args:
            quadratic_program: The parent QuadraticProgram.
            coefficients: The (sparse) representation of the coefficients.

        """
        super().__init__(quadratic_program)
        self.coefficients = coefficients 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:19,代码来源:quadratic_expression.py

示例12: __init__

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def __init__(self, quadratic_program: Any,
                 coefficients: Union[ndarray, spmatrix, List[float],
                                     Dict[Union[int, str], float]]) -> None:
        """Creates a new linear expression.

        The linear expression can be defined via an array, a list, a sparse matrix, or a dictionary
        that uses variable names or indices as keys and stores the values internally as a
        dok_matrix.

        Args:
            quadratic_program: The parent QuadraticProgram.
            coefficients: The (sparse) representation of the coefficients.

        """
        super().__init__(quadratic_program)
        self.coefficients = coefficients 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:18,代码来源:linear_expression.py

示例13: __init__

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def __init__(
        self,
        adata: "anndata.AnnData",
        X: Union[np.ndarray, sparse.spmatrix, None] = None,
        var: Union[pd.DataFrame, Mapping[str, Sequence], None] = None,
        varm: Union[AxisArrays, Mapping[str, np.ndarray], None] = None,
    ):
        from .anndata import _gen_dataframe

        self._adata = adata
        self._n_obs = adata.n_obs
        # construct manually
        if adata.isbacked == (X is None):
            self._X = X
            self._var = _gen_dataframe(var, self.X.shape[1], ["var_names"])
            self._varm = AxisArrays(self, 1, varm)
        elif X is None:  # construct from adata
            self._X = adata.X.copy()
            self._var = adata.var.copy()
            self._varm = AxisArrays(self, 1, adata.varm.copy())
        elif adata.isbacked:
            raise ValueError("Cannot specify X if adata is backed") 
开发者ID:theislab,项目名称:anndata,代码行数:24,代码来源:raw.py

示例14: X

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def X(self) -> Union[SparseDataset, np.ndarray, sparse.spmatrix]:
        # TODO: Handle unsorted array of integer indices for h5py.Datasets
        if not self._adata.isbacked:
            return self._X
        if not self._adata.file.is_open:
            self._adata.file.open()
        # Handle legacy file formats:
        if "raw/X" in self._adata.file:
            X = self._adata.file["raw/X"]
        elif "raw.X" in self._adata.file:
            X = self._adata.file["raw.X"]  # Backwards compat
        else:
            raise AttributeError(
                f"Could not find dataset for raw X in file: "
                f"{self._adata.file.filename}."
            )
        if isinstance(X, h5py.Group):
            X = SparseDataset(X)
        # Check if we need to subset
        if self._adata.is_view:
            # TODO: As noted above, implement views of raw
            #       so we can know if we need to subset by var
            return X[self._adata._oidx, slice(None)]
        else:
            return X 
开发者ID:theislab,项目名称:anndata,代码行数:27,代码来源:raw.py

示例15: _move_adj_mtx

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import spmatrix [as 别名]
def _move_adj_mtx(d):
    """
    Read-time fix for moving adjacency matrices from uns to obsp
    """
    n = d.get("uns", {}).get("neighbors", {})
    obsp = d.setdefault("obsp", {})

    for k in ("distances", "connectivities"):
        if (
            (k in n)
            and isinstance(n[k], (spmatrix, np.ndarray))
            and len(n[k].shape) == 2
        ):
            warn(
                f"Moving element from .uns['neighbors']['{k}'] to .obsp['{k}'].\n\n"
                "This is where adjacency matrices should go now.",
                FutureWarning,
            )
            obsp[k] = n.pop(k) 
开发者ID:theislab,项目名称:anndata,代码行数:21,代码来源:__init__.py


注:本文中的scipy.sparse.spmatrix方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。