示例#1
0
    def test_qsvm_setup_data(self, data_preparation_type):
        """ QSVM Setup Data 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')

        data_preparation = self.data_preparation[data_preparation_type]
        try:
            if data_preparation_type == 'wrapped':
                warnings.filterwarnings('ignore', category=DeprecationWarning)
            svm = QSVM(data_preparation)
            if data_preparation_type == 'wrapped':
                warnings.filterwarnings('always', category=DeprecationWarning)

            svm.setup_training_data(self.training_data)
            svm.setup_test_data(self.testing_data)
            quantum_instance = QuantumInstance(
                backend,
                seed_transpiler=self.random_seed,
                seed_simulator=self.random_seed)
            result = svm.run(quantum_instance)

            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)
        except NameError as ex:
            self.skipTest(str(ex))
示例#2
0
    def test_qsvm_multiclass_all_pairs(self, use_circuits):
        """ QSVM Multiclass All Pairs test """
        training_input = {'A': np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296],
                                           [0.8690704, 0.70847635]]),
                          'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951],
                                           [0.49156185, -0.3660534]]),
                          'C': np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294],
                                           [-0.82139073, 0.29941512]])}

        test_input = {'A': np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544],
                                       [0.48142649, 0.15931707]]),
                      'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828],
                                       [0.06183066, -0.53376975]]),
                      'C': np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162],
                                       [-0.66489165, 0.1181712]])}

        total_array = np.concatenate((test_input['A'], test_input['B'], test_input['C']))

        aqua_globals.random_seed = self.random_seed
        feature_map = SecondOrderExpansion(feature_dimension=get_feature_dimension(training_input),
                                           depth=2,
                                           entangler_map=[[0, 1]])
        if use_circuits:
            x = ParameterVector('x', feature_map.feature_dimension)
            feature_map = feature_map.construct_circuit(x)
            feature_map.ordered_parameters = list(x)

        try:
            svm = QSVM(feature_map, training_input, test_input, total_array,
                       multiclass_extension=AllPairs())

            quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
                                               shots=self.shots,
                                               seed_simulator=aqua_globals.random_seed,
                                               seed_transpiler=aqua_globals.random_seed)
            result = svm.run(quantum_instance)
            self.assertAlmostEqual(result['testing_accuracy'], 0.444444444, places=4)
            self.assertEqual(result['predicted_classes'], ['A', 'A', 'C', 'A',
                                                           'A', 'A', 'A', 'C', 'C'])
        except NameError as ex:
            self.skipTest(str(ex))
示例#3
0
    def test_qsvm_binary_directly(self):

        ref_kernel_training = np.array([[1., 0.85366667, 0.12341667, 0.36408333],
                                        [0.85366667, 1., 0.11141667, 0.45491667],
                                        [0.12341667, 0.11141667, 1., 0.667],
                                        [0.36408333, 0.45491667, 0.667, 1.]])

        ref_kernel_testing = np.array([[0.14316667, 0.18208333, 0.4785, 0.14441667],
                                       [0.33608333, 0.3765, 0.02316667, 0.15858333]])

        # ref_alpha = np.array([0.36064489, 1.49204209, 0.0264953, 1.82619169])
        ref_alpha = np.array([0.34903335, 1.48325498, 0.03074852, 1.80153981])
        # ref_bias = np.array([-0.03380763])
        ref_bias = np.array([-0.03059226])

        ref_support_vectors = np.array([[2.95309709, 2.51327412], [3.14159265, 4.08407045],
                                        [4.08407045, 2.26194671], [4.46106157, 2.38761042]])

        aqua_globals.random_seed = self.random_seed
        backend = BasicAer.get_backend('qasm_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, shots=self.shots, seed=self.random_seed,
                                           seed_transpiler=self.random_seed)

        result = svm.run(quantum_instance)
        np.testing.assert_array_almost_equal(
            result['kernel_matrix_training'], ref_kernel_training, decimal=1)
        np.testing.assert_array_almost_equal(
            result['kernel_matrix_testing'], ref_kernel_testing, decimal=1)

        self.assertEqual(len(result['svm']['support_vectors']), 4)
        np.testing.assert_array_almost_equal(
            result['svm']['support_vectors'], ref_support_vectors, decimal=4)

        np.testing.assert_array_almost_equal(result['svm']['alphas'], ref_alpha, decimal=8)
        np.testing.assert_array_almost_equal(result['svm']['bias'], ref_bias, decimal=8)

        self.assertEqual(result['testing_accuracy'], 0.5)
示例#4
0
    def test_binary(self, mode):
        """Test QSVM on binary classification on BasicAer's QASM simulator."""
        if mode == 'circuit':
            data_preparation = QuantumCircuit(2).compose(self.data_preparation)
        else:
            data_preparation = self.data_preparation

        svm = QSVM(data_preparation,
                   self.training_data,
                   self.testing_data,
                   None,
                   lambda2=0)

        try:
            result = svm.run(self.qasm_simulator)
            np.testing.assert_array_almost_equal(
                result['kernel_matrix_training'],
                self.ref_kernel_training,
                decimal=1)
            np.testing.assert_array_almost_equal(
                result['kernel_matrix_testing'],
                self.ref_kernel_testing['qasm'],
                decimal=1)

            self.assertEqual(len(result['svm']['support_vectors']), 4)
            np.testing.assert_array_almost_equal(
                result['svm']['support_vectors'],
                self.ref_support_vectors,
                decimal=4)

            np.testing.assert_array_almost_equal(result['svm']['alphas'],
                                                 self.ref_alpha,
                                                 decimal=8)
            np.testing.assert_array_almost_equal(result['svm']['bias'],
                                                 self.ref_bias,
                                                 decimal=8)

            self.assertEqual(result['testing_accuracy'], 0.5)
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
示例#5
0
    def test_qsvm_setup_data(self):
        """ QSVM Setup Data 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]])
        try:
            svm = QSVM(feature_map)

            svm.setup_training_data(self.training_data)
            svm.setup_test_data(self.testing_data)
            quantum_instance = QuantumInstance(
                backend,
                seed_transpiler=self.random_seed,
                seed_simulator=self.random_seed)
            result = svm.run(quantum_instance)

            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)
        except NameError as ex:
            self.skipTest(str(ex))
示例#6
0
    def test_qsvm_multiclass_error_correcting_code(self, data_preparation_type):
        """ QSVM Multiclass error Correcting Code test """
        training_input = {'A': np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296],
                                           [0.8690704, 0.70847635]]),
                          'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951],
                                           [0.49156185, -0.3660534]]),
                          'C': np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294],
                                           [-0.82139073, 0.29941512]])}

        test_input = {'A': np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544],
                                       [0.48142649, 0.15931707]]),
                      'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828],
                                       [0.06183066, -0.53376975]]),
                      'C': np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162],
                                       [-0.66489165, 0.1181712]])}

        total_array = np.concatenate((test_input['A'], test_input['B'], test_input['C']))

        aqua_globals.random_seed = self.random_seed
        data_preparation = self.data_preparation[data_preparation_type]
        try:
            if data_preparation_type == 'wrapped':
                warnings.filterwarnings('ignore', category=DeprecationWarning)
            svm = QSVM(data_preparation, training_input, test_input, total_array,
                       multiclass_extension=ErrorCorrectingCode(code_size=5))
            if data_preparation_type == 'wrapped':
                warnings.filterwarnings('always', category=DeprecationWarning)

            quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
                                               shots=self.shots,
                                               seed_simulator=aqua_globals.random_seed,
                                               seed_transpiler=aqua_globals.random_seed)
            result = svm.run(quantum_instance)
            self.assertAlmostEqual(result['testing_accuracy'], 0.444444444, places=4)
            self.assertEqual(result['predicted_classes'], ['A', 'A', 'C', 'A',
                                                           'A', 'A', 'A', 'C', 'C'])
        except NameError as ex:
            self.skipTest(str(ex))
示例#7
0
    def test_setup_data(self):
        """Test the setup_*_data methods of QSVM."""
        data_preparation = self.data_preparation
        try:
            svm = QSVM(data_preparation)

            svm.setup_training_data(self.training_data)
            svm.setup_test_data(self.testing_data)
            result = svm.run(self.statevector_simulator)

            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)
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
print(class_to_label)

seed = 10598

feature_map = ZZFeatureMap(feature_dimension=feature_dim,
                           reps=2,
                           entanglement='linear')
qsvm = QSVM(feature_map, training_input, test_input, datapoints[0])

backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend,
                                   shots=1024,
                                   seed_simulator=seed,
                                   seed_transpiler=seed)

result = qsvm.run(quantum_instance)

print("testing success ratio: {}".format(result['testing_accuracy']))
print("preduction of datapoints:")
print("ground truth: {}".format(
    map_label_to_class_name(datapoints[1], qsvm.label_to_class)))
print("prediction:   {}".format(result['predicted_classes']))

print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),
                 interpolation='nearest',
                 origin='upper',
                 cmap='bone_r')
plt.show()
示例#9
0
    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)
        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)

        file_path = self._get_resource_path('qsvm_test.npz')
        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)

        if os.path.exists(file_path):
            try:
                os.remove(file_path)
            except Exception:  # pylint: disable=broad-except
                pass
backend = provider.get_backend(
    'ibmq_qasm_simulator')  # Specifying Quantum device

num_qubits = 1

feature_map = SecondOrderExpansion(feature_dimension=num_qubits,
                                   depth=2,
                                   entanglement='full')

svm = QSVM(feature_map, training_data, testing_data)  # Creation of QSVM

quantum_instance = QuantumInstance(backend,
                                   shots=shots,
                                   skip_qobj_validation=False)

print('Running....\n')

result = svm.run(quantum_instance)  # Running the QSVM and getting the accuracy

data = np.array([[1.453], [1.023], [0.135], [0.266]])  #Unlabelled data

prediction = svm.predict(data,
                         quantum_instance)  # Predict using unlabelled data

print(
    'Prediction of Smoker or Non-Smoker based upon gene expression of CDKN2A\n'
)
print('Accuracy: ', result['testing_accuracy'], '\n')
print('Prediction from input data where 0 = Non-Smoker and 1 = Smoker\n')
print(prediction)
示例#11
0
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
示例#12
0
    def test_multiclass(self, multiclass_extension):
        """ QSVM Multiclass One Against All test """
        train_input = {
            'A':
            np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296],
                        [0.8690704, 0.70847635]]),
            'B':
            np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951],
                        [0.49156185, -0.3660534]]),
            'C':
            np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294],
                        [-0.82139073, 0.29941512]])
        }

        test_input = {
            'A':
            np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544],
                        [0.48142649, 0.15931707]]),
            'B':
            np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828],
                        [0.06183066, -0.53376975]]),
            'C':
            np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162],
                        [-0.66489165, 0.1181712]])
        }

        method = {
            'one_vs_all': OneAgainstRest(),
            'all_vs_all': AllPairs(),
            'error_correcting': ErrorCorrectingCode(code_size=5)
        }

        accuracy = {
            'one_vs_all': 0.444444444,
            'all_vs_all': 0.444444444,
            'error_correcting': 0.555555555
        }

        predicted_classes = {
            'one_vs_all': ['A', 'A', 'C', 'A', 'A', 'A', 'A', 'C', 'C'],
            'all_vs_all': ['A', 'A', 'C', 'A', 'A', 'A', 'A', 'C', 'C'],
            'error_correcting': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'C']
        }

        total_array = np.concatenate(
            (test_input['A'], test_input['B'], test_input['C']))

        data_preparation = self.data_preparation
        try:
            svm = QSVM(data_preparation,
                       train_input,
                       test_input,
                       total_array,
                       multiclass_extension=method[multiclass_extension])
            result = svm.run(self.qasm_simulator)
            self.assertAlmostEqual(result['testing_accuracy'],
                                   accuracy[multiclass_extension],
                                   places=4)
            self.assertEqual(result['predicted_classes'],
                             predicted_classes[multiclass_extension])
        except MissingOptionalLibraryError as ex:
            self.skipTest(str(ex))
示例#13
0
    def test_qsvm_binary_directly_statevector(self, data_preparation_type):
        """ 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')
        data_preparation = self.data_preparation[data_preparation_type]
        if data_preparation_type == 'wrapped':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
        svm = QSVM(data_preparation, self.training_data, self.testing_data, None)
        if data_preparation_type == 'wrapped':
            warnings.filterwarnings('always', category=DeprecationWarning)
        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
示例#14
0
    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,
                   lambda2=0)

        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