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


Python numpy.asanyarray函数代码示例

本文整理汇总了Python中numpy.asanyarray函数的典型用法代码示例。如果您正苦于以下问题:Python asanyarray函数的具体用法?Python asanyarray怎么用?Python asanyarray使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: ravel_indices

def ravel_indices(indices, shape):
    """
    Convert nD to 1D indices for an array of given shape.
        flat_indices = ravel_indices(indices, size)
    
    :Input:
        indices: array of indices. Should be integer and have shape=([S],D), 
                 for S the "subshape" of indices array, pointing to a D dimensional array.
        shape:   shape of the nd-array these indices are pointing to (a tuple/list/ of length D)
        
    :Output: 
        flat_indices: an array of shape S
    
    :Note: 
       This is the opposite of unravel_indices: for any tuple 'shape'
          ind is equal to    ravel_indices(unravel_indices(ind,shape),shape)
                   and to  unravel_indices(  ravel_indices(ind,shape),shape)
    """
    dim_prod = _np.cumprod([1] + list(shape)[:0:-1])[_np.newaxis,::-1]
    ind = _np.asanyarray(indices)
    S   = ind.shape[:-1]
    K   = _np.asanyarray(shape).size
    ind.shape = S + (K,)
    
    return _np.sum(ind*dim_prod,-1)
开发者ID:julien-diener,项目名称:ndarray,代码行数:25,代码来源:__init__.py

示例2: fit

    def fit(self, X, y, **params):
        """
        Fit Ridge regression model

        Parameters
        ----------
        X : numpy array of shape [n_samples,n_features]
            Training data
        y : numpy array of shape [n_samples]
            Target values

        Returns
        -------
        self : returns an instance of self.
        """
        self._set_params(**params)

        X = np.asanyarray(X, dtype=np.float)
        y = np.asanyarray(y, dtype=np.float)

        n_samples, n_features = X.shape

        X, y, Xmean, ymean = self._center_data(X, y)

        if n_samples > n_features:
            # w = inv(X^t X + alpha*Id) * X.T y
            self.coef_ = linalg.solve(np.dot(X.T, X) + self.alpha * np.eye(n_features), np.dot(X.T, y))
        else:
            # w = X.T * inv(X X^t + alpha*Id) y
            self.coef_ = np.dot(X.T, linalg.solve(np.dot(X, X.T) + self.alpha * np.eye(n_samples), y))

        self._set_intercept(Xmean, ymean)
        return self
开发者ID:kurtosis-zz,项目名称:scikit-learn,代码行数:33,代码来源:ridge.py

示例3: eval

 def eval(self, x, y):
     """Evaluate model at a given position ``(x, y)`` position.
     """
     x = np.asanyarray(x, dtype=float)
     y = np.asanyarray(y, dtype=float)
     parvals = self.parvals(x)
     return self._eval_y(y, parvals)
开发者ID:ellisowen,项目名称:gammapy,代码行数:7,代码来源:models.py

示例4: __call__

    def __call__(self, projectables, **info):
        if len(projectables) != 2:
            raise ValueError("Expected 2 datasets, got %d" %
                             (len(projectables), ))

        # TODO: support datasets with palette to delegate this to the image
        # writer.

        data, palette = projectables
        palette = np.asanyarray(palette).squeeze() / 255.0
        colormap = self.build_colormap(palette, data.dtype, data.attrs)

        channels, colors = colormap.palettize(np.asanyarray(data.squeeze()))
        channels = palette[channels]
        fill_value = data.attrs.get('_FillValue', np.nan)
        if np.isnan(fill_value):
            mask = data.notnull()
        else:
            mask = data != data.attrs['_FillValue']
        r = xr.DataArray(channels[:, :, 0].reshape(data.shape),
                         dims=data.dims, coords=data.coords,
                         attrs=data.attrs).where(mask)
        g = xr.DataArray(channels[:, :, 1].reshape(data.shape),
                         dims=data.dims, coords=data.coords,
                         attrs=data.attrs).where(mask)
        b = xr.DataArray(channels[:, :, 2].reshape(data.shape),
                         dims=data.dims, coords=data.coords,
                         attrs=data.attrs).where(mask)

        res = super(PaletteCompositor, self).__call__((r, g, b), **data.attrs)
        res.attrs['_FillValue'] = np.nan
        return res
开发者ID:davidh-ssec,项目名称:satpy,代码行数:32,代码来源:__init__.py

示例5: fit

    def fit(self, X, y):
        """
        Fit linear model.

        Parameters
        ----------
        X : numpy array of shape [n_samples,n_features]
            Training data
        y : numpy array of shape [n_samples]
            Target values
        fit_intercept : boolean, optional
            wether to calculate the intercept for this model. If set
            to false, no intercept will be used in calculations
            (e.g. data is expected to be already centered).
        normalize : boolean, optional
            If True, the regressors X are normalized

        Returns
        -------
        self : returns an instance of self.
        """
        X = np.asanyarray(X)
        y = np.asanyarray(y)

        X, y, X_mean, y_mean, X_std = self._center_data(X, y,
                self.fit_intercept, self.normalize, self.copy_X)

        self.coef_, self.residues_, self.rank_, self.singular_ = \
                np.linalg.lstsq(X, y)

        self._set_intercept(X_mean, y_mean, X_std)
        return self
开发者ID:lymantc,项目名称:scikit-learn,代码行数:32,代码来源:base.py

示例6: __init__

    def __init__(self, points, inside=None):
        r"""
        Parameters
        ----------
        points : An Nx3 array of (*x*, *y*, *z*) triples in vector space
            These points define the boundary of the polygon.  It must
            be "closed", i.e., the last point is the same as the first.

            It may contain zero points, in which it defines the null
            polygon.  It may not contain one, two or three points.
            Four points are needed to define a triangle, since the
            polygon must be closed.

        inside : An (*x*, *y*, *z*) triple, optional
            This point must be inside the polygon.  If not provided, the
            mean of the points will be used.
        """
        if len(points) == 0:
            # handle special case of initializing with an empty list of
            # vertices (ticket #1079).
            self._inside = np.zeros(3)
            self._points = np.asanyarray(points)
            return
        elif len(points) < 3:
            raise ValueError("Polygon made of too few points")
        else:
            assert np.array_equal(points[0], points[-1]), 'Polygon is not closed'

        self._points = points = np.asanyarray(points)

        if inside is None:
            self._inside = self._find_new_inside(points)
        else:
            self._inside = np.asanyarray(inside)
开发者ID:jhunkeler,项目名称:stsci.sphere,代码行数:34,代码来源:polygon.py

示例7: chi2

def chi2(N_S, B, S, sigma2):
    r"""Chi-square statistic with user-specified variance.

     .. math::

         \chi^2 = \frac{(N_S - B - S) ^ 2}{\sigma ^ 2}

    Parameters
    ----------
    N_S : array_like
        Number of observed counts
    B : array_like
        Model background
    S : array_like
        Model signal
    sigma2 : array_like
        Variance

    Returns
    -------
    stat : ndarray
        Statistic per bin

    References
    ----------
    * Sherpa stats page (http://cxc.cfa.harvard.edu/sherpa/statistics/#chisq)
    """
    N_S = np.asanyarray(N_S, dtype=np.float64)
    B = np.asanyarray(B, dtype=np.float64)
    S = np.asanyarray(S, dtype=np.float64)
    sigma2 = np.asanyarray(sigma2, dtype=np.float64)

    stat = (N_S - B - S) ** 2 / sigma2

    return stat
开发者ID:mahmoud-lsw,项目名称:gammapy,代码行数:35,代码来源:fit_statistics.py

示例8: fit

    def fit(self, X, y, **params):
        """
        Fit linear model.

        Parameters
        ----------
        X : numpy array of shape [n_samples,n_features]
            Training data
        y : numpy array of shape [n_samples]
            Target values
        fit_intercept : boolean, optional
            wether to calculate the intercept for this model. If set
            to false, no intercept will be used in calculations
            (e.g. data is expected to be already centered).

        Returns
        -------
        self : returns an instance of self.
        """
        self._set_params(**params)
        X = np.asanyarray(X)
        y = np.asanyarray(y)

        X, y, Xmean, ymean = LinearModel._center_data(X, y, self.fit_intercept)

        self.coef_, self.residues_, self.rank_, self.singular_ = \
                np.linalg.lstsq(X, y)

        self._set_intercept(Xmean, ymean)
        return self
开发者ID:aayushsaxena15,项目名称:projects,代码行数:30,代码来源:base.py

示例9: predict

    def predict(self, X, copy=True):
        """Apply the dimension reduction learned on the train data.
            Parameters
            ----------
            X: array-like of predictors, shape (n_samples, p)
                Training vectors, where n_samples in the number of samples and
                p is the number of predictors.

            copy: X has to be normalize, do it on a copy or in place
                with side effect!

            Notes
            -----
            This call require the estimation of a p x q matrix, which may
            be an issue in high dimensional space.
        """
        # Normalize
        if copy:
            Xc = (np.asanyarray(X) - self.x_mean_)
        else:
            X = np.asanyarray(X)
            Xc -= self.x_mean_
            Xc /= self.x_std_
        Ypred = np.dot(Xc, self.coefs)
        return Ypred + self.y_mean_
开发者ID:dattanchu,项目名称:scikit-learn,代码行数:25,代码来源:pls.py

示例10: background_error

def background_error(n_off, alpha):
    r"""Estimate standard error on background
    in the on region from an off-region observation.

    .. math::

          \Delta\mu_{bkg} = \alpha \times \sqrt{n_{off}}

    Parameters
    ----------
    n_off : array_like
        Observed number of counts in the off region
    alpha : array_like
        On / off region exposure ratio for background events

    Returns
    -------
    background : ndarray
        Background estimate for the on region

    Examples
    --------
    >>> background_error(n_off=4, alpha=0.1)
    0.2
    >>> background_error(n_off=9, alpha=0.2)
    0.6
    """
    n_off = np.asanyarray(n_off, dtype=np.float64)
    alpha = np.asanyarray(alpha, dtype=np.float64)

    return alpha * sqrt(n_off)
开发者ID:registerrier,项目名称:gammapy,代码行数:31,代码来源:poisson.py

示例11: excess

def excess(n_on, n_off, alpha):
    r"""Estimate excess in the on region for an on-off observation.

    .. math::

          \mu_{excess} = n_{on} - \alpha \times n_{off}

    Parameters
    ----------
    n_on : array_like
        Observed number of counts in the on region
    n_off : array_like
        Observed number of counts in the off region
    alpha : array_like
        On / off region exposure ratio for background events

    Returns
    -------
    excess : ndarray
        Excess estimate for the on region

    Examples
    --------
    >>> excess(n_on=10, n_off=20, alpha=0.1)
    8.0
    >>> excess(n_on=4, n_off=9, alpha=0.5)
    -0.5
    """
    n_on = np.asanyarray(n_on, dtype=np.float64)
    n_off = np.asanyarray(n_off, dtype=np.float64)
    alpha = np.asanyarray(alpha, dtype=np.float64)

    return n_on - alpha * n_off
开发者ID:registerrier,项目名称:gammapy,代码行数:33,代码来源:poisson.py

示例12: background

def background(n_off, alpha):
    r"""Estimate background in the on-region from an off-region observation.

    .. math::

        \mu_{background} = \alpha \times n_{off}

    Parameters
    ----------
    n_off : array_like
        Observed number of counts in the off region
    alpha : array_like
        On / off region exposure ratio for background events

    Returns
    -------
    background : ndarray
        Background estimate for the on region

    Examples
    --------
    >>> background(n_off=4, alpha=0.1)
    0.4
    >>> background(n_off=9, alpha=0.2)
    1.8
    """
    n_off = np.asanyarray(n_off, dtype=np.float64)
    alpha = np.asanyarray(alpha, dtype=np.float64)

    return alpha * n_off
开发者ID:registerrier,项目名称:gammapy,代码行数:30,代码来源:poisson.py

示例13: fit

    def fit(self, X, y, **params):
        """Fit the model using X, y as training data

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training data.

        y : array-like, shape = [n_samples]
            Target values, array of integer values.

        params : list of keyword, optional
            Overwrite keywords from __init__
        """
        X = np.asanyarray(X)
        if y is None:
            raise ValueError("y must not be None")
        self._y = np.asanyarray(y)
        self._set_params(**params)

        if self.algorithm == 'ball_tree' or \
           (self.algorithm == 'auto' and X.shape[1] < 20):
            self.ball_tree = BallTree(X, self.window_size)
        else:
            self.ball_tree = None
            self._fit_X = X
        return self
开发者ID:scollis,项目名称:scikit-learn,代码行数:27,代码来源:neighbors.py

示例14: unravel_indices

def unravel_indices(indices,shape):
    """
    Convert indices in a flatten array to nD indices of the array with given shape.
        nd_indices = unravel_indices(indices, shape)
    
    :Input:
        indices: array/list/tuple of flat indices. Should be integer, of any shape S
        shape:   nD shape of the array these indices are pointing to
        
    :Output: 
        nd_indices: a nd-array of shape [S]xK, where 
                    [S] is the shape of indices input argument
                    and K the size (number of element) of shape     
    
    :Note:
        The algorithm has been inspired from numpy.unravel_index 
        and can be seen as a generalization that manage set of indices
        However, it does not return tuples and no assertion is done on 
        the input indices before convertion:
        The output indices might be negative or bigger than the array size
        
        This is the opposite of ravel_indices:  for any tuple 'shape'
          ind is equal to    ravel_indices(unravel_indices(ind,shape),shape)
                   and to  unravel_indices(  ravel_indices(ind,shape),shape)
    """

    dim_prod = _np.cumprod([1] + list(shape)[:0:-1])[::-1]
    ind = _np.asanyarray(indices)
    S   = ind.shape
    K   = _np.asanyarray(shape).size
    
    ndInd = ind.ravel()[:,_np.newaxis]/dim_prod % shape
    ndInd.shape = S + (K,)
    return ndInd
开发者ID:julien-diener,项目名称:ndarray,代码行数:34,代码来源:__init__.py

示例15: interp

def interp(x, xp, fp, left=None, right=None):
    """
    Like numpy.interp except for handling of running sequences of
    same values in `xp`.
    """
    x = numpy.asanyarray(x)
    xp = numpy.asanyarray(xp)
    fp = numpy.asanyarray(fp)

    if xp.shape != fp.shape:
        raise ValueError("xp and fp must have the same shape")

    ind = numpy.searchsorted(xp, x, side="right")
    fx = numpy.zeros(len(x))

    under = ind == 0
    over = ind == len(xp)
    between = ~under & ~over

    fx[under] = left if left is not None else fp[0]
    fx[over] = right if right is not None else fp[-1]

    if right is not None:
        # Fix points exactly on the right boundary.
        fx[x == xp[-1]] = fp[-1]

    ind = ind[between]

    df = (fp[ind] - fp[ind - 1]) / (xp[ind] - xp[ind - 1])

    fx[between] = df * (x[between] - xp[ind]) + fp[ind]

    return fx
开发者ID:randxie,项目名称:orange3,代码行数:33,代码来源:owrocanalysis.py


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