本文整理汇总了Python中hypothesis.extra.numpy.arrays方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.arrays方法的具体用法?Python numpy.arrays怎么用?Python numpy.arrays使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hypothesis.extra.numpy
的用法示例。
在下文中一共展示了numpy.arrays方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _strategy_2d_array
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def _strategy_2d_array(dtype, minval=0, maxval=None, **kwargs):
if 'min_side' in kwargs:
min_side = kwargs.pop('min_side')
else:
min_side = 1
if 'max_side' in kwargs:
max_side = kwargs.pop('max_side')
else:
max_side = None
if dtype is np.int:
elems = st.integers(minval, maxval, **kwargs)
elif dtype is np.float:
elems = st.floats(minval, maxval, **kwargs)
elif dtype is np.str:
elems = st.text(min_size=minval, max_size=maxval, **kwargs)
else:
raise ValueError('no elements strategy for dtype', dtype)
return arrays(dtype, array_shapes(2, 2, min_side, max_side), elements=elems)
示例2: test_Axis_iterator_multiple_items_0d
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_Axis_iterator_multiple_items_0d():
name = "some_name"
label = "some_label"
unit = "some_unit"
arrays = [np.array(1), np.array(2), np.array(3)]
axis = Axis(arrays[0], name=name, label=label, unit=unit)
axis.append(Axis(arrays[1], name=name, label=label, unit=unit))
axis.append(Axis(arrays[2], name=name, label=label, unit=unit))
for ax, arr in zip(axis, arrays):
assert ax is not axis
assert ax.name == name
assert ax.label == label
assert ax.unit == unit
np.testing.assert_array_equal(ax, arr)
示例3: numpy_video
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def numpy_video(
draw,
min_length=1,
max_length=3,
min_width=1,
max_width=10,
min_height=1,
max_height=10,
mode=None,
):
length, height, width = draw(
video_shape(
min_length, max_length, min_height, max_height, min_width, max_width
)
)
if mode is None:
mode = draw(st.sampled_from(["RGB", "L"]))
if mode == "RGB":
array_st = arrays(dtype=np.uint8, shape=(length, width, height, 3))
else:
array_st = arrays(dtype=np.uint8, shape=(length, width, height))
return draw(array_st)
示例4: test_padding
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_padding(ndim: int, data: st.DataObject):
"""Ensure that convolving a padding-only image with a commensurate kernel yields the single entry: 0"""
padding = data.draw(
st.integers(1, 3) | st.tuples(*[st.integers(1, 3)] * ndim), label="padding"
)
x = Tensor(
data.draw(
hnp.arrays(shape=(1, 1) + (0,) * ndim, dtype=float, elements=st.floats()),
label="x",
)
)
pad_tuple = padding if isinstance(padding, tuple) else (padding,) * ndim
kernel = data.draw(
hnp.arrays(
shape=(1, 1) + tuple(2 * p for p in pad_tuple),
dtype=float,
elements=st.floats(allow_nan=False, allow_infinity=False),
)
)
out = conv_nd(x, kernel, padding=padding, stride=1)
assert out.shape == (1,) * x.ndim
assert out.item() == 0.0
out.sum().backward()
assert x.grad.shape == x.shape
示例5: test_negative_log_likelihood
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_negative_log_likelihood(data: st.DataObject, labels_as_tensor: bool):
s = data.draw(
hnp.arrays(
shape=hnp.array_shapes(max_side=10, min_dims=2, max_dims=2),
dtype=float,
elements=st.floats(-100, 100),
)
)
y_true = data.draw(
hnp.arrays(
shape=(s.shape[0],),
dtype=hnp.integer_dtypes(),
elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
).map(Tensor if labels_as_tensor else lambda x: x)
)
scores = Tensor(s)
nll = negative_log_likelihood(mg.log(mg.nnet.softmax(scores)), y_true)
nll.backward()
cross_entropy_scores = Tensor(s)
ce = softmax_crossentropy(cross_entropy_scores, y_true)
ce.backward()
assert_allclose(nll.data, ce.data, atol=1e-5, rtol=1e-5)
assert_allclose(scores.grad, cross_entropy_scores.grad, atol=1e-5, rtol=1e-5)
示例6: arrays
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def arrays(self, i: int) -> st.SearchStrategy:
"""
Hypothesis search strategy for drawing an array y to be passed to f(x, ..., y_i,...).
By default, y is drawn to have a shape that is broadcast-compatible with x.
Parameters
----------
i : int
The argument index-location of y in the signature of f.
Returns
-------
hypothesis.searchstrategy.SearchStrategy"""
return hnp.arrays(
shape=self.index_to_arr_shapes.get(i),
dtype=float,
elements=st.floats(*self.index_to_bnds.get(i, self.default_bnds)),
)
示例7: test_upcast_roundtrip
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_upcast_roundtrip(type_strategy, data: st.DataObject):
thin, wide = data.draw(
st.tuples(type_strategy, type_strategy).map(
lambda x: sorted(x, key=lambda y: np.dtype(y).itemsize)
)
)
orig_tensor = data.draw(
hnp.arrays(
dtype=thin,
shape=hnp.array_shapes(),
elements=hnp.from_dtype(thin).filter(np.isfinite),
).map(Tensor)
)
roundtripped_tensor = orig_tensor.astype(wide).astype(thin)
assert_array_equal(orig_tensor, roundtripped_tensor)
示例8: test_reduce_broadcast_keepdim
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_reduce_broadcast_keepdim(var_shape, data):
""" example broadcasting: (2, 1, 4) -> (2, 5, 4)"""
grad = data.draw(
hnp.arrays(
dtype=float,
shape=broadcastable_shapes(
shape=var_shape, min_dims=len(var_shape), max_dims=len(var_shape)
),
elements=st.just(1.0),
),
label="grad",
)
reduced_grad = reduce_broadcast(grad=grad, var_shape=var_shape)
assert reduced_grad.shape == tuple(
i if i < j else j for i, j in zip(var_shape, grad.shape)
)
assert (i == 1 for i, j in zip(var_shape, grad.shape) if i < j)
sum_axes = tuple(n for n, (i, j) in enumerate(zip(var_shape, grad.shape)) if i != j)
assert_allclose(actual=reduced_grad, desired=grad.sum(axis=sum_axes, keepdims=True))
示例9: test_scalars_dict_update
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_scalars_dict_update():
mesh = examples.load_uniform()
n = len(mesh.point_arrays)
arrays = {
'foo': np.arange(mesh.n_points),
'rand': np.random.random(mesh.n_points)
}
mesh.point_arrays.update(arrays)
assert 'foo' in mesh.array_names
assert 'rand' in mesh.array_names
assert len(mesh.point_arrays) == n + 2
# Test update from Table
table = pyvista.Table(arrays)
mesh = examples.load_uniform()
mesh.point_arrays.update(table)
assert 'foo' in mesh.array_names
assert 'rand' in mesh.array_names
assert len(mesh.point_arrays) == n + 2
示例10: test_draw_bs_pairs_linreg_nan
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_draw_bs_pairs_linreg_nan():
x = np.array([])
y = np.array([])
with pytest.raises(RuntimeError) as excinfo:
dcst.draw_bs_pairs_linreg(x, y, size=1)
excinfo.match('Arrays must have at least 2 mutual non-NaN entries.')
x = np.array([np.nan])
y = np.array([np.nan])
with pytest.raises(RuntimeError) as excinfo:
dcst.draw_bs_pairs_linreg(x, y, size=1)
excinfo.match('Arrays must have at least 2 mutual non-NaN entries.')
x = np.array([np.nan, 1])
y = np.array([1, np.nan])
with pytest.raises(RuntimeError) as excinfo:
dcst.draw_bs_pairs_linreg(x, y, size=1)
excinfo.match('Arrays must have at least 2 mutual non-NaN entries.')
x = np.array([0, 1, 5])
y = np.array([1, np.inf, 3])
with pytest.raises(RuntimeError) as excinfo:
dcst.draw_bs_pairs_linreg(x, y, size=1)
excinfo.match('All entries in arrays must be finite.')
示例11: test_pearson_r_edge
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_pearson_r_edge():
x = np.array([])
y = np.array([])
with pytest.raises(RuntimeError) as excinfo:
dcst.pearson_r(x, y)
excinfo.match('Arrays must have at least 2 mutual non-NaN entries.')
x = np.array([np.nan])
y = np.array([np.nan])
with pytest.raises(RuntimeError) as excinfo:
dcst.pearson_r(x, y)
excinfo.match('Arrays must have at least 2 mutual non-NaN entries.')
x = np.array([np.nan, 1])
y = np.array([1, np.nan])
with pytest.raises(RuntimeError) as excinfo:
dcst.pearson_r(x, y)
excinfo.match('Arrays must have at least 2 mutual non-NaN entries.')
x = np.array([0, 1, 5])
y = np.array([1, np.inf, 3])
with pytest.raises(RuntimeError) as excinfo:
dcst.pearson_r(x, y)
excinfo.match('All entries in arrays must be finite.')
示例12: test_tabulations
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_tabulations():
assert np.allclose(tabulation[Delhommeau_f90][2][:, :, 0, 0],
tabulation[XieDelhommeau_f90][2][:, :, 0, 0])
assert np.allclose(tabulation[Delhommeau_f90][2][:, :, 1, 0],
tabulation[XieDelhommeau_f90][2][:, :, 1, 0])
assert np.allclose(tabulation[Delhommeau_f90][2][:, :, 1, 1],
tabulation[XieDelhommeau_f90][2][:, :, 1, 1])
r_range = tabulation[Delhommeau_f90][0]
Z_range = tabulation[Delhommeau_f90][1]
# Make 2D arrays
r = r_range[:, None] * np.ones_like(Z_range)[None, :]
Z = np.ones_like(r_range)[:, None] * Z_range[None, :]
R1 = np.sqrt(np.square(r) + np.square(Z))
# Compare Z1, for great values of Z, where both methods are as accurate
Del = tabulation[Delhommeau_f90][2][:, :, 0, 1] - pi/R1
Xie = tabulation[XieDelhommeau_f90][2][:, :, 0, 1]
assert np.allclose(Del[abs(Z) > 1], Xie[abs(Z) > 1], atol=1e-3)
示例13: to_min_max
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def to_min_max(arr: np.ndarray) -> st.SearchStrategy:
bnd_shape = hnp.broadcastable_shapes(
shape=arr.shape, max_dims=arr.ndim, max_side=min(arr.shape) if arr.ndim else 1
)
bnd_strat = hnp.arrays(
shape=bnd_shape, elements=st.floats(-1e6, 1e6), dtype=np.float64
)
return st.fixed_dictionaries(dict(a_min=bnd_strat, a_max=bnd_strat))
示例14: test_multiclass_hinge
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_multiclass_hinge(data):
"""Test the built-in implementation of multiclass hinge
against the pure mygrad version"""
s = data.draw(
hnp.arrays(
shape=hnp.array_shapes(max_side=10, min_dims=2, max_dims=2),
dtype=float,
elements=st.floats(-100, 100),
)
)
loss = data.draw(
hnp.arrays(
shape=(s.shape[0],),
dtype=hnp.integer_dtypes(),
elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
)
)
hinge_scores = Tensor(s)
hinge_loss = multiclass_hinge(hinge_scores, loss, constant=False)
hinge_loss.backward()
mygrad_scores = Tensor(s)
correct_labels = (range(len(loss)), loss)
correct_class_scores = mygrad_scores[correct_labels] # Nx1
Lij = mygrad_scores - correct_class_scores[:, np.newaxis] + 1.0 # NxC margins
Lij[Lij <= 0] = 0
Lij[correct_labels] = 0
mygrad_loss = Lij.sum() / mygrad_scores.shape[0]
mygrad_loss.backward()
assert_allclose(hinge_loss.data, mygrad_loss.data)
assert_allclose(mygrad_scores.grad, hinge_scores.grad)
示例15: test_softmax_focal_loss
# 需要导入模块: from hypothesis.extra import numpy [as 别名]
# 或者: from hypothesis.extra.numpy import arrays [as 别名]
def test_softmax_focal_loss(num_datum, num_classes, alpha, gamma, data, grad, target_type):
scores = data.draw(
hnp.arrays(shape=(num_datum, num_classes), dtype=float, elements=st.floats(1, 100))
)
assume((abs(scores.sum(axis=1)) > 0.001).all())
scores_mygrad = Tensor(scores)
scores_nn = Tensor(scores)
truth = np.zeros((num_datum, num_classes))
targets = data.draw(st.tuples(*(st.integers(0, num_classes - 1) for i in range(num_datum))))
truth[range(num_datum), targets] = 1
targets = target_type(targets)
probs = softmax(scores_mygrad)
mygrad_focal_loss = sum(truth * (-alpha * (1 - probs + 1e-14)**gamma * log(probs))) / num_datum
mygrad_focal_loss.backward(grad)
nn_loss = softmax_focal_loss(scores_nn, targets, alpha=alpha, gamma=gamma).mean()
nn_loss.backward(grad)
assert isinstance(nn_loss, Tensor) and nn_loss.ndim == 0
assert_allclose(nn_loss.data, mygrad_focal_loss.data, atol=1e-4, rtol=1e-4)
assert_allclose(scores_nn.grad, scores_mygrad.grad, atol=1e-4, rtol=1e-4)
nn_loss.null_gradients()
assert scores_nn.grad is None