本文整理匯總了Python中numpy.testing.assert_raises方法的典型用法代碼示例。如果您正苦於以下問題:Python testing.assert_raises方法的具體用法?Python testing.assert_raises怎麽用?Python testing.assert_raises使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy.testing
的用法示例。
在下文中一共展示了testing.assert_raises方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_predict
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_predict():
dates = pd.date_range(start='1980-01-01', end='1981-01-01', freq='AS')
endog = pd.Series([1,2], index=dates)
mod = MLEModel(endog, **kwargs)
res = mod.filter([])
# Test that predict with start=None, end=None does prediction with full
# dataset
predict = res.predict()
assert_equal(predict.shape, (mod.nobs,))
assert_allclose(res.get_prediction().predicted_mean, predict)
# Test a string value to the dynamic option
assert_allclose(res.predict(dynamic='1981-01-01'), res.predict())
# Test an invalid date string value to the dynamic option
# assert_raises(ValueError, res.predict, dynamic='1982-01-01')
# Test for passing a string to predict when dates are not set
mod = MLEModel([1,2], **kwargs)
res = mod.filter([])
assert_raises(KeyError, res.predict, dynamic='string')
示例2: test_erlang_runtimewarning
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_erlang_runtimewarning():
# erlang should generate a RuntimeWarning if a non-integer
# shape parameter is used.
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
# The non-integer shape parameter 1.3 should trigger a RuntimeWarning
npt.assert_raises(RuntimeWarning,
stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)
# Calling the fit method with `f0` set to an integer should
# *not* trigger a RuntimeWarning. It should return the same
# values as gamma.fit(...).
data = [0.5, 1.0, 2.0, 4.0]
result_erlang = stats.erlang.fit(data, f0=1)
result_gamma = stats.gamma.fit(data, f0=1)
npt.assert_allclose(result_erlang, result_gamma, rtol=1e-3)
示例3: test_valid_origins
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_valid_origins():
"""Regression test for #1311."""
func = lambda x: np.mean(x)
data = np.array([1,2,3,4,5], dtype=np.float64)
assert_raises(ValueError, sndi.generic_filter, data, func, size=3,
origin=2)
func2 = lambda x, y: np.mean(x + y)
assert_raises(ValueError, sndi.generic_filter1d, data, func,
filter_size=3, origin=2)
assert_raises(ValueError, sndi.percentile_filter, data, 0.2, size=3,
origin=2)
for filter in [sndi.uniform_filter, sndi.minimum_filter,
sndi.maximum_filter, sndi.maximum_filter1d,
sndi.median_filter, sndi.minimum_filter1d]:
# This should work, since for size == 3, the valid range for origin is
# -1 to 1.
list(filter(data, 3, origin=-1))
list(filter(data, 3, origin=1))
# Just check this raises an error instead of silently accepting or
# segfaulting.
assert_raises(ValueError, filter, data, 3, origin=2)
示例4: test_pow_freq_bands
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_pow_freq_bands():
expected = np.array([0, 0.005, 0, 0, 0.00125]) / 0.00625
assert_almost_equal(compute_pow_freq_bands(sfreq, data_sin,
psd_method='fft'), expected)
# Ratios of power in bands:
# For data_sin, only the usual theta (4Hz - 8Hz) and low gamma
# (30Hz - 70Hz) bands contain non-zero power.
fb = np.array([[4., 8.], [30., 70.]])
expected_pow = np.array([0.005, 0.00125]) / 0.00625
expected_ratios = np.array([4., 0.25])
assert_almost_equal(compute_pow_freq_bands(sfreq, data_sin, freq_bands=fb,
ratios='all', psd_method='fft'),
np.r_[expected_pow, expected_ratios])
assert_almost_equal(compute_pow_freq_bands(sfreq, data_sin, freq_bands=fb,
ratios='only',
psd_method='fft'),
expected_ratios)
with assert_raises(ValueError):
# Invalid `ratios` parameter
compute_pow_freq_bands(sfreq, data_sin, ratios=['alpha', 'beta'])
示例5: test_user_defined_feature_function
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_user_defined_feature_function():
# User-defined feature function
@nb.jit()
def top_feature(arr, gamma=3.14):
return np.sum(np.power(gamma * arr, 3) - np.power(arr / gamma, 2),
axis=-1)
# Valid feature extraction
selected_funcs = ['mean', ('top_feature', top_feature)]
feat = extract_features(data, sfreq, selected_funcs)
assert_equal(feat.shape, (n_epochs, 2 * n_channels))
# Changing optional parameter ``gamma`` of ``top_feature``
feat2 = extract_features(data, sfreq, selected_funcs,
funcs_params={'top_feature__gamma': 1.41})
assert_equal(feat2.shape, (n_epochs, 2 * n_channels))
# Invalid feature extractions
with assert_raises(ValueError):
# Alias is already used
extract_features(data, sfreq, ['variance', ('mean', top_feature)])
# Tuple is not of length 2
extract_features(data, sfreq, ['variance', ('top_feature', top_feature,
data[:, ::2])])
# Invalid type
extract_features(data, sfreq, ['mean', top_feature])
示例6: test_dataset_evaluators
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_dataset_evaluators():
X = theano.tensor.matrix('X')
brick = TestBrick(name='test_brick')
Y = brick.apply(X)
graph = ComputationGraph([Y])
monitor_variables = [v for v in graph.auxiliary_variables]
validator = DatasetEvaluator(monitor_variables)
data = [numpy.arange(1, 5, dtype=theano.config.floatX).reshape(2, 2),
numpy.arange(10, 16, dtype=theano.config.floatX).reshape(3, 2)]
data_stream = IterableDataset(dict(X=data)).get_example_stream()
values = validator.evaluate(data_stream)
assert values['test_brick_apply_V_squared'] == 4
numpy.testing.assert_allclose(
values['test_brick_apply_mean_row_mean'], numpy.vstack(data).mean())
per_batch_mean = numpy.mean([batch.mean() for batch in data])
numpy.testing.assert_allclose(
values['test_brick_apply_mean_batch_element'], per_batch_mean)
with assert_raises(Exception) as ar:
data_stream = IterableDataset(dict(X2=data)).get_example_stream()
validator.evaluate(data_stream)
assert "Not all data sources" in ar.exception.args[0]
示例7: test_raise_exception_spatial
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_raise_exception_spatial():
"""Test that SpatialBatchNormalization raises an expected exception."""
# Work around a stupid bug in nose2 that unpacks the tuple into
# separate arguments.
sbn1 = SpatialBatchNormalization((5,))
yield assert_raises, (ValueError, sbn1.allocate)
sbn2 = SpatialBatchNormalization(3)
yield assert_raises, (ValueError, sbn2.allocate)
def do_not_fail(*input_dim):
try:
sbn = SpatialBatchNormalization(input_dim)
sbn.allocate()
except ValueError:
assert False
# Work around a stupid bug in nose2 by passing as *args.
yield do_not_fail, 5, 4, 3
yield do_not_fail, 7, 6
yield do_not_fail, 3, 9, 2, 3
示例8: test_autoconversion
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_autoconversion(self):
# Tests autoconversion
adtype = [('A', int), ('B', bool), ('C', float)]
a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
bdtype = [('A', int), ('B', float), ('C', float)]
b = ma.array([(4, 5, 6)], dtype=bdtype)
control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
dtype=bdtype)
test = stack_arrays((a, b), autoconvert=True)
assert_equal(test, control)
assert_equal(test.mask, control.mask)
with assert_raises(TypeError):
stack_arrays((a, b), autoconvert=False)
示例9: test_duplicate_keys
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_duplicate_keys(self):
a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b)
示例10: test_no_postfix
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_no_postfix(self):
assert_raises(ValueError, join_by, 'a', self.a, self.b,
r1postfix='', r2postfix='')
示例11: test_opt_out
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_opt_out(self):
class OptOut(object):
"""Object that opts out of __array_ufunc__."""
__array_ufunc__ = None
def __add__(self, other):
return self
def __radd__(self, other):
return self
array_like = ArrayLike(1)
opt_out = OptOut()
# supported operations
assert_(array_like + opt_out is opt_out)
assert_(opt_out + array_like is opt_out)
# not supported
with assert_raises(TypeError):
# don't use the Python default, array_like = array_like + opt_out
array_like += opt_out
with assert_raises(TypeError):
array_like - opt_out
with assert_raises(TypeError):
opt_out - array_like
示例12: test_object
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_object(self):
x = ArrayLike(0)
obj = object()
with assert_raises(TypeError):
x + obj
with assert_raises(TypeError):
obj + x
with assert_raises(TypeError):
x += obj
示例13: check_function
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def check_function(self, t):
if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
err = 1e-5
else:
err = 0.0
assert_(abs(t(234) - 234.0) <= err)
assert_(abs(t(234.6) - 234.6) <= err)
assert_(abs(t(long(234)) - 234.0) <= err)
assert_(abs(t('234') - 234) <= err)
assert_(abs(t('234.6') - 234.6) <= err)
assert_(abs(t(-234) + 234) <= err)
assert_(abs(t([234]) - 234) <= err)
assert_(abs(t((234,)) - 234.) <= err)
assert_(abs(t(array(234)) - 234.) <= err)
assert_(abs(t(array([234])) - 234.) <= err)
assert_(abs(t(array([[234]])) - 234.) <= err)
assert_(abs(t(array([234], 'b')) + 22) <= err)
assert_(abs(t(array([234], 'h')) - 234.) <= err)
assert_(abs(t(array([234], 'i')) - 234.) <= err)
assert_(abs(t(array([234], 'l')) - 234.) <= err)
assert_(abs(t(array([234], 'B')) - 234.) <= err)
assert_(abs(t(array([234], 'f')) - 234.) <= err)
assert_(abs(t(array([234], 'd')) - 234.) <= err)
if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
assert_(t(1e200) == t(1e300)) # inf
#assert_raises(ValueError, t, array([234], 'S1'))
assert_raises(ValueError, t, 'abc')
assert_raises(IndexError, t, [])
assert_raises(IndexError, t, ())
assert_raises(Exception, t, t)
assert_raises(Exception, t, {})
try:
r = t(10 ** 400)
assert_(repr(r) in ['inf', 'Infinity'], repr(r))
except OverflowError:
pass
示例14: check_function
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def check_function(self, t):
assert_(t(123) == 123, repr(t(123)))
assert_(t(123.6) == 123)
assert_(t(long(123)) == 123)
assert_(t('123') == 123)
assert_(t(-123) == -123)
assert_(t([123]) == 123)
assert_(t((123,)) == 123)
assert_(t(array(123)) == 123)
assert_(t(array([123])) == 123)
assert_(t(array([[123]])) == 123)
assert_(t(array([123], 'b')) == 123)
assert_(t(array([123], 'h')) == 123)
assert_(t(array([123], 'i')) == 123)
assert_(t(array([123], 'l')) == 123)
assert_(t(array([123], 'B')) == 123)
assert_(t(array([123], 'f')) == 123)
assert_(t(array([123], 'd')) == 123)
#assert_raises(ValueError, t, array([123],'S3'))
assert_raises(ValueError, t, 'abc')
assert_raises(IndexError, t, [])
assert_raises(IndexError, t, ())
assert_raises(Exception, t, t)
assert_raises(Exception, t, {})
if t.__doc__.split()[0] in ['t8', 's8']:
assert_raises(OverflowError, t, 100000000000000000000000)
assert_raises(OverflowError, t, 10000000011111111111111.23)
示例15: test_invalid
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_raises [as 別名]
def test_invalid(self):
with np.errstate(all='raise', under='ignore'):
a = -np.arange(3)
# This should work
with np.errstate(invalid='ignore'):
np.sqrt(a)
# While this should fail!
with assert_raises(FloatingPointError):
np.sqrt(a)