def test_ad_hoc_data(self): """Ad Hoc Data test.""" training_features, training_labels, _, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, gap=0.3, plot_data=False, one_hot=False) np.testing.assert_array_equal(training_features.shape, (40, 2)) np.testing.assert_array_equal(training_labels.shape, (40,)) np.testing.assert_array_almost_equal(test_labels, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) _, _, _, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, gap=0.3, plot_data=False, one_hot=True) np.testing.assert_array_equal(test_labels.shape, (20, 2)) np.testing.assert_array_equal(test_labels, [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]])
def test_ref_data(self): """Tests ad hoc against known reference data""" input_file = self.get_resource_path("ad_hoc_ref.json", "datasets") with open(input_file, encoding="utf8") as file: ref_data = json.load(file) for seed in ref_data: algorithm_globals.random_seed = int(seed) training_features, training_labels, test_features, test_labels = ad_hoc_data( training_size=20, test_size=5, n=2, gap=0.3, plot_data=False, one_hot=False) with self.subTest("Test training_features"): np.testing.assert_almost_equal( ref_data[seed]["training_features"], training_features) with self.subTest("Test training_labels"): np.testing.assert_almost_equal( ref_data[seed]["training_labels"], training_labels) with self.subTest("Test test_features"): np.testing.assert_almost_equal(ref_data[seed]["test_features"], test_features) with self.subTest("Test test_labels"): np.testing.assert_almost_equal(ref_data[seed]["test_labels"], test_labels)
def test_wrong_params(self, num_features): """Tests Ad Hoc Data with wrong parameters.""" with self.assertRaises(ValueError): _, _, _, _ = ad_hoc_data(training_size=20, test_size=10, n=num_features, gap=0.3)
def test_minibatching_gradient_based(self): """Test the minibatching option with a gradient-based optimizer.""" n_dim = 2 # dimension of each data point _, training_input, test_input, _ = ad_hoc_data(training_size=4, test_size=2, n=n_dim, gap=0.3, plot_data=False) optimizer = L_BFGS_B(maxfun=30) data_preparation = self.data_preparation wavefunction = TwoLocal(2, ['ry', 'rz'], 'cz', reps=1, insert_barriers=True) vqc = VQC(optimizer, data_preparation, wavefunction, training_input, test_input, minibatch_size=2) result = vqc.run(self.statevector_simulator) self.log.debug(result['testing_accuracy']) self.assertAlmostEqual(result['testing_accuracy'], 0.75, places=3)
def test_ad_hoc_data(self): """Ad Hoc Data test.""" _, _, test_input, class_labels = ad_hoc_data(training_size=20, test_size=10, n=2, gap=0.3, plot_data=False) np.testing.assert_array_equal(class_labels, ['A', 'B']) datapoints, class_to_label = split_dataset_to_data_and_labels( test_input) np.testing.assert_array_equal( datapoints[1].tolist(), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) self.assertDictEqual(class_to_label, {'A': 0, 'B': 1})
def test_minibatching_gradient_free(self): """Test the minibatching option with a gradient-free optimizer.""" n_dim = 2 # dimension of each data point _, training_input, test_input, _ = ad_hoc_data(training_size=6, test_size=3, n=n_dim, gap=0.3, plot_data=False) optimizer = COBYLA(maxiter=40) data_preparation = self.data_preparation wavefunction = self.ryrz_wavefunction vqc = VQC(optimizer, data_preparation, wavefunction, training_input, test_input, minibatch_size=2) result = vqc.run(self.qasm_simulator) self.log.debug(result['testing_accuracy']) self.assertAlmostEqual(result['testing_accuracy'], 0.3333333333333333)
def test_matrix_psd(self): """ Test kernel matrix positive semi-definite enforcement. """ try: from cvxpy.error import DQCPError except ImportError: self.skipTest('cvxpy does not appeat to be installed') seed = 10598 feature_dim = 2 _, training_input, _, _ = ad_hoc_data(training_size=10, test_size=5, n=feature_dim, gap=0.3) training_input, _ = split_dataset_to_data_and_labels(training_input) training_data = training_input[0] training_labels = training_input[1] labels = training_labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1 labels = labels.astype(float) feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear') try: with self.assertRaises(DQCPError): # Sampling noise means that the kernel matrix will not quite be positive # semi-definite which will cause the optimize svm to fail backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) kernel_matrix = QSVM.get_kernel_matrix(quantum_instance, feature_map=feature_map, x1_vec=training_data, enforce_psd=False) _ = optimize_svm(kernel_matrix, labels, lambda2=0) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) return # This time we enforce that the matrix be positive semi-definite which runs logic to # make it so. backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) kernel_matrix = QSVM.get_kernel_matrix(quantum_instance, feature_map=feature_map, x1_vec=training_data, enforce_psd=True) alpha, b, support = optimize_svm(kernel_matrix, labels, lambda2=0) expected_alpha = [ 0.855861781, 2.59807482, 0, 0.962959215, 1.08141696, 0.217172547, 0, 0, 0.786462904, 0, 0.969727949, 1.98066946, 0, 0, 1.62049430, 0, 0.394212728, 0, 0.507740935, 1.02910286 ] expected_b = [-0.17543365] expected_support = [ True, True, False, True, True, True, False, False, True, False, True, True, False, False, True, False, True, False, True, True ] np.testing.assert_array_almost_equal(alpha, expected_alpha) np.testing.assert_array_almost_equal(b, expected_b) np.testing.assert_array_equal(support, expected_support)
from qiskit_machine_learning.datasets import ad_hoc_data from qiskit_machine_learning.algorithms import VQC from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.providers.aer import QasmSimulator X_train, y_train, X_test, y_test = ad_hoc_data(20, 10, 2, 0.1) num_qubits = 2 vqc = VQC(feature_map=ZZFeatureMap(num_qubits), ansatz=RealAmplitudes(num_qubits, reps=1), loss='cross_entropy', optimizer=L_BFGS_B(), quantum_instance=QasmSimulator()) vqc.fit(X_train, y_train) vqc.score(X_test, y_test)