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


Python numpy.geomspace方法代码示例

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


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

示例1: test_celer_path_logreg

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def test_celer_path_logreg():
    X, y = build_dataset(
        n_samples=50, n_features=100, sparse_X=True)
    y = np.sign(y)
    alpha_max = norm(X.T.dot(y), ord=np.inf) / 2
    alphas = alpha_max * np.geomspace(1, 1e-2, 10)

    tol = 1e-8
    coefs, Cs, n_iters = _logistic_regression_path(
        X, y, Cs=1. / alphas, fit_intercept=False, penalty='l1',
        solver='liblinear', tol=tol)

    _, coefs_c, gaps = celer_path(
        X, y, "logreg", alphas=alphas, tol=tol, verbose=2)

    np.testing.assert_array_less(gaps, tol)
    np.testing.assert_allclose(coefs != 0, coefs_c.T != 0)
    np.testing.assert_allclose(coefs, coefs_c.T, atol=1e-5, rtol=1e-3) 
开发者ID:mathurinm,项目名称:celer,代码行数:20,代码来源:test_lasso.py

示例2: test_scott_vs_stone

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def test_scott_vs_stone(self):
        """Verify that Scott's rule and Stone's rule converges for normally distributed data"""

        def nbins_ratio(seed, size):
            rng = np.random.RandomState(seed)
            x = rng.normal(loc=0, scale=2, size=size)
            a, b = len(np.histogram(x, 'stone')[0]), len(np.histogram(x, 'scott')[0])
            return a / (a + b)

        ll = [[nbins_ratio(seed, size) for size in np.geomspace(start=10, stop=100, num=4).round().astype(int)]
              for seed in range(256)]

        # the average difference between the two methods decreases as the dataset size increases.
        assert_almost_equal(abs(np.mean(ll, axis=0) - 0.5),
                            [0.1065248,
                             0.0968844,
                             0.0331818,
                             0.0178057],
                            decimal=3) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_histograms.py

示例3: next

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def next(self, state, **runopts):
        bqm = state.problem

        # get a reasonable beta range
        beta_hot, beta_cold = neal.default_beta_range(bqm)

        # generate betas for all branches/replicas
        betas = np.geomspace(beta_hot, beta_cold, self.num_replicas)

        # create num_replicas with betas spaced with geometric progression
        states = hybrid.States(*[state.updated(beta=b) for b in betas])

        return states


#
# A few PT workflow generators. Should be treated as Runnable classes
# 
开发者ID:dwavesystems,项目名称:dwave-hybrid,代码行数:20,代码来源:pt.py

示例4: next

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def next(self, state, **runopts):
        bqm = state.problem

        # get a reasonable beta range
        beta_hot, beta_cold = neal.default_beta_range(bqm)

        # generate betas
        if self.interpolation == 'linear':
            beta_schedule = np.linspace(beta_hot, beta_cold, self.length)
        elif self.interpolation == 'geometric':
            beta_schedule = np.geomspace(beta_hot, beta_cold, self.length)
        else:
            raise ValueError("Beta schedule type {} not implemented".format(self.interpolation))

        # store the schedule in output state
        return state.updated(beta_schedule=beta_schedule) 
开发者ID:dwavesystems,项目名称:dwave-hybrid,代码行数:18,代码来源:pa.py

示例5: geomspace

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def geomspace(start, stop, num=50, endpoint=True, dtype=float):  # pylint: disable=missing-docstring
  if dtype:
    dtype = utils.result_type(dtype)
  if num < 0:
    raise ValueError('Number of samples {} must be non-negative.'.format(num))
  if not num:
    return empty([0])
  step = 1.
  if endpoint:
    if num > 1:
      step = tf.pow((stop / start), 1 / (num - 1))
  else:
    step = tf.pow((stop / start), 1 / num)
  result = tf.cast(tf.range(num), step.dtype)
  result = tf.pow(step, result)
  result = tf.multiply(result, start)
  if dtype:
    result = tf.cast(result, dtype=dtype)
  return arrays_lib.tensor_to_ndarray(result)


# Building matrices. 
开发者ID:google,项目名称:trax,代码行数:24,代码来源:array_ops.py

示例6: testGeomSpace

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def testGeomSpace(self):

    def run_test(start, stop, **kwargs):
      arg1 = start
      arg2 = stop
      self.match(
          array_ops.geomspace(arg1, arg2, **kwargs),
          np.geomspace(arg1, arg2, **kwargs),
          msg='geomspace({}, {})'.format(arg1, arg2),
          almost=True,
          decimal=4)

    run_test(1, 1000, num=5)
    run_test(1, 1000, num=5, endpoint=False)
    run_test(-1, -1000, num=5)
    run_test(-1, -1000, num=5, endpoint=False) 
开发者ID:google,项目名称:trax,代码行数:18,代码来源:array_ops_test.py

示例7: monkeypatch

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def monkeypatch():
    """
    monkeypatch built-in numpy functions to call those provided by nparray instead.

    ```py
    import nparray
    import numpy as np

    nparray.monkeypatch()
    print(np.linspace(0,1,11))
    ```

    """
    np.array = array
    np.arange = arange
    np.linspace = linspace
    np.logspace = logspace
    np.geomspace = geomspace
    np.full = full
    np.full_like = full_like
    np.zeros = zeros
    np.zeros_like = zeros_like
    np.ones = ones
    np.ones_like = ones_like
    np.eye = eye 
开发者ID:phoebe-project,项目名称:phoebe2,代码行数:27,代码来源:__init__.py

示例8: generate_combo

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def generate_combo(self, params_dict):
        """
        Method to generate all combinations from a given set of key-value pairs
        
        Args:
            params_dict: Set of key-value pairs with the key being the param name and the value being the list of values
            you want to try for that param
        
        Returns:
            new_dict: The list of all combinations of parameters
        """
        if not params_dict:
            return None

        new_dict = {}
        for key, value in params_dict.items():
            assert isinstance(value, collections.Iterable)
            if key == 'layers':
                new_dict[key] = value
            elif type(value[0]) != str:
                tmp_list = list(np.geomspace(value[0], value[1], value[2]))
                if key in self.convert_to_int:
                    new_dict[key] = [int(x) for x in tmp_list]
                else:
                    new_dict[key] = tmp_list
            else:
                new_dict[key] = value
        return new_dict 
开发者ID:ATOMconsortium,项目名称:AMPL,代码行数:30,代码来源:hyperparam_search_wrapper.py

示例9: testGeomspace

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def testGeomspace(self, start_shape, stop_shape, num,
                    endpoint, dtype, rng_factory):
    rng = rng_factory()
    # relax default tolerances slightly
    tol = {onp.float16: 4e-3, onp.float32: 2e-3, onp.complex128: 1e-14}
    def args_maker():
      """Test the set of inputs onp.geomspace is well-defined on."""
      start, stop = self._GetArgsMaker(rng,
                                [start_shape, stop_shape],
                                [dtype, dtype])()
      # onp.geomspace can't handle differently ranked tensors
      # w. negative numbers!
      start, stop = lnp.broadcast_arrays(start, stop)
      if dtype in complex_dtypes:
        return start, stop
      # to avoid NaNs, non-complex start and stop cannot
      # differ in sign, elementwise
      start = start * lnp.sign(start) * lnp.sign(stop)
      return start, stop
    start, stop = args_maker()
    ndim = len(onp.shape(start + stop))
    for axis in range(-ndim, ndim):
      def lnp_op(start, stop):
        return lnp.geomspace(start, stop, num, endpoint=endpoint, dtype=dtype,
                             axis=axis)
      def onp_op(start, stop):
        start = start.astype(onp.float32) if dtype == lnp.bfloat16 else start
        stop = stop.astype(onp.float32) if dtype == lnp.bfloat16 else stop
        return onp.geomspace(
          start, stop, num, endpoint=endpoint,
          dtype=dtype if dtype != lnp.bfloat16 else onp.float32,
          axis=axis).astype(dtype)
      self._CheckAgainstNumpy(onp_op, lnp_op, args_maker,
                              check_dtypes=False, tol=tol)
      if dtype in (inexact_dtypes + [None,]):
        self._CompileAndCheck(lnp_op, args_maker,
                              check_dtypes=False, atol=tol, rtol=tol,
                              check_incomplete_shape=True) 
开发者ID:google,项目名称:trax,代码行数:40,代码来源:lax_numpy_test.py

示例10: _lasso

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def _lasso(self):
        """Order features according to their corresponding coefficients."""
        if self.line_search:
            pred = None
            try:
                alpha_list = np.geomspace(self.max_alpha, self.min_alpha,
                                          self.steps)
            except AttributeError:
                alpha_list = np.exp(np.linspace(np.log(self.max_alpha),
                                                np.log(self.min_alpha),
                                                self.steps))
            for alpha in alpha_list:
                regr = Lasso(alpha=alpha, max_iter=self.iter,
                             fit_intercept=True, normalize=True,
                             selection='random')
                model = regr.fit(self.train_matrix, self.train_target)
                nz = len(model.coef_) - (model.coef_ == 0.).sum()
                if nz >= self.size:
                    coeff = model.coef_
                    break
        else:
            regr = LassoCV(fit_intercept=True, normalize=True,
                           n_alphas=self.steps, max_iter=self.iter,
                           eps=self.eps, cv=None)
            model = regr.fit(X=self.train_matrix, y=self.train_target)
            coeff = model.coef_

            # Make the linear prediction.
            pred = None
            if self.predict:
                data = model.predict(self.test_matrix)
                pred = get_error(prediction=data,
                                 target=self.test_target)['average']

        return coeff, pred 
开发者ID:SUNCAT-Center,项目名称:CatLearn,代码行数:37,代码来源:scikit_wrapper.py

示例11: preceding_sent_weighed_similarity

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def preceding_sent_weighed_similarity(self, sent_list,
                                                item,
                                                k=5,
                                                start=1.1,
                                                end=0.8,
                                                *args):
        k = min(len(sent_list), k)
        return np.arange(k), np.geomspace(start, end, k) 
开发者ID:easonnie,项目名称:combine-FEVER-NSMN,代码行数:10,代码来源:item_rules.py

示例12: bin_dataframe

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def bin_dataframe(df, n_bins):
    """
    Assign a "bin" column to the dataframe to indicate which bin the true
    charges belong to.

    Bins are assigned in log space.

    Parameters
    ----------
    df : pd.DataFrame
    n_bins : int
        Number of bins to allow in range

    Returns
    -------
    pd.DataFrame
    """
    true = df["true"].values
    min_ = true.min()
    max_ = true.max()
    bins = np.geomspace(min_, max_, n_bins)
    log_bin_width = np.diff(np.log10(bins))[0]
    bins = np.append(bins, 10 ** (np.log10(bins[-1]) + log_bin_width))
    df["bin"] = np.digitize(true, bins, right=True) - 1

    return df 
开发者ID:cta-observatory,项目名称:ctapipe,代码行数:28,代码来源:charge_resolution.py

示例13: get_length

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def get_length(matrix):
    if matrix.IDENTIFIER == V1HpChoice.IDENTIFIER:
        return len(matrix.value)
    if matrix.IDENTIFIER == V1HpPChoice.IDENTIFIER:
        return len(matrix.value)

    if matrix.IDENTIFIER == V1HpRange.IDENTIFIER:
        return len(np.arange(**matrix.value))

    if matrix.IDENTIFIER == V1HpLinSpace.IDENTIFIER:
        return len(np.linspace(**matrix.value))

    if matrix.IDENTIFIER == V1HpLogSpace.IDENTIFIER:
        return len(np.logspace(**matrix.value))

    if matrix.IDENTIFIER == V1HpGeomSpace.IDENTIFIER:
        return len(np.geomspace(**matrix.value))

    if matrix.IDENTIFIER in {
        V1HpUniform.IDENTIFIER,
        V1HpQUniform.IDENTIFIER,
        V1HpLogUniform.IDENTIFIER,
        V1HpQLogUniform.IDENTIFIER,
        V1HpNormal.IDENTIFIER,
        V1HpQNormal.IDENTIFIER,
        V1HpLogNormal.IDENTIFIER,
        V1HpQLogNormal.IDENTIFIER,
    }:
        raise ValidationError("Distribution should not call `length`") 
开发者ID:polyaxon,项目名称:polyaxon,代码行数:31,代码来源:utils.py

示例14: to_numpy

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def to_numpy(matrix):
    if matrix.IDENTIFIER == V1HpChoice.IDENTIFIER:
        return matrix.value
    if matrix.IDENTIFIER == V1HpPChoice.IDENTIFIER:
        raise ValidationError(
            "Distribution should not call `to_numpy`, "
            "instead it should call `sample`."
        )

    if matrix.IDENTIFIER == V1HpRange.IDENTIFIER:
        return np.arange(**matrix.value)

    if matrix.IDENTIFIER == V1HpLinSpace.IDENTIFIER:
        return np.linspace(**matrix.value)

    if matrix.IDENTIFIER == V1HpLogSpace.IDENTIFIER:
        return np.logspace(**matrix.value)

    if matrix.IDENTIFIER == V1HpGeomSpace.IDENTIFIER:
        return np.geomspace(**matrix.value)

    if matrix.IDENTIFIER in {
        V1HpUniform.IDENTIFIER,
        V1HpQUniform.IDENTIFIER,
        V1HpLogUniform.IDENTIFIER,
        V1HpQLogUniform.IDENTIFIER,
        V1HpNormal.IDENTIFIER,
        V1HpQNormal.IDENTIFIER,
        V1HpLogNormal.IDENTIFIER,
        V1HpQLogNormal.IDENTIFIER,
    }:
        raise ValidationError(
            "Distribution should not call `to_numpy`, "
            "instead it should call `sample`."
        ) 
开发者ID:polyaxon,项目名称:polyaxon,代码行数:37,代码来源:utils.py

示例15: logspace

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import geomspace [as 别名]
def logspace(start, stop, num, endpoint=True, base=10.0, unit=None):
    """
    See also:

    * <nparray.geomspace>

    Arguments
    ------------
    * `start` (int or float): ``base ** start`` is the starting value of the sequence.
    * `stop` (int or float): ``base ** stop`` is the final value of the sequence,
        unless `endpoint` is False.  In that case, ``num + 1`` values are spaced
        over the interval in log-space, of which all but the last (a sequence of
        length `num`) are returned.
    * `num` (int): number of samples to generate.
    * `endpoint` (bool, optional, default=True): If True, `stop` is the last
        sample. Otherwise, it is not included.
    * `base` (float, optional, default=10.0): The base of the log space. The
        step size between the elements in ``ln(samples) / ln(base)``
        (or ``log_base(samples)``) is uniform.
    * `unit` (astropy unit or string, optional, default=None): unit
      corresponding to the passed values.

    Returns
    -----------
    * <Logspace>
    """
    return _wrappers.Logspace(start, stop, num, endpoint, base, unit) 
开发者ID:phoebe-project,项目名称:phoebe2,代码行数:29,代码来源:__init__.py


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