本文整理匯總了Python中numpy.NAN屬性的典型用法代碼示例。如果您正苦於以下問題:Python numpy.NAN屬性的具體用法?Python numpy.NAN怎麽用?Python numpy.NAN使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類numpy
的用法示例。
在下文中一共展示了numpy.NAN屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: mean
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def mean(self, n, p):
"""
Mean of the Multinomial distribution
Parameters
----------
%(_doc_default_callparams)s
Returns
-------
mean : float
The mean of the distribution
"""
n, p, npcond = self._process_parameters(n, p)
result = n[..., np.newaxis]*p
return self._checkresult(result, npcond, np.NAN)
示例2: test_constants
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def test_constants():
assert chainerx.Inf is numpy.Inf
assert chainerx.Infinity is numpy.Infinity
assert chainerx.NAN is numpy.NAN
assert chainerx.NINF is numpy.NINF
assert chainerx.NZERO is numpy.NZERO
assert chainerx.NaN is numpy.NaN
assert chainerx.PINF is numpy.PINF
assert chainerx.PZERO is numpy.PZERO
assert chainerx.e is numpy.e
assert chainerx.euler_gamma is numpy.euler_gamma
assert chainerx.inf is numpy.inf
assert chainerx.infty is numpy.infty
assert chainerx.nan is numpy.nan
assert chainerx.newaxis is numpy.newaxis
assert chainerx.pi is numpy.pi
示例3: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def __init__(self, x0, P0, Q, R, cor, f, h):
self.Q = Q
self.R = R
self.cor = cor
self.fa = lambda col: f(col[0], col[2])
self.ha = lambda col: h(col[0], col[1])
Pxx = P0
Pxv = 0.
self.xa = np.array( ((x0,), (0.,), (0.,), (0.,)) )
self.Pa = np.array( ((Pxx, Pxv , 0. , 0. ),
(Pxv, self.R, 0. , 0. ),
(0. , 0. , self.Q , self.cor),
(0. , 0. , self.cor, self.R )) )
self.lastobservation = np.NAN
self.predictedobservation = np.NAN
self.innov = np.NAN
self.innovcov = np.NAN
self.gain = np.NAN
self.loglikelihood = 0.0
示例4: get_site_index
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def get_site_index(material, defect):
"""
Given two trajectories with equal atom positions and one atom difference,
determines the site index of the defect site.
:param material:
:param defect:
:return: site index integer
"""
matlist = material.get_positions()
deflist = defect.get_positions()
site_detected = []
for pos in matlist:
boollist = [np.allclose(pos, defpos, rtol=1e-03) for defpos in deflist]
site_detected.append(any(boollist))
site_idx = [idx for idx, _ in enumerate(site_detected) if not _]
if len(site_idx) == 0:
site_idx = [np.NAN]
return site_idx[0]
示例5: get_DFT_site_stability
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def get_DFT_site_stability(self, site):
"""
Computes site stability based on material,
defect and reference dict.
:param site: SiteFeaturizer site.
:return: Site stability in eV.
"""
e_mat = site['material'].total_energy
atom = site['material'].atoms[site['site_index']].symbol
e_atom = self.reference_dict[atom]
e_def = site['defect'].total_energy
try:
e_site = e_mat - e_def - e_atom
except:
# print('Check; site may not be converged: \n')
# print(site)
# print('\n')
e_site = np.NAN
return e_site
示例6: _format_value_error
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def _format_value_error(self, v, e, pm=" +/- "):
"""
Returns a string v +/- e with the right number of sig figs.
"""
# If we have weird stuff
if not _s.fun.is_a_number(v) or not _s.fun.is_a_number(e) \
or v in [_n.inf, _n.nan, _n.NAN] or e in [_n.inf, _n.nan, _n.NAN]:
return str(v)+pm+str(e)
# Normal values.
try:
sig_figs = -int(_n.floor(_n.log10(abs(e))))+1
return str(_n.round(v, sig_figs)) + pm + str(_n.round(e, sig_figs))
except:
return str(v)+pm+str(e)
示例7: mahalanobis_distances
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def mahalanobis_distances(df, axis=0):
'''
Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns
'''
df = df.transpose() if axis == 1 else df
means = df.mean()
try:
inv_cov = np.linalg.inv(df.cov())
except LinAlgError:
return pd.Series([np.NAN] * len(df.index), df.index,
name='Mahalanobis')
dists = []
for i, sample in df.iterrows():
dists.append(mahalanobis(sample, means, inv_cov))
return pd.Series(dists, df.index, name='Mahalanobis')
示例8: bounce
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def bounce(dataframe: DataFrame, level):
"""
:param dataframe:
:param level:
:return:
1 if it bounces up
0 if no bounce
-1 if it bounces below
"""
from scipy.ndimage.interpolation import shift
open = dataframe['open']
close = dataframe['close']
touch = shift(touches(dataframe, level), 1, cval=np.NAN)
return np.vectorize(_bounce)(open, close, level, touch)
示例9: _fit1_slope
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def _fit1_slope(y: np.ndarray, x: np.ndarray) -> float:
"""Simple function that fit a linear regression model without intercept
"""
if not np.any(x):
m = np.NAN # It is definetelly not at steady state!!!
elif not np.any(y):
m = 0
else:
result, rnorm = scipy.optimize.nnls(x[:, None], y) # Fastest but costrains result >= 0
m = result[0]
# Second fastest: m, _ = scipy.optimize.leastsq(lambda m: x*m - y, x0=(0,))
# Third fastest: m = scipy.optimize.minimize_scalar(lambda m: np.sum((x*m - y)**2 )).x
# Before I was doinf fastest: scipy.optimize.minimize_scalar(lambda m: np.sum((y - m * x)**2), bounds=(0, 3), method="bounded").x
# Optionally one could clip m if high value make no sense
# m = np.clip(m,0,3)
return m
示例10: _fit1_slope_weighted
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def _fit1_slope_weighted(y: np.ndarray, x: np.ndarray, w: np.ndarray, limit_gamma: bool=False, bounds: Tuple[float, float]=(0, 20)) -> float:
"""Simple function that fit a weighted linear regression model without intercept
"""
if not np.any(x):
m = np.NAN # It is definetelly not at steady state!!!
elif not np.any(y):
m = 0
else:
if limit_gamma:
if np.median(y) > np.median(x):
high_x = x > np.percentile(x, 90)
up_gamma = np.percentile(y[high_x], 10) / np.median(x[high_x])
up_gamma = np.maximum(1.5, up_gamma)
else:
up_gamma = 1.5 # Just a bit more than 1
m = scipy.optimize.minimize_scalar(lambda m: np.sum(w * (x * m - y)**2), bounds=(1e-8, up_gamma), method="bounded").x
else:
m = scipy.optimize.minimize_scalar(lambda m: np.sum(w * (x * m - y)**2), bounds=bounds, method="bounded").x
return m
示例11: _fit1_slope_offset
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def _fit1_slope_offset(y: np.ndarray, x: np.ndarray, fixperc_q: bool=False) -> Tuple[float, float]:
"""Simple function that fit a linear regression model with intercept
"""
if not np.any(x):
m = (np.NAN, 0) # It is definetelly not at steady state!!!
elif not np.any(y):
m = (0, 0)
else:
# result, rnorm = scipy.optimize.nnls(x[:, None], y) # Fastest but costrains result >= 0
# m = result[0]
if fixperc_q:
m1 = np.percentile(y[x <= np.percentile(x, 1)], 50)
m0 = scipy.optimize.minimize_scalar(lambda m: np.sum((x * m - y + m1)**2), bounds=(0, 20), method="bounded").x
m = (m0, m1)
else:
m, _ = scipy.optimize.leastsq(lambda m: -y + x * m[0] + m[1], x0=(0, 0))
# Third fastest: m = scipy.optimize.minimize_scalar(lambda m: np.sum((x*m - y)**2 )).x
# Before I was doinf fastest: scipy.optimize.minimize_scalar(lambda m: np.sum((y - m * x)**2), bounds=(0, 3), method="bounded").x
# Optionally one could clip m if high value make no sense
# m = np.clip(m,0,3)
return m[0], m[1]
示例12: remask
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def remask(self):
"""Reset the mask based on the seeded connected component.
"""
body = self.to_body()
if not body.is_seed_in_mask():
return False
new_mask_bin, bounds = body.get_seeded_component(CONFIG.postprocessing.closing_shape)
new_mask_bin = new_mask_bin.astype(np.bool)
mask_block = self.mask[list(map(slice, bounds[0], bounds[1]))].copy()
# Clip any values not in the seeded connected component so that they
# cannot not generate moves when rechecking.
mask_block[~new_mask_bin] = np.clip(mask_block[~new_mask_bin], None, 0.9 * CONFIG.model.t_move)
self.mask[:] = np.NAN
self.mask[list(map(slice, bounds[0], bounds[1]))] = mask_block
return True
示例13: logpmf
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def logpmf(self, x, n, p):
"""
Log of the Multinomial probability mass function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
Each quantile must be a symmetric positive definite matrix.
%(_doc_default_callparams)s
Returns
-------
logpmf : ndarray or scalar
Log of the probability mass function evaluated at `x`
Notes
-----
%(_doc_callparams_note)s
"""
n, p, npcond = self._process_parameters(n, p)
x, xcond = self._process_quantiles(x, n, p)
result = self._logpmf(x, n, p)
# replace values for which x was out of the domain; broadcast
# xcond to the right shape
xcond_ = xcond | np.zeros(npcond.shape, dtype=np.bool_)
result = self._checkresult(result, xcond_, np.NINF)
# replace values bad for n or p; broadcast npcond to the right shape
npcond_ = npcond | np.zeros(xcond.shape, dtype=np.bool_)
return self._checkresult(result, npcond_, np.NAN)
示例14: sign
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def sign(x):
if x is None:
return None
if np.isnan(x):
return np.NAN
if x==0:
return 0.0
if x<0:
return -1.0
if x>0:
return 1.0
示例15: testFlatIndexSeriesPercentageDifferenceJackknifeMelted
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import NAN [as 別名]
def testFlatIndexSeriesPercentageDifferenceJackknifeMelted(self):
# Output is screenshot/xXqjxgZb6eH
flat_idx = pd.Series(
list(range(3)), index=pd.Index(list("abc"), name="foo"))
metric = [
metrics.Sum("X"),
metrics.Metric("Constant", fn=lambda df: flat_idx)
]
comparison = comparisons.PercentageDifference("U", 1)
se_method = standard_errors.Jackknife("Y")
output = core.Analyze(self.data).relative_to(
comparison).with_standard_errors(se_method).calculate(metric).run(1)
sum_x = core.Analyze(self.data).relative_to(
comparison).with_standard_errors(se_method).calculate(metric[0]).run(1)
sum_x["foo"] = ""
sum_x.set_index("foo", append=True, inplace=True)
sum_x = sum_x.reorder_levels(["Metric", "foo", "U"])
constant = pd.DataFrame({
"Metric": ["Constant"] * 6,
"foo": list("abcabc"),
"U": [2] * 3 + [3] * 3,
"Percentage Difference": [np.NAN, 0, 0] * 2,
"Percentage Difference Jackknife SE": [np.NAN, 0, 0] * 2,
})
constant.set_index(["Metric", "foo", "U"], inplace=True)
correct = pd.concat([sum_x, constant])
pd.util.testing.assert_frame_equal(output, correct)