Пример #1
0
    def test_qsvm_multiclass_all_pairs(self):
        """ 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]])
        svm = QSVM(feature_map, training_input, test_input, total_array,
                   multiclass_extension=AllPairs(_QSVM_Estimator, [feature_map]))

        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'])
Пример #2
0
    def test_qsvm_multiclass_all_pairs(self, data_preparation_type):
        """ 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
        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=AllPairs())
            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))
Пример #3
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], lambda2=0)
            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))
temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)

try:
    aqua_globals.random_seed = 10598

    backend = BasicAer.get_backend('qasm_simulator')
    feature_map = ZZFeatureMap(
        feature_dimension=get_feature_dimension(training_input),
        reps=2,
        entanglement='linear')
    svm = QSVM(feature_map,
               training_input,
               test_input,
               total_array,
               multiclass_extension=AllPairs())
    quantum_instance = QuantumInstance(
        backend,
        shots=1024,
        seed_simulator=aqua_globals.random_seed,
        seed_transpiler=aqua_globals.random_seed)

    result = svm.run(quantum_instance)
    for k, v in result.items():
        print(f'{k} : {v}')
except Exception as e:
    print('QSVM error', e)

# feature_dim = np.shape(X)[1]
#
# # Train test split
Пример #5
0
    def test_multiclass_all_pairs(self):
        """ multiclass all pairs test """
        training_input = {
            'A':
            np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296],
                        [0.79687342, 0.26933706], [0.39016555, -0.08469916],
                        [0.3994399, 0.13601573], [0.26752049, -0.03978988],
                        [0.24026485, 0.01953518], [0.49490503, 0.17239737],
                        [0.70171827, 0.5323737], [0.43221576, 0.42357294],
                        [0.62864856, 0.45504447], [0.6259567, 0.30917324],
                        [0.58272403, 0.20760754], [0.3938784, 0.17184466],
                        [0.14154948, 0.06201424], [0.80202323, 0.40582692],
                        [0.46779595, 0.39946754], [0.57660199, 0.21821317],
                        [0.51044761, 0.03699459], [0.8690704, 0.70847635]]),
            'B':
            np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951],
                        [-0.30119743, -0.11221681], [-0.16479252, -0.08640519],
                        [-0.21808884, -0.56508327], [-0.14683258, -0.46528508],
                        [-0.05888195, -0.51474852], [0.20517435, -0.66839091],
                        [0.25475584, -0.21239966], [0.55194854, 0.02789679],
                        [-0.11542951, -0.54157026], [0.44625538, -0.49485869],
                        [-0.14609118, -0.60719757], [0.18121305, -0.1922198],
                        [0.19283785, -0.31798925], [0.29626405, -0.54563098],
                        [-0.39044304, -0.36527253], [-0.29432215, -0.43924164],
                        [-0.40294517, -0.31381308], [0.49156185, -0.3660534]]),
            'C':
            np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294],
                        [-0.54323753, 0.67630888], [-0.57685569, -0.08515631],
                        [-0.67765364, 0.19654347], [-0.62129115, 0.22223066],
                        [-0.78040851, 0.65247848], [-0.50730279, 0.59898039],
                        [-0.64275805, 0.63381998], [-0.72854201, 0.14151325],
                        [-0.57004437, 0.12344874], [-0.55215973, 0.74331215],
                        [-0.60916047, 0.52006917], [-0.23093745, 1.],
                        [-0.84025337, 0.5564536], [-0.66952391, 0.57918859],
                        [-0.67725082, 0.60439934], [-1., 0.23715261],
                        [-0.62933025, 0.19055405], [-0.82139073, 0.29941512]])
        }

        test_input = {
            'A':
            np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544],
                        [0.08791134, 0.11515506], [0.45988094, 0.32854319],
                        [0.53015085, 0.41539212], [0.5073321, 0.47346751],
                        [0.71081819, 0.19202569], [1., 0.51698289],
                        [0.630973, 0.19898666], [0.48142649, 0.15931707]]),
            'B':
            np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828],
                        [-0.17323832, -0.49535592], [0.14043268, -0.87869109],
                        [-0.15046837, -0.47340207], [-0.39600934, -0.21647957],
                        [-0.394202, -0.44705385], [0.15243621, -0.36695163],
                        [0.06195634, -0.23262325], [0.06183066, -0.53376975]]),
            'C':
            np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162],
                        [-0.52649891, 0.35265538], [-0.54345106, 0.13113995],
                        [-0.57181448, 0.13594725], [-0.33713329, 0.05095243],
                        [-0.65741384, 0.477976], [-0.79986067, 0.41733195],
                        [-0.73856328, 0.80699537], [-0.66489165, 0.1181712]])
        }

        temp = [test_input[k] for k in sorted(test_input)]
        total_array = np.concatenate(temp)

        result = SklearnSVM(training_input,
                            test_input,
                            total_array,
                            multiclass_extension=AllPairs()).run()

        self.assertEqual(result['testing_accuracy'], 1.0)
        self.assertEqual(result['predicted_classes'], [
            'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B',
            'B', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C',
            'C', 'C', 'C', 'C'
        ])
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from qiskit.aqua.algorithms import SklearnSVM
from qiskit.aqua.components.multiclass_extensions import (OneAgainstRest,
                                                          AllPairs,
                                                          ErrorCorrectingCode)


feature_dim = 2  # dimension of each data point
sample_Total, training_input, test_input, class_labels = wine(training_size=20,
                                                              test_size=10, n=feature_dim, plot_data=True)

temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)


extensions = [ OneAgainstRest(),
               AllPairs(),
               ErrorCorrectingCode(code_size=5) ]

for extension in extensions:
    result = SklearnSVM(training_input, test_input, total_array, multiclass_extension=extension).run()
    print("\n----- Using multiclass extension: '{}' -----\n".format(extension.__class__.__name__))
    for k,v in result.items():
        print("'{}' : {}".format(k, v))



# 'testing_accuracy' : 1.0

# sumber = https://github.com/qiskit-community/qiskit-community-tutorials/blob/master/machine_learning/svm_classical_multiclass.ipynb
Пример #7
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