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_callback(self): """Test the callback function of the VQC.""" history = { 'eval_count': [], 'parameters': [], 'cost': [], 'batch_index': [] } def store_intermediate_result(eval_count, parameters, cost, batch_index): history['eval_count'].append(eval_count) history['parameters'].append(parameters) history['cost'].append(cost) history['batch_index'].append(batch_index) optimizer = COBYLA(maxiter=3) data_preparation = self.data_preparation wavefunction = self.ryrz_wavefunction # set up algorithm vqc = VQC(optimizer, data_preparation, wavefunction, self.training_data, self.testing_data, callback=store_intermediate_result) vqc.run(self.qasm_simulator) with self.subTest('eval count'): self.assertTrue( all(isinstance(count, int) for count in history['eval_count'])) with self.subTest('cost'): self.assertTrue( all(isinstance(cost, float) for cost in history['cost'])) with self.subTest('batch index'): self.assertTrue( all( isinstance(index, int) for index in history['batch_index'])) for params in history['parameters']: with self.subTest('params'): self.assertTrue( all(isinstance(param, float) for param in params))
def test_save_and_load_model(self): """Test saving and loading a model with the VQC.""" data_preparation = self.data_preparation wavefunction = self.ryrz_wavefunction vqc = VQC(self.spsa, data_preparation, wavefunction, self.training_data, self.testing_data) result = vqc.run(self.qasm_simulator) with self.subTest( msg='check optimal params, training loss and testing accuracy' ): np.testing.assert_array_almost_equal(result['opt_params'], self.ref_opt_params, decimal=4) np.testing.assert_array_almost_equal(result['training_loss'], self.ref_train_loss, decimal=8) self.assertEqual(0.5, result['testing_accuracy']) file_path = self.get_resource_path('vqc_test.npz') vqc.save_model(file_path) with self.subTest(msg='assert saved file exists'): self.assertTrue(os.path.exists(file_path)) loaded_vqc = VQC(self.spsa, data_preparation, wavefunction, self.training_data, None) loaded_vqc.load_model(file_path) loaded_test_acc = loaded_vqc.test(vqc.test_dataset[0], vqc.test_dataset[1], self.qasm_simulator) with self.subTest( msg= 'check optimal parameters and testing accuracy of loaded model' ): np.testing.assert_array_almost_equal(loaded_vqc.ret['opt_params'], self.ref_opt_params, decimal=4) self.assertEqual(result['testing_accuracy'], loaded_test_acc) predicted_probs, predicted_labels = loaded_vqc.predict( self.testing_data['A'], self.qasm_simulator) with self.subTest(msg='check probs and labels of predicted labels'): np.testing.assert_array_almost_equal(predicted_probs, self.ref_prediction_a_probs, decimal=8) np.testing.assert_array_equal(predicted_labels, self.ref_prediction_a_label) if os.path.exists(file_path): try: os.remove(file_path) except Exception: # pylint: disable=broad-except pass
def test_same_parameter_names_raises(self): """Test that the varform and feature map can have parameters with the same name.""" algorithm_globals.random_seed = self.seed var_form = QuantumCircuit(1) var_form.ry(Parameter('a'), 0) feature_map = QuantumCircuit(1) feature_map.rz(Parameter('a'), 0) optimizer = SPSA() vqc = VQC(optimizer, feature_map, var_form, self.training_data, self.testing_data) with self.assertRaises(QiskitMachineLearningError): _ = vqc.run(BasicAer.get_backend('statevector_simulator'))
def test_usage_in_vqc(self): """Test using the circuit the a single VQC iteration works.""" feature_dim = 4 _, training_input, test_input, _ = wine(training_size=1, test_size=1, n=feature_dim, plot_data=False) feature_map = RawFeatureVector(feature_dimension=feature_dim) vqc = VQC(COBYLA(maxiter=1), feature_map, EfficientSU2(feature_map.num_qubits, reps=1), training_input, test_input) backend = Aer.get_backend('qasm_simulator') result = vqc.run(backend) self.assertTrue(result['eval_count'] > 0)
def test_statevector(self): """Test running the VQC on BasicAer's Statevector simulator.""" optimizer = L_BFGS_B(maxfun=200) data_preparation = self.data_preparation wavefunction = self.ryrz_wavefunction vqc = VQC(optimizer, data_preparation, wavefunction, self.training_data, self.testing_data) result = vqc.run(self.statevector_simulator) with self.subTest(msg='check training loss'): self.assertLess(result['training_loss'], 0.12) with self.subTest(msg='check testing accuracy'): self.assertEqual(result['testing_accuracy'], 0.5)
def test_readme_sample(self): """ readme sample test """ # pylint: disable=import-outside-toplevel,redefined-builtin def print(*args): """ overloads print to log values """ if args: self.log.debug(args[0], *args[1:]) # --- Exact copy of sample code ---------------------------------------- from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_machine_learning.algorithms import VQC from qiskit_machine_learning.datasets import wine from qiskit_machine_learning.circuit.library import RawFeatureVector seed = 1376 algorithm_globals.random_seed = seed # Use Wine data set for training and test data feature_dim = 4 # dimension of each data point _, training_input, test_input, _ = wine(training_size=12, test_size=4, n=feature_dim) feature_map = RawFeatureVector(feature_dimension=feature_dim) vqc = VQC(COBYLA(maxiter=100), feature_map, TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3), training_input, test_input) result = vqc.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, seed_simulator=seed, seed_transpiler=seed)) print('Testing accuracy: {:0.2f}'.format(result['testing_accuracy'])) # ---------------------------------------------------------------------- self.assertGreater(result['testing_accuracy'], 0.8)
def test_raw_feature_vector_on_wine(self, ): """Test VQC on the wine dataset using the ``RawFeatureVector`` as data preparation.""" feature_dim = 4 # dimension of each data point training_dataset_size = 8 testing_dataset_size = 4 _, training_input, test_input, _ = wine( training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, plot_data=False) feature_map = RawFeatureVector(feature_dimension=feature_dim) vqc = VQC(COBYLA(maxiter=100), feature_map, TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3), training_input, test_input) result = vqc.run(self.statevector_simulator) self.log.debug(result['testing_accuracy']) self.assertGreater(result['testing_accuracy'], 0.7)
def test_wine(self): """Test VQC on the wine dataset.""" feature_dim = 4 # dimension of each data point training_dataset_size = 6 testing_dataset_size = 3 _, training_input, test_input, _ = wine( training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, plot_data=False) algorithm_globals.random_seed = self.seed data_preparation = ZZFeatureMap(feature_dim) wavefunction = TwoLocal(feature_dim, ['ry', 'rz'], 'cz', reps=2) vqc = VQC(COBYLA(maxiter=100), data_preparation, wavefunction, training_input, test_input) result = vqc.run(self.statevector_simulator) self.log.debug(result['testing_accuracy']) self.assertGreater(result['testing_accuracy'], 0.3)
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)