Exemple #1
0
    def test_binary(self, mode):
        """Test QSVM on binary classification on BasicAer's QASM simulator."""
        if mode == 'component':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            # data encoding using a FeatureMap type
            data_preparation = SecondOrderExpansion(feature_dimension=2,
                                                    depth=2,
                                                    entangler_map=[[0, 1]])
        elif 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)
        if mode == 'component':
            warnings.filterwarnings('always', category=DeprecationWarning)

        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 NameError as ex:
            self.skipTest(str(ex))
Exemple #2
0
    def test_qsvm_multiclass_error_correcting_code(self):
        """ 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
        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=ErrorCorrectingCode(_QSVM_Estimator,
                                                            [feature_map], code_size=5))

        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'])
Exemple #3
0
    def test_qsvm_binary(self, data_preparation_type):
        """ QSVM Binary test """
        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]])

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

        try:
            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)
        except NameError as ex:
            self.skipTest(str(ex))
Exemple #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))
Exemple #5
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)
        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
Exemple #6
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)

        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
Exemple #7
0
    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)
Exemple #8
0
    def test_qsvm_binary(self):
        """ QSVM Binary test """
        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]])

        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_simulator=self.random_seed,
                                           seed_transpiler=self.random_seed)
        try:
            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)
        except NameError as ex:
            self.skipTest(str(ex))
Exemple #9
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.555555555,
                                   places=4)
            self.assertEqual(result['predicted_classes'],
                             ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'C'])
        except NameError as ex:
            self.skipTest(str(ex))
Exemple #10
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))
Exemple #11
0
    def train_model(self):
        backend = Aer.get_backend('qasm_simulator')
        feature_expansion = SecondOrderExpansion(
            feature_dimension=self.feature_dim,
            depth=self.feature_depth,
            entangler_map=[[0, 1]])
        #feature_expansion = FirstOrderExpansion(feature_dimension=self.feature_dim)

        # Model definition
        svm = QSVM(feature_expansion, self.train, self.test)
        #svm.random_seed = self.seed
        q_inst = QuantumInstance(backend, shots=self.copies)

        # Train the SVM
        result = svm.run(q_inst)
        return svm, result
Exemple #12
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]])

        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)
Exemple #13
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))
    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))
Exemple #15
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))
test = np.append(X_test, y_test, axis=1)

train = pd.DataFrame(data=train[:, :])
test = pd.DataFrame(data=test[:, :])
train = train.sample(frac=1).reset_index(drop=True)
test = test.sample(frac=1).reset_index(drop=True)
train = {k: np.asarray(g.iloc[:, :-1]) for k, g in train.groupby(10)}
test = {k: np.asarray(g.iloc[:, :-1]) for k, g in test.groupby(10)}

backend = BasicAer.get_backend('qasm_simulator')

#IBMQ.enable_account(HERE)
#provider = IBMQ.get_provider(hub='ibm-q')
#backend = provider.get_backend('ibmq_16_melbourne') # Specifying Quantum device

seed = 11111
feature_dim = 10
feature_map = ZZFeatureMap(feature_dimension=feature_dim,
                           reps=2,
                           entanglement='linear')
qsvm = QSVM(feature_map, train, test)

quantum_instance = QuantumInstance(backend,
                                   shots=1024,
                                   seed_simulator=seed,
                                   seed_transpiler=seed,
                                   skip_qobj_validation=False)

result = qsvm.run(quantum_instance)
print("Quantum accuracy on test set: {0}%".format(
    round(result['testing_accuracy'] * 100, 2)))
Exemple #17
0
testing_dataset_size = 10
random_seed = 10598
shots = 1024

sample_Total, training_input, test_input, class_labels = ad_hoc_data(
    training_size=training_dataset_size,
    test_size=testing_dataset_size,
    n=feature_dim, gap=0.3, plot_data=False
)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
print(class_to_label)


backend = BasicAer.get_backend('qasm_simulator')
feature_map = ZZFeatureMap(feature_dim, reps=2)
svm = QSVM(feature_map, training_input, test_input, None)# the data for prediction can be fed later.
svm.random_seed = random_seed
quantum_instance = QuantumInstance(backend, shots=shots, seed_simulator=random_seed, seed_transpiler=random_seed)
result = svm.run(quantum_instance)


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()

print("testing success ratio: ", result['testing_accuracy'])


predicted_labels = svm.predict(datapoints[0])
    'B': np.asarray([[1.777], [1.341], [1.514], [1.204], [1.135]])
}

IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')

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(
feature_dim = 2
sample_total, training_input, test_input, class_labels = ad_hoc_data(
    training_size=50,
    test_size=10,
    n=feature_dim,
    gap=0.3,
    # plot_data=True
    plot_data=False)
extra_test_data = sample_ad_hoc_data(sample_total, 10, n=feature_dim)
datapoints, class_to_label = split_dataset_to_data_and_labels(extra_test_data)
print(class_to_label)

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(f'Testing success ratio: {result["testing_accuracy"]}')
print()
print('Prediction from datapoints set:')
print(
    f'  ground truth: {map_label_to_class_name(datapoints[1], qsvm.label_to_class)}'
)
Exemple #20
0
    array_train = []
    array_test= []
    for i in (range(len(training_input[key]))):
        if (i%2==0):
            array_train += [training_input[key][i]]
        else:
            array_test += [training_input[key][i]]
    new_training_input.update({key: array_train})
    new_test_input.update({key: array_train})

multi_ext_classical = OneAgainstRest(_RBF_SVC_Estimator)
svm = SVM_Classical(new_training_input, new_test_input, multiclass_extension=multi_ext_classical)

feature_map = PauliExpansion(feature_dimension=feature_dim, depth=2, paulis=['Z', 'ZZ'], entanglement='linear')
multi_ext_quantum = OneAgainstRest(_QSVM_Estimator, [feature_map])
qsvm = QSVM(feature_map, new_training_input, new_test_input, multiclass_extension=multi_ext_quantum)

seed = 1001
backend = Aer.get_backend('qasm_simulator')
#device = IBMQ.get_provider().get_backend('ibmqx2')
classical_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_transpiler=seed)
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_transpiler=seed, circuit_caching=False, skip_qobj_validation=False)

#start_classical = timeit.default_timer()
#result_classical = svm.run(classical_instance)
#elapsed_classical = timeit.default_timer() - start_classical

start_quantum = timeit.default_timer()
result_quant = qsvm.run(quantum_instance)
elapsed_quantum = timeit.default_timer() - start_quantum
Exemple #21
0
}

if config['local']:
    config['server'] = 'qasm_simulator'
else:
    config['qbits'] = servers[config['server']]

data = json.load(open('data' + str(config['qbits']) + '.json', 'r'))

IBMQ.save_account(config['token'])
if config['local']:
    IBMQ.load_accounts(hub=None)
    feature_map = SecondOrderExpansion(feature_dimension=config['qbits'],
                                       depth=config['depth'],
                                       entanglement=config['entanglement'])
    qsvm = QSVM(feature_map, data["train"], data["test"])
    backend = BasicAer.get_backend(config['server'])
    quantum_instance = QuantumInstance(backend,
                                       shots=config['shots'],
                                       seed_transpiler=config['seed'])
    result = qsvm.run(quantum_instance)
    print(result)
else:
    IBMQ.load_accounts(hub=None)
    feature_map = SecondOrderExpansion(feature_dimension=config['qbits'],
                                       depth=config['depth'],
                                       entanglement=config['entanglement'])
    qsvm = QSVM(feature_map, data["train"], data["test"])
    provider = IBMQ.get_provider()
    backend = provider.get_backend(config['server'])
    quantum_instance = QuantumInstance(backend,
Exemple #22
0
    training_size=20, test_size=10, n=feature_dim, gap=0.3, plot_data=False)

# Using the statevector simulator
backend = BasicAer.get_backend('statevector_simulator')
random_seed = 10598

quantum_instance = QuantumInstance(backend,
                                   seed_simulator=random_seed,
                                   seed_transpiler=random_seed)

# Generate the feature map
feature_map = ZFeatureMap(feature_dimension=feature_dim, reps=2)

# Run the Quantum Kernel Estimator and classify the test data
qsvm = QSVM(feature_map=feature_map,
            training_dataset=training_dataset,
            test_dataset=test_dataset)

result = qsvm.run(quantum_instance)
print("testing success ratio: ", result['testing_accuracy'])

feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2)

qsvm = QSVM(feature_map=feature_map,
            training_dataset=training_dataset,
            test_dataset=test_dataset)

result = qsvm.run(quantum_instance)
print("testing success ratio: ", result['testing_accuracy'])

#Divide dataset into training and testing with a 7:3 ratio
p_train, p_test, notp_train, notp_test = train_test_split(p_now, notp, test_size=0.3, random_state=12)


#Combine training/testing arrays
training_data={'A': p_train, 'B': notp_train}
testing_data = {'A' : p_test, 'B': notp_test}


num_qubits=9


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


svm = QSVM(feature_map,training_data,testing_data)


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


#Run the QSVM for accuracy results
result = svm.run(quantum_instance)


#Unlabelled data
data = np.array([[0, 0.80766, 0.73961, 0.20569, 445, 444, 0.004334704, 2.43E-05, 0.00072],
[1, 0.83967, 0.80944, 0.45038, 259, 257, 0.007310325, 0.00251383, 0.00534],
[1, 0.81525, 0.73462, 0.64849, 303, 302, 0.006381791, 0.000149359, 0.00292],
[1, 0.79163, 0.80358, 0.43866, 330, 329, 0.005844644, 8.21E-05, 0.00278],
[0, 0.7594, 0.68265, 0.39428, 443, 442, 0.004354498, 6.69E-05, 0.00076],
# from qiskit import IBMQ
# provider = IBMQ.load_account()

feature_dim = 2  # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(
    training_size=20, test_size=10, n=feature_dim, gap=0.3, plot_data=True)
extra_test_data = sample_ad_hoc_data(sample_Total, 10, n=feature_dim)
datapoints, class_to_label = split_dataset_to_data_and_labels(extra_test_data)
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']))
Exemple #25
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