本文整理匯總了Python中numpy.testing.assert_almost_equal方法的典型用法代碼示例。如果您正苦於以下問題:Python testing.assert_almost_equal方法的具體用法?Python testing.assert_almost_equal怎麽用?Python testing.assert_almost_equal使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy.testing
的用法示例。
在下文中一共展示了testing.assert_almost_equal方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_dft_2d
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_dft_2d(self):
"""Test the discrete Fourier transform on 2D data"""
N = 16
da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
coords={'x':range(N),'y':range(N)}
)
ft = xrft.dft(da, shift=False)
npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))
ft = xrft.dft(da, shift=False, window=True, detrend='constant')
dim = da.dims
window = np.hanning(N) * np.hanning(N)[:, np.newaxis]
da_prime = (da - da.mean(dim=dim)).values
npt.assert_almost_equal(ft.values, np.fft.fftn(da_prime*window))
da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
coords={'x':range(N,0,-1),'y':range(N,0,-1)}
)
assert (xrft.power_spectrum(da, shift=False,
density=True) >= 0.).all()
示例2: test_dft_4d
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_dft_4d(self):
"""Test the discrete Fourier transform on 2D data"""
N = 16
da = xr.DataArray(np.random.rand(N,N,N,N),
dims=['time','z','y','x'],
coords={'time':range(N),'z':range(N),
'y':range(N),'x':range(N)}
)
with pytest.raises(ValueError):
xrft.dft(da.chunk({'time':8}), dim=['y','x'], detrend='linear')
ft = xrft.dft(da, shift=False)
npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))
da_prime = xrft.detrendn(da[:,0].values, [0,1,2]) # cubic detrend over time, y, and x
npt.assert_almost_equal(xrft.dft(da[:,0].drop('z'),
dim=['time','y','x'],
shift=False, detrend='linear'
).values,
np.fft.fftn(da_prime))
示例3: test_dft_real_2d
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_dft_real_2d(self):
"""
Test the real discrete Fourier transform function on one-dimensional
data. Non-trivial because we need to keep only some of the negative
frequencies.
"""
Nx, Ny = 16, 32
da = xr.DataArray(np.random.rand(Nx, Ny), dims=['x', 'y'],
coords={'x': range(Nx), 'y': range(Ny)})
dx = float(da.x[1] - da.x[0])
dy = float(da.y[1] - da.y[0])
daft = xrft.dft(da, real='x')
npt.assert_almost_equal(daft.values,
np.fft.rfftn(da.transpose('y','x')).transpose())
npt.assert_almost_equal(daft.values,
xrft.dft(da, dim=['y'], real='x'))
actual_freq_x = daft.coords['freq_x'].values
expected_freq_x = np.fft.rfftfreq(Nx, dx)
npt.assert_almost_equal(actual_freq_x, expected_freq_x)
actual_freq_y = daft.coords['freq_y'].values
expected_freq_y = np.fft.fftfreq(Ny, dy)
npt.assert_almost_equal(actual_freq_y, expected_freq_y)
示例4: test_cross_phase_2d
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_cross_phase_2d(self, dask):
Ny, Nx = (32, 16)
x = np.linspace(0, 1, num=Nx, endpoint=False)
y = np.ones(Ny)
f = 6
phase_offset = np.pi/2
signal1 = np.cos(2*np.pi*f*x) # frequency = 1/(2*pi)
signal2 = np.cos(2*np.pi*f*x - phase_offset)
da1 = xr.DataArray(data=signal1*y[:,np.newaxis], name='a',
dims=['y','x'], coords={'y':y, 'x':x})
da2 = xr.DataArray(data=signal2*y[:,np.newaxis], name='b',
dims=['y','x'], coords={'y':y, 'x':x})
with pytest.raises(ValueError):
xrft.cross_phase(da1, da2, dim=['y','x'])
if dask:
da1 = da1.chunk({'x': 16})
da2 = da2.chunk({'x': 16})
cp = xrft.cross_phase(da1, da2, dim=['x'])
actual_phase_offset = cp.sel(freq_x=f).values
npt.assert_almost_equal(actual_phase_offset, phase_offset)
示例5: test_broadcast
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_broadcast():
"""Test for broadcasting in onnx operators."""
input1 = np.random.rand(1, 3, 4, 5).astype("float32")
input2 = np.random.rand(1, 5).astype("float32")
inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]
outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]
nodes = [helper.make_node("Add", ["input1", "input2"], ["output"])]
graph = helper.make_graph(nodes,
"bcast_test",
inputs,
outputs)
bcast_model = helper.make_model(graph)
bkd_rep = mxnet_backend.prepare(bcast_model)
numpy_op = input1 + input2
output = bkd_rep.run([input1, input2])
npt.assert_almost_equal(output[0], numpy_op)
示例6: test_greater
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_greater():
"""Test for logical greater in onnx operators."""
input1 = np.random.rand(1, 3, 4, 5).astype("float32")
input2 = np.random.rand(1, 5).astype("float32")
inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]
outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]
nodes = [helper.make_node("Greater", ["input1", "input2"], ["output"])]
graph = helper.make_graph(nodes,
"greater_test",
inputs,
outputs)
greater_model = helper.make_model(graph)
bkd_rep = mxnet_backend.prepare(greater_model)
numpy_op = np.greater(input1, input2).astype(np.float32)
output = bkd_rep.run([input1, input2])
npt.assert_almost_equal(output[0], numpy_op)
示例7: test_lesser
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_lesser():
"""Test for logical greater in onnx operators."""
input1 = np.random.rand(1, 3, 4, 5).astype("float32")
input2 = np.random.rand(1, 5).astype("float32")
inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]
outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]
nodes = [helper.make_node("Less", ["input1", "input2"], ["output"])]
graph = helper.make_graph(nodes,
"lesser_test",
inputs,
outputs)
greater_model = helper.make_model(graph)
bkd_rep = mxnet_backend.prepare(greater_model)
numpy_op = np.less(input1, input2).astype(np.float32)
output = bkd_rep.run([input1, input2])
npt.assert_almost_equal(output[0], numpy_op)
示例8: test_equal
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_equal():
"""Test for logical greater in onnx operators."""
input1 = np.random.rand(1, 3, 4, 5).astype("float32")
input2 = np.random.rand(1, 5).astype("float32")
inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]
outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]
nodes = [helper.make_node("Equal", ["input1", "input2"], ["output"])]
graph = helper.make_graph(nodes,
"equal_test",
inputs,
outputs)
greater_model = helper.make_model(graph)
bkd_rep = mxnet_backend.prepare(greater_model)
numpy_op = np.equal(input1, input2).astype(np.float32)
output = bkd_rep.run([input1, input2])
npt.assert_almost_equal(output[0], numpy_op)
示例9: test_square
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_square():
input1 = np.random.randint(1, 10, (2, 3)).astype("float32")
ipsym = mx.sym.Variable("input1")
square = mx.sym.square(data=ipsym)
model = mx.mod.Module(symbol=square, data_names=['input1'], label_names=None)
model.bind(for_training=False, data_shapes=[('input1', np.shape(input1))], label_shapes=None)
model.init_params()
args, auxs = model.get_params()
params = {}
params.update(args)
params.update(auxs)
converted_model = onnx_mxnet.export_model(square, params, [np.shape(input1)], np.float32, "square.onnx")
sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model)
result = forward_pass(sym, arg_params, aux_params, ['input1'], input1)
numpy_op = np.square(input1)
npt.assert_almost_equal(result, numpy_op)
示例10: testBoundingBoxParser
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def testBoundingBoxParser(self):
bounding_boxes = np.array([[0.0, 0.5, 0.3], [0.0, 0.1, 0.6],
[1.0, 0.6, 0.8], [1.0, 0.6, 0.7]]).transpose()
features = {
'ymin': self._FloatFeature(bounding_boxes[:, 0]),
'xmin': self._FloatFeature(bounding_boxes[:, 1]),
'ymax': self._FloatFeature(bounding_boxes[:, 2]),
'xmax': self._FloatFeature(bounding_boxes[:, 3])
}
example = tf.train.Example(features=tf.train.Features(feature=features))
parser = tf_example_parser.BoundingBoxParser('xmin', 'ymin', 'xmax', 'ymax')
result = parser.parse(example)
self.assertIsNotNone(result)
np_testing.assert_almost_equal(result, bounding_boxes)
parser = tf_example_parser.BoundingBoxParser('xmin', 'ymin', 'xmax',
'another_ymax')
result = parser.parse(example)
self.assertIsNone(result)
示例11: test_ImageStimulus_scale
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_ImageStimulus_scale():
# Create a horizontal bar:
fname = 'test.png'
shape = (5, 5)
ndarray = np.zeros(shape, dtype=np.uint8)
ndarray[2, :] = 255
imsave(fname, ndarray)
# Scale phosphene:
stim = ImageStimulus(fname)
npt.assert_almost_equal(stim.data, stim.scale(1).data)
npt.assert_almost_equal(stim.scale(0.1)[12], 1)
npt.assert_almost_equal(stim.scale(0.1)[:12], 0)
npt.assert_almost_equal(stim.scale(0.1)[13:], 0)
with pytest.raises(ValueError):
stim.scale(0)
os.remove(fname)
示例12: test_ImageStimulus_encode
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_ImageStimulus_encode():
stim = ImageStimulus(np.random.rand(4, 5))
# Amplitude encoding in default range:
enc = stim.encode()
npt.assert_almost_equal(enc.time[-1], 500)
npt.assert_almost_equal(enc.data.max(axis=1).min(), 0)
npt.assert_almost_equal(enc.data.max(axis=1).max(), 50)
# Amplitude encoding in custom range:
enc = stim.encode(amp_range=(2, 43))
npt.assert_almost_equal(enc.time[-1], 500)
npt.assert_almost_equal(enc.data.max(axis=1).min(), 2)
npt.assert_almost_equal(enc.data.max(axis=1).max(), 43)
with pytest.raises(TypeError):
stim.encode(pulse={'invalid': 1})
with pytest.raises(ValueError):
stim.encode(pulse=LogoUCSB())
示例13: test_conv
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_conv(mode, method):
reload(convolution)
# time vector for stimulus (long)
stim_dur = 0.5 # seconds
tsample = 0.001 / 1000
t = np.arange(0, stim_dur, tsample)
# stimulus (10 Hz anondic and cathodic pulse train)
stim = np.zeros_like(t)
stim[::1000] = 1
stim[100::1000] = -1
# kernel
_, gg = gamma(1, 0.005, tsample)
# make sure conv returns the same result as np.convolve for all modes:
npconv = np.convolve(stim, gg, mode=mode)
conv = convolution.conv(stim, gg, mode=mode, method=method)
npt.assert_equal(conv.shape, npconv.shape)
npt.assert_almost_equal(conv, npconv)
with pytest.raises(ValueError):
convolution.conv(gg, stim, mode="invalid")
with pytest.raises(ValueError):
convolution.conv(gg, stim, method="invalid")
示例14: test_gamma
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_gamma():
tsample = 0.005 / 1000
with pytest.raises(ValueError):
t, g = gamma(0, 0.1, tsample)
with pytest.raises(ValueError):
t, g = gamma(2, -0.1, tsample)
with pytest.raises(ValueError):
t, g = gamma(2, 0.1, -tsample)
for tau in [0.001, 0.01, 0.1]:
for n in [1, 2, 5]:
t, g = gamma(n, tau, tsample)
npt.assert_equal(np.arange(0, t[-1] + tsample / 2.0, tsample), t)
if n > 1:
npt.assert_equal(g[0], 0.0)
# Make sure area under the curve is normalized
npt.assert_almost_equal(np.trapz(np.abs(g), dx=tsample), 1.0,
decimal=2)
# Make sure peak sits correctly
npt.assert_almost_equal(g.argmax() * tsample, tau * (n - 1))
示例15: test_Grid2D
# 需要導入模塊: from numpy import testing [as 別名]
# 或者: from numpy.testing import assert_almost_equal [as 別名]
def test_Grid2D(x_range, y_range):
grid = Grid2D(x_range, y_range, step=1, grid_type='rectangular')
npt.assert_equal(grid.x_range, x_range)
npt.assert_equal(grid.y_range, y_range)
npt.assert_equal(grid.step, 1)
npt.assert_equal(grid.type, 'rectangular')
# Grid is created with indexing='xy', so check coordinates:
npt.assert_equal(grid.x.shape,
(np.abs(np.diff(y_range)) + 1,
np.abs(np.diff(x_range)) + 1))
npt.assert_equal(grid.x.shape, grid.y.shape)
npt.assert_equal(grid.x.shape, grid.shape)
npt.assert_almost_equal(grid.x[0, 0], x_range[0])
npt.assert_almost_equal(grid.x[0, -1], x_range[1])
npt.assert_almost_equal(grid.x[-1, 0], x_range[0])
npt.assert_almost_equal(grid.x[-1, -1], x_range[1])
npt.assert_almost_equal(grid.y[0, 0], y_range[0])
npt.assert_almost_equal(grid.y[0, -1], y_range[0])
npt.assert_almost_equal(grid.y[-1, 0], y_range[1])
npt.assert_almost_equal(grid.y[-1, -1], y_range[1])