本文整理汇总了Python中numpy.allclose方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.allclose方法的具体用法?Python numpy.allclose怎么用?Python numpy.allclose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.allclose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_clip_eta_goldilocks
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_clip_eta_goldilocks(self):
# Test that the clipping handles perturbations that are
# too small, just right, and too big correctly
eta = tf.constant([[2.], [3.], [4.]])
assert eta.dtype == tf.float32, eta.dtype
eps = 3.
for ord_arg in [np.inf, 1, 2]:
for sign in [-1., 1.]:
clipped = clip_eta(eta * sign, ord_arg, eps)
clipped_value = self.sess.run(clipped)
gold = sign * np.array([[2.], [3.], [3.]])
self.assertClose(clipped_value, gold)
grad, = tf.gradients(clipped, eta)
grad_value = self.sess.run(grad)
# Note: the second 1. is debatable (the left-sided derivative
# and the right-sided derivative do not match, so formally
# the derivative is not defined). This test makes sure that
# we at least handle this oddity consistently across all the
# argument values we test
gold = sign * np.array([[1.], [1.], [0.]])
assert np.allclose(grad_value, gold)
示例2: test_separate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_separate(test_file, configuration, backend):
""" Test separation from raw data. """
with tf.Session() as sess:
instruments = MODEL_TO_INST[configuration]
adapter = get_default_audio_adapter()
waveform, _ = adapter.load(test_file)
separator = Separator(configuration, stft_backend=backend)
prediction = separator.separate(waveform, test_file)
assert len(prediction) == len(instruments)
for instrument in instruments:
assert instrument in prediction
for instrument in instruments:
track = prediction[instrument]
assert waveform.shape[:-1] == track.shape[:-1]
assert not np.allclose(waveform, track)
for compared in instruments:
if instrument != compared:
assert not np.allclose(track, prediction[compared])
示例3: test_naivebayes_breastcancer
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_naivebayes_breastcancer(self):
# python -m unittest tests_classification.Tests_Classification.test_naivebayes_breastcancer
from discomll.classification import naivebayes
train_data1, test_data1 = datasets.breastcancer_disc_orange()
train_data2, test_data2 = datasets.breastcancer_disc_discomll()
for m in range(3):
learner = Orange.classification.bayes.NaiveLearner(m=m)
classifier = learner(train_data1)
predictions1 = [classifier(inst, Orange.classification.Classifier.GetBoth) for inst in test_data1]
predictions1_target = [v[0].value for v in predictions1]
predictions1_probs = [v[1].values() for v in predictions1]
fitmodel_url = naivebayes.fit(train_data2)
predictions_url = naivebayes.predict(test_data2, fitmodel_url, m=m)
predictions2_target = []
predictions2_probs = []
for k, v in result_iterator(predictions_url):
predictions2_target.append(v[0])
predictions2_probs.append(v[1])
self.assertListEqual(predictions1_target, predictions2_target)
self.assertTrue(np.allclose(predictions1_probs, predictions2_probs))
示例4: test_naivebayes_breastcancer_cont
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_naivebayes_breastcancer_cont(self):
# python -m unittest tests_classification.Tests_Classification.test_naivebayes_breastcancer_cont
from sklearn.naive_bayes import GaussianNB
from discomll.classification import naivebayes
x_train, y_train, x_test, y_test = datasets.breastcancer_cont(replication=1)
train_data, test_data = datasets.breastcancer_cont_discomll(replication=1)
clf = GaussianNB()
probs_log1 = clf.fit(x_train, y_train).predict_proba(x_test)
fitmodel_url = naivebayes.fit(train_data)
prediction_url = naivebayes.predict(test_data, fitmodel_url)
probs_log2 = [v[1] for _, v in result_iterator(prediction_url)]
self.assertTrue(np.allclose(probs_log1, probs_log2, atol=1e-8))
示例5: test_lwlr
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_lwlr(self):
# python -m unittest tests_regression.Tests_Regression.test_lwlr
import locally_weighted_linear_regression as lwlr1
from discomll.regression import locally_weighted_linear_regression as lwlr2
x_train, y_train, x_test, y_test = datasets.regression_data()
train_data, test_data = datasets.regression_data_discomll()
lwlr1 = lwlr1.Locally_Weighted_Linear_Regression()
taus = [1, 10, 25]
sorted_indices = np.argsort([str(el) for el in x_test[:, 1].tolist()])
for tau in taus:
thetas1, estimation1 = lwlr1.fit(x_train, y_train, x_test, tau=tau)
thetas1, estimation1 = np.array(thetas1)[sorted_indices], np.array(estimation1)[sorted_indices]
results = lwlr2.fit_predict(train_data, test_data, tau=tau)
thetas2, estimation2 = [], []
for x_id, (est, thetas) in result_iterator(results):
estimation2.append(est)
thetas2.append(thetas)
self.assertTrue(np.allclose(thetas1, thetas2, atol=1e-8))
self.assertTrue(np.allclose(estimation1, estimation2, atol=1e-3))
示例6: test_add_single_ground_truth_image_info
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_add_single_ground_truth_image_info(self):
expected_num_gt_instances_per_class = np.array([3, 1, 2], dtype=int)
expected_num_gt_imgs_per_class = np.array([2, 1, 2], dtype=int)
self.assertTrue(np.array_equal(expected_num_gt_instances_per_class,
self.od_eval.num_gt_instances_per_class))
self.assertTrue(np.array_equal(expected_num_gt_imgs_per_class,
self.od_eval.num_gt_imgs_per_class))
groundtruth_boxes2 = np.array([[10, 10, 11, 11], [500, 500, 510, 510],
[10, 10, 12, 12]], dtype=float)
self.assertTrue(np.allclose(self.od_eval.groundtruth_boxes["img2"],
groundtruth_boxes2))
groundtruth_is_difficult_list2 = np.array([False, True, False], dtype=bool)
self.assertTrue(np.allclose(
self.od_eval.groundtruth_is_difficult_list["img2"],
groundtruth_is_difficult_list2))
groundtruth_class_labels1 = np.array([0, 2, 0], dtype=int)
self.assertTrue(np.array_equal(self.od_eval.groundtruth_class_labels[
"img1"], groundtruth_class_labels1))
示例7: test_add_single_detected_image_info
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_add_single_detected_image_info(self):
expected_scores_per_class = [[np.array([0.8, 0.7], dtype=float)], [],
[np.array([0.9], dtype=float)]]
expected_tp_fp_labels_per_class = [[np.array([0, 1], dtype=bool)], [],
[np.array([0], dtype=bool)]]
expected_num_images_correctly_detected_per_class = np.array([0, 0, 0],
dtype=int)
for i in range(self.od_eval.num_class):
for j in range(len(expected_scores_per_class[i])):
self.assertTrue(np.allclose(expected_scores_per_class[i][j],
self.od_eval.scores_per_class[i][j]))
self.assertTrue(np.array_equal(expected_tp_fp_labels_per_class[i][
j], self.od_eval.tp_fp_labels_per_class[i][j]))
self.assertTrue(np.array_equal(
expected_num_images_correctly_detected_per_class,
self.od_eval.num_images_correctly_detected_per_class))
示例8: test_combining_stat
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_combining_stat():
for shape in [(), (3,), (3, 4)]:
li = []
rs1 = RunningStat(shape)
rs2 = RunningStat(shape)
rs = RunningStat(shape)
for _ in range(5):
val = np.random.randn(*shape)
rs1.push(val)
rs.push(val)
li.append(val)
for _ in range(9):
rs2.push(val)
rs.push(val)
li.append(val)
rs1.update(rs2)
assert np.allclose(rs.mean, rs1.mean)
assert np.allclose(rs.std, rs1.std)
示例9: test_givens_inverse
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_givens_inverse():
r"""
The Givens rotation in OpenFermion is defined as
.. math::
\begin{pmatrix}
\cos(\theta) & -e^{i \varphi} \sin(\theta) \\
\sin(\theta) & e^{i \varphi} \cos(\theta)
\end{pmatrix}.
confirm numerically its hermitian conjugate is it's inverse
"""
a = numpy.random.random() + 1j * numpy.random.random()
b = numpy.random.random() + 1j * numpy.random.random()
ab_rotation = givens_matrix_elements(a, b, which='right')
assert numpy.allclose(ab_rotation.dot(numpy.conj(ab_rotation).T),
numpy.eye(2))
assert numpy.allclose(numpy.conj(ab_rotation).T.dot(ab_rotation),
numpy.eye(2))
示例10: test_circuit_generation_and_accuracy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_circuit_generation_and_accuracy():
for dim in range(2, 10):
qubits = cirq.LineQubit.range(dim)
u_generator = numpy.random.random(
(dim, dim)) + 1j * numpy.random.random((dim, dim))
u_generator = u_generator - numpy.conj(u_generator).T
assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T)
unitary = scipy.linalg.expm(u_generator)
circuit = cirq.Circuit()
circuit.append(optimal_givens_decomposition(qubits, unitary))
fermion_generator = QubitOperator(()) * 0.0
for i, j in product(range(dim), repeat=2):
fermion_generator += jordan_wigner(
FermionOperator(((i, 1), (j, 0)), u_generator[i, j]))
true_unitary = scipy.linalg.expm(
get_sparse_operator(fermion_generator).toarray())
assert numpy.allclose(true_unitary.conj().T.dot(true_unitary),
numpy.eye(2 ** dim, dtype=complex))
test_unitary = cirq.unitary(circuit)
assert numpy.isclose(
abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim)
示例11: _eigen_components
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def _eigen_components(self):
components = [(0, np.diag([1, 1, 1, 0, 1, 0, 0, 1]))]
nontrivial_part = np.zeros((3, 3), dtype=np.complex128)
for ij, w in zip([(1, 2), (0, 2), (0, 1)], self.weights):
nontrivial_part[ij] = w
nontrivial_part[ij[::-1]] = w.conjugate()
assert np.allclose(nontrivial_part, nontrivial_part.conj().T)
eig_vals, eig_vecs = np.linalg.eigh(nontrivial_part)
for eig_val, eig_vec in zip(eig_vals, eig_vecs.T):
exp_factor = -eig_val / np.pi
proj = np.zeros((8, 8), dtype=np.complex128)
nontrivial_indices = np.array([3, 5, 6], dtype=np.intp)
proj[nontrivial_indices[:, np.newaxis], nontrivial_indices] = (
np.outer(eig_vec.conjugate(), eig_vec))
components.append((exp_factor, proj))
return components
示例12: assert_permute_consistent
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def assert_permute_consistent(gate):
gate = gate.__copy__()
n_qubits = gate.num_qubits()
qubits = cirq.LineQubit.range(n_qubits)
for pos in itertools.permutations(range(n_qubits)):
permuted_gate = gate.__copy__()
gate.permute(pos)
assert permuted_gate.permuted(pos) == gate
actual_unitary = cirq.unitary(permuted_gate)
ops = [
cca.LinearPermutationGate(n_qubits, dict(zip(range(n_qubits), pos)),
ofc.FSWAP)(*qubits),
gate(*qubits),
cca.LinearPermutationGate(n_qubits, dict(zip(pos, range(n_qubits))),
ofc.FSWAP)(*qubits)
]
circuit = cirq.Circuit(ops)
expected_unitary = cirq.unitary(circuit)
assert np.allclose(actual_unitary, expected_unitary)
with pytest.raises(ValueError):
gate.permute(range(1, n_qubits))
with pytest.raises(ValueError):
gate.permute([1] * n_qubits)
示例13: assert_interaction_operator_consistent
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def assert_interaction_operator_consistent(gate):
interaction_op = gate.interaction_operator_generator()
other_gate = gate.from_interaction_operator(operator=interaction_op)
if other_gate is None:
assert np.allclose(gate.weights, 0)
else:
assert cirq.approx_eq(gate, other_gate)
interaction_op = openfermion.normal_ordered(interaction_op)
other_interaction_op = openfermion.InteractionOperator.zero(
interaction_op.n_qubits)
super(type(gate),
gate).interaction_operator_generator(operator=other_interaction_op)
other_interaction_op = openfermion.normal_ordered(interaction_op)
assert interaction_op == other_interaction_op
other_interaction_op = super(type(gate),
gate).interaction_operator_generator()
other_interaction_op = openfermion.normal_ordered(interaction_op)
assert interaction_op == other_interaction_op
示例14: test_quadratic_fermionic_simulation_gate_unitary
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_quadratic_fermionic_simulation_gate_unitary(weights, exponent):
generator = np.zeros((4, 4), dtype=np.complex128)
# w0 |10><01| + h.c.
generator[2, 1] = weights[0]
generator[1, 2] = weights[0].conjugate()
# w1 |11><11|
generator[3, 3] = weights[1]
expected_unitary = la.expm(-1j * exponent * generator)
gate = ofc.QuadraticFermionicSimulationGate(weights, exponent=exponent)
actual_unitary = cirq.unitary(gate)
assert np.allclose(expected_unitary, actual_unitary)
symbolic_gate = (ofc.QuadraticFermionicSimulationGate(
(sympy.Symbol('w0'), sympy.Symbol('w1')), exponent=sympy.Symbol('t')))
qubits = cirq.LineQubit.range(2)
circuit = cirq.Circuit(symbolic_gate._decompose_(qubits))
resolver = {'w0': weights[0], 'w1': weights[1], 't': exponent}
resolved_circuit = cirq.resolve_parameters(circuit, resolver)
decomp_unitary = resolved_circuit.unitary(qubit_order=qubits)
assert np.allclose(expected_unitary, decomp_unitary)
示例15: test_cubic_fermionic_simulation_gate_consistency_docstring
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import allclose [as 别名]
def test_cubic_fermionic_simulation_gate_consistency_docstring(
weights, exponent):
generator = np.zeros((8, 8), dtype=np.complex128)
# w0 |110><101| + h.c.
generator[6, 5] = weights[0]
generator[5, 6] = weights[0].conjugate()
# w1 |110><011| + h.c.
generator[6, 3] = weights[1]
generator[3, 6] = weights[1].conjugate()
# w2 |101><011| + h.c.
generator[5, 3] = weights[2]
generator[3, 5] = weights[2].conjugate()
expected_unitary = la.expm(-1j * exponent * generator)
gate = ofc.CubicFermionicSimulationGate(weights, exponent=exponent)
actual_unitary = cirq.unitary(gate)
assert np.allclose(expected_unitary, actual_unitary)