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


Python numpy.isinf方法代码示例

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


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

示例1: _compute_delta

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def _compute_delta(log_moments, eps):
  """Compute delta for given log_moments and eps.

  Args:
    log_moments: the log moments of privacy loss, in the form of pairs
      of (moment_order, log_moment)
    eps: the target epsilon.
  Returns:
    delta
  """
  min_delta = 1.0
  for moment_order, log_moment in log_moments:
    if moment_order == 0:
      continue
    if math.isinf(log_moment) or math.isnan(log_moment):
      sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
      continue
    if log_moment < moment_order * eps:
      min_delta = min(min_delta,
                      math.exp(log_moment - moment_order * eps))
  return min_delta 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:23,代码来源:gaussian_moments.py

示例2: _compute_eps

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def _compute_eps(log_moments, delta):
  """Compute epsilon for given log_moments and delta.

  Args:
    log_moments: the log moments of privacy loss, in the form of pairs
      of (moment_order, log_moment)
    delta: the target delta.
  Returns:
    epsilon
  """
  min_eps = float("inf")
  for moment_order, log_moment in log_moments:
    if moment_order == 0:
      continue
    if math.isinf(log_moment) or math.isnan(log_moment):
      sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
      continue
    min_eps = min(min_eps, (log_moment - math.log(delta)) / moment_order)
  return min_eps 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:21,代码来源:gaussian_moments.py

示例3: normalize_adj

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def normalize_adj(A, is_sym=True, exponent=0.5):
  """
    Normalize adjacency matrix

    is_sym=True: D^{-1/2} A D^{-1/2}
    is_sym=False: D^{-1} A
  """
  rowsum = np.array(A.sum(1))

  if is_sym:
    r_inv = np.power(rowsum, -exponent).flatten()
  else:
    r_inv = np.power(rowsum, -1.0).flatten()

  r_inv[np.isinf(r_inv)] = 0.

  if sp.isspmatrix(A):
    r_mat_inv = sp.diags(r_inv.squeeze())
  else:
    r_mat_inv = np.diag(r_inv)

  if is_sym:
    return r_mat_inv.dot(A).dot(r_mat_inv)
  else:
    return r_mat_inv.dot(A) 
开发者ID:lrjconan,项目名称:LanczosNetwork,代码行数:27,代码来源:data_helper.py

示例4: _get_numeric_feature_analysis_data

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def _get_numeric_feature_analysis_data(self, series, output):

	logger.info("Checking series of type: %s (isM8=%s)" % (series.dtype, series.dtype == np.dtype('M8[ns]')))

	if np.isinf(series).any():
	    raise ValueError("Numeric feature '%s' contains Infinity values" % name)

	output['stats'] = {
	    'min': series.min(),
	    'average': series.mean(),
	    'median': series.median(),
	    'max': series.max(),
	    'p99': series.quantile(0.99),
	    'std': series.std()
	}
        output['nulls_count'] = series.isnull().sum()

        return output 
开发者ID:dataiku,项目名称:dataiku-contrib,代码行数:20,代码来源:data_collection.py

示例5: test_float

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def test_float(self):
        # offset for alignment test
        for i in range(4):
            assert_array_equal(self.f[i:] > 0, self.ef[i:])
            assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:])
            assert_array_equal(self.f[i:] == 0, ~self.ef[i:])
            assert_array_equal(-self.f[i:] < 0, self.ef[i:])
            assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:])
            r = self.f[i:] != 0
            assert_array_equal(r, self.ef[i:])
            r2 = self.f[i:] != np.zeros_like(self.f[i:])
            r3 = 0 != self.f[i:]
            assert_array_equal(r, r2)
            assert_array_equal(r, r3)
            # check bool == 0x1
            assert_array_equal(r.view(np.int8), r.astype(np.int8))
            assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
            assert_array_equal(r3.view(np.int8), r3.astype(np.int8))

            # isnan on amd64 takes the same code path
            assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:])
            assert_array_equal(np.isfinite(self.nf[i:]), ~self.ef[i:])
            assert_array_equal(np.isfinite(self.inff[i:]), ~self.ef[i:])
            assert_array_equal(np.isinf(self.inff[i:]), self.efnonan[i:])
            assert_array_equal(np.signbit(self.signf[i:]), self.ef[i:]) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:test_numeric.py

示例6: test_double

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def test_double(self):
        # offset for alignment test
        for i in range(2):
            assert_array_equal(self.d[i:] > 0, self.ed[i:])
            assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:])
            assert_array_equal(self.d[i:] == 0, ~self.ed[i:])
            assert_array_equal(-self.d[i:] < 0, self.ed[i:])
            assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:])
            r = self.d[i:] != 0
            assert_array_equal(r, self.ed[i:])
            r2 = self.d[i:] != np.zeros_like(self.d[i:])
            r3 = 0 != self.d[i:]
            assert_array_equal(r, r2)
            assert_array_equal(r, r3)
            # check bool == 0x1
            assert_array_equal(r.view(np.int8), r.astype(np.int8))
            assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
            assert_array_equal(r3.view(np.int8), r3.astype(np.int8))

            # isnan on amd64 takes the same code path
            assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:])
            assert_array_equal(np.isfinite(self.nd[i:]), ~self.ed[i:])
            assert_array_equal(np.isfinite(self.infd[i:]), ~self.ed[i:])
            assert_array_equal(np.isinf(self.infd[i:]), self.ednonan[i:])
            assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:]) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:test_numeric.py

示例7: test_zero_division

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def test_zero_division(self):
        with np.errstate(all="ignore"):
            for t in [np.complex64, np.complex128]:
                a = t(0.0)
                b = t(1.0)
                assert_(np.isinf(b/a))
                b = t(complex(np.inf, np.inf))
                assert_(np.isinf(b/a))
                b = t(complex(np.inf, np.nan))
                assert_(np.isinf(b/a))
                b = t(complex(np.nan, np.inf))
                assert_(np.isinf(b/a))
                b = t(complex(np.nan, np.nan))
                assert_(np.isnan(b/a))
                b = t(0.)
                assert_(np.isnan(b/a)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:18,代码来源:test_scalarmath.py

示例8: test_numpy_type_funcs

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def test_numpy_type_funcs(func):
    # for func in [np.isfinite, np.isinf, np.isnan, np.signbit]:
    # copy and paste from idx fixture as pytest doesn't support
    # parameters and fixtures at the same time.
    major_axis = Index(['foo', 'bar', 'baz', 'qux'])
    minor_axis = Index(['one', 'two'])
    major_codes = np.array([0, 0, 1, 2, 3, 3])
    minor_codes = np.array([0, 1, 0, 1, 0, 1])
    index_names = ['first', 'second']

    idx = MultiIndex(
        levels=[major_axis, minor_axis],
        codes=[major_codes, minor_codes],
        names=index_names,
        verify_integrity=False
    )

    with pytest.raises(Exception):
        func(idx) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_analytics.py

示例9: test_sum_inf

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def test_sum_inf(self):
        s = Series(np.random.randn(10))
        s2 = s.copy()

        s[5:8] = np.inf
        s2[5:8] = np.nan

        assert np.isinf(s.sum())

        arr = np.random.randn(100, 100).astype('f4')
        arr[:, 2] = np.inf

        with pd.option_context("mode.use_inf_as_na", True):
            tm.assert_almost_equal(s.sum(), s2.sum())

        res = nanops.nansum(arr, axis=1)
        assert np.isinf(res).all() 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,代码来源:test_reductions.py

示例10: _get_viewpoint_estimation_labels

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def _get_viewpoint_estimation_labels(viewpoint_data, clss, num_classes):
    """Bounding-box regression targets are stored in a compact form in the
    roidb.

    This function expands those targets into the 4-of-4*K representation used
    by the network (i.e. only one class has non-zero targets). The loss weights
    are similarly expanded.

    Returns:
        view_target_data (ndarray): N x 3K blob of regression targets
        view_loss_weights (ndarray): N x 3K blob of loss weights
    """
    view_targets = np.zeros((clss.size, 3 * num_classes), dtype=np.float32)
    view_loss_weights = np.zeros(view_targets.shape, dtype=np.float32)
    inds = np.where( (clss > 0) & np.isfinite(viewpoint_data[:,0]) & np.isfinite(viewpoint_data[:,1]) & np.isfinite(viewpoint_data[:,2]) )[0]
    for ind in inds:
        cls = clss[ind]
        start = 3 * cls
        end = start + 3
        view_targets[ind, start:end] = viewpoint_data[ind, :]
        view_loss_weights[ind, start:end] = [1., 1., 1.]

    assert not np.isinf(view_targets).any(), 'viewpoint undefined'
    return view_targets, view_loss_weights 
开发者ID:CharlesShang,项目名称:TFFRCNN,代码行数:26,代码来源:minibatch2.py

示例11: _check_1d_arrays

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def _check_1d_arrays(a: ndarray, b: ndarray, kind: str, tol: float = 10 ** -4) -> bool:
    if kind == 'O':
        if not va.is_equal_1d_object(a, b):
            raise AssertionError(f'The values of the columns are not equal')
        return True
    elif kind == 'f':
        with np.errstate(invalid='ignore'):
            criteria1 = np.abs(a - b) < tol
            criteria2 = np.isnan(a) & np.isnan(b)
            criteria3 = np.isinf(a) & np.isinf(b)
        return (criteria1 | criteria2 | criteria3).all()
    else:
        try:
            np.testing.assert_array_equal(a, b)
        except AssertionError:
            return False
        return True 
开发者ID:dexplo,项目名称:dexplo,代码行数:19,代码来源:testing.py

示例12: map

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def map(self, data):
        data = data[self.fieldName]
        colors = np.empty((len(data), 4))
        default = np.array(fn.colorTuple(self['Default'])) / 255.
        colors[:] = default
        
        for v in self.param('Values'):
            mask = data == v.maskValue
            c = np.array(fn.colorTuple(v.value())) / 255.
            colors[mask] = c
        #scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1)
        #cmap = self.value()
        #colors = cmap.map(scaled, mode='float')
        
        #mask = np.isnan(data) | np.isinf(data)
        #nanColor = self['NaN']
        #nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.)
        #colors[mask] = nanColor
        
        return colors 
开发者ID:SrikanthVelpuri,项目名称:tf-pose,代码行数:22,代码来源:ColorMapWidget.py

示例13: testDtypeExecution

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def testDtypeExecution(self):
        a = ones((10, 20), dtype='f4', chunk_size=5)

        c = truediv(a, 2, dtype='f8')

        res = self.executor.execute_tensor(c, concat=True)[0]
        self.assertEqual(res.dtype, np.float64)

        c = truediv(a, 0, dtype='f8')
        res = self.executor.execute_tensor(c, concat=True)[0]
        self.assertTrue(np.isinf(res[0, 0]))

        with self.assertRaises(FloatingPointError):
            with np.errstate(divide='raise'):
                c = truediv(a, 0, dtype='f8')
                _ = self.executor.execute_tensor(c, concat=True)[0]  # noqa: F841 
开发者ID:mars-project,项目名称:mars,代码行数:18,代码来源:test_arithmetic_execution.py

示例14: scale_neg_1_to_1_with_zero_mean_log_abs_max

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def scale_neg_1_to_1_with_zero_mean_log_abs_max(v):
	'''
	!!! not working
	'''
	df = pd.DataFrame({'v':v,
	                   'sign': (v > 0) * 2 - 1})
	df['lg'] = np.log(np.abs(v)) / np.log(1.96)
	df['exclude'] = (np.isinf(df.lg) | np.isneginf(df.lg))
	for mask in [(df['sign'] == -1) & (df['exclude'] == False),
	             (df['sign'] == 1) & (df['exclude'] == False)]:
		df[mask]['lg'] = df[mask]['lg'].max() - df[mask]['lg']
	df['lg'] *= df['sign']
	df['lg'] = df['lg'].fillna(0)
	print(df[df['exclude']]['lg'].values)
	#to_rescale = convention_df['lg'].reindex(v.index)
	df['to_out'] =  scale_neg_1_to_1_with_zero_mean_abs_max(df['lg'])
	print('right')
	print(df.sort_values(by='lg').iloc[:5])
	print(df.sort_values(by='lg').iloc[-5:])
	print('to_out')
	print(df.sort_values(by='to_out').iloc[:5])
	print(df.sort_values(by='to_out').iloc[-5:])
	print(len(df), len(df.dropna()))
	return df['to_out'] 
开发者ID:JasonKessler,项目名称:scattertext,代码行数:26,代码来源:Scalers.py

示例15: calc_inv_vol_weights

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isinf [as 别名]
def calc_inv_vol_weights(returns):
    """
    Calculates weights proportional to inverse volatility of each column.

    Returns weights that are inversely proportional to the column's
    volatility resulting in a set of portfolio weights where each position
    has the same level of volatility.

    Note, that assets with returns all equal to NaN or 0 are excluded from
    the portfolio (their weight is set to NaN).

    Returns:
        Series {col_name: weight}
    """
    # calc vols
    vol = np.divide(1., np.std(returns, ddof=1))
    vol[np.isinf(vol)] = np.NaN
    volsum = vol.sum()
    return np.divide(vol, volsum) 
开发者ID:pmorissette,项目名称:ffn,代码行数:21,代码来源:core.py


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