def test_qsvm_binary_directly_statevector(self): """ QSVM Binary Directly Statevector test """ ref_kernel_testing = np. array([[0.1443953, 0.18170069, 0.47479649, 0.14691763], [0.33041779, 0.37663733, 0.02115561, 0.16106199]]) ref_support_vectors = np.array([[2.95309709, 2.51327412], [3.14159265, 4.08407045], [4.08407045, 2.26194671], [4.46106157, 2.38761042]]) backend = BasicAer.get_backend('statevector_simulator') num_qubits = 2 feature_map = SecondOrderExpansion(feature_dimension=num_qubits, depth=2, entangler_map=[[0, 1]]) svm = QSVM(feature_map, self.training_data, self.testing_data, None) quantum_instance = QuantumInstance(backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed) file_path = self.get_resource_path('qsvm_test.npz') try: result = svm.run(quantum_instance) ori_alphas = result['svm']['alphas'] np.testing.assert_array_almost_equal( result['kernel_matrix_testing'], ref_kernel_testing, decimal=4) self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal( result['svm']['support_vectors'], ref_support_vectors, decimal=4) self.assertEqual(result['testing_accuracy'], 0.5) svm.save_model(file_path) self.assertTrue(os.path.exists(file_path)) loaded_svm = QSVM(feature_map) loaded_svm.load_model(file_path) np.testing.assert_array_almost_equal( loaded_svm.ret['svm']['support_vectors'], ref_support_vectors, decimal=4) np.testing.assert_array_almost_equal( loaded_svm.ret['svm']['alphas'], ori_alphas, decimal=4) loaded_test_acc = loaded_svm.test(svm.test_dataset[0], svm.test_dataset[1], quantum_instance) self.assertEqual(result['testing_accuracy'], loaded_test_acc) np.testing.assert_array_almost_equal( loaded_svm.ret['kernel_matrix_testing'], ref_kernel_testing, decimal=4) except NameError as ex: self.skipTest(str(ex)) finally: if os.path.exists(file_path): try: os.remove(file_path) except Exception: # pylint: disable=broad-except pass
def test_binary_directly_statevector(self): """Test QSVM on binary classification on BasicAer's statevector simulator. Also tests saving and loading models.""" data_preparation = self.data_preparation svm = QSVM(data_preparation, self.training_data, self.testing_data, None) file_path = self.get_resource_path('qsvm_test.npz') try: result = svm.run(self.statevector_simulator) ori_alphas = result['svm']['alphas'] np.testing.assert_array_almost_equal( result['kernel_matrix_testing'], self.ref_kernel_testing['statevector'], decimal=4) self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal( result['svm']['support_vectors'], self.ref_support_vectors, decimal=4) self.assertEqual(result['testing_accuracy'], 0.5) svm.save_model(file_path) self.assertTrue(os.path.exists(file_path)) loaded_svm = QSVM(data_preparation) loaded_svm.load_model(file_path) np.testing.assert_array_almost_equal( loaded_svm.ret['svm']['support_vectors'], self.ref_support_vectors, decimal=4) np.testing.assert_array_almost_equal( loaded_svm.ret['svm']['alphas'], ori_alphas, decimal=4) loaded_test_acc = loaded_svm.test(svm.test_dataset[0], svm.test_dataset[1], self.statevector_simulator) self.assertEqual(result['testing_accuracy'], loaded_test_acc) np.testing.assert_array_almost_equal( loaded_svm.ret['kernel_matrix_testing'], self.ref_kernel_testing['statevector'], decimal=4) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) finally: if os.path.exists(file_path): try: os.remove(file_path) except Exception: # pylint: disable=broad-except pass
def compareMethods(class1, class2, class3 = None, backend=BasicAer.get_backend('qasm_simulator'), name = "", include_unscaled=False, include_QSVM = True, include_VQC = True, feature_dimension = 2, gamma = 'auto', C = 1.0): #Define header and chart data data = [] header = ["Algorithm", "Backend", "Time", "Accuracy", "Only one Class Predicted?"] data.append(header) #Split data into train and test class1_train, class1_test = train_test_split(class1, test_size=0.33, random_state=42) class2_train, class2_test = train_test_split(class2, test_size=0.33, random_state=42) feature_dim = feature_dimension if class3 is not None: class3_train, class3_test = train_test_split(class3, test_size=0.33, random_state=42) #Get input data for quantum training_data = {'A': np.asarray(class1_train), 'B': np.asarray(class2_train)} test_data = {'A': np.asarray(class1_test), 'B': np.asarray(class2_test)} total_array = np.concatenate((test_data['A'], test_data['B'])) if class3 is not None: training_data["C"] = class3_train test_data["C"] = class3_test total_array = np.concatenate((total_array, test_data['C'])) #Get input data for classical X_train, x_test, Y_train, y_test = convertFromQS(training_data, test_data) #Classical SVM, linear kernel (scaled and unscaled) if include_unscaled: start = time.time() clf = svm.SVC(kernel='linear') # Linear Kernel model = clf.fit(X_train, Y_train) y_pred = clf.predict(x_test) end = time.time() data.append(["SVM, Linear Kernel", "Local Processor", round(end-start), str(round(100*metrics.accuracy_score(y_test, y_pred), 2)),checkAllSame(y_pred)]) start = time.time() scaler = StandardScaler() X_train_std = scaler.fit_transform(X_train) x_test_std = scaler.fit_transform(x_test) clf = svm.SVC(kernel='linear') # Linear Kernel model = clf.fit(X_train_std, Y_train) y_pred = clf.predict(x_test_std) end = time.time() data.append(["SVM, Linear Kernel, scaled", "Local Processor", round(end-start), str(round(100*metrics.accuracy_score(y_test, y_pred), 2)),checkAllSame(y_pred)]) #Classical SVM, rbf kernel (scaled and unscaled) if include_unscaled: start = time.time() clf = svm.SVC(C=C, kernel='rbf', gamma = gamma) # rbf Kernel model = clf.fit(X_train, Y_train) y_pred = clf.predict(x_test) end = time.time() data.append(["SVM, RBF Kernel", "Local Processor", round(end-start), str(round(100*metrics.accuracy_score(y_test, y_pred), 2)),checkAllSame(y_pred)]) start = time.time() scaler = StandardScaler() X_train_std = scaler.fit_transform(X_train) x_test_std = scaler.fit_transform(x_test) clf = svm.SVC(C=C, kernel='rbf', gamma = gamma) # rbf Kernel model = clf.fit(X_train_std, Y_train) y_pred = clf.predict(x_test_std) end = time.time() data.append(["SVM, RBF Kernel, scaled", "Local Processor", round(end-start), str(round(100*metrics.accuracy_score(y_test, y_pred), 2)),checkAllSame(y_pred)]) #QSVM run if include_QSVM: start = time.time() feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear') if class3 is None: qsvm = QSVM(feature_map, training_data, test_data, total_array) else: qsvm = QSVM(feature_map, training_data, test_data, total_array, multiclass_extension=AllPairs()) quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598) resultSVM = qsvm.run(quantum_instance) end = time.time() QSVM_Summary = ["QSVM", backend.name(), round(end-start), str(round(100*resultSVM['testing_accuracy'], 2)), checkAllSame(resultSVM['predicted_classes'])] data.append(QSVM_Summary) path = 'C:\\Users\\admin\\Desktop\\QQML\\Code\\Saved_SVMs\\' + name + "_" + backend.name() + "_QSVM" if class3 is None: #Bug in package prevents saving Multiclass svms. Will find workaround or submit bug report if time. qsvm.save_model(path) #VQC run if include_VQC: start = time.time() optimizer = SPSA(max_trials=100, c0=4.0, skip_calibration=True) optimizer.set_options(save_steps=1) feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2) var_form = TwoLocal(feature_dim, ['ry', 'rz'], 'cz', reps=3) vqc = VQC(optimizer, feature_map, var_form, training_data, test_data, total_array) quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10589, seed_transpiler=10598) resultVQC = vqc.run(quantum_instance) end = time.time() VQC_Summary = ["VQC", backend.name(), round(end-start), str(round(100*resultVQC['testing_accuracy'], 2)), checkAllSame(resultVQC['predicted_classes'])] data.append(VQC_Summary) path = 'C:\\Users\\admin\\Desktop\\QQML\\Code\\Saved_SVMs\\' + name + "_" + backend.name() + "_VQC" vqc.save_model(path) display(HTML(tabulate.tabulate(data, tablefmt='html'))) return data