Exemplo n.º 1
0
    def decision_function(self, X):
        """
        predicted values for the points which account for both the labels and the confidence
        Args:
            X (numpy.ndarray): input points
        """

        alphas = self._ret['svm']['alphas']
        bias = self._ret['svm']['bias']
        SVMs = self._ret['svm']['support_vectors']
        yin = self._ret['svm']['yin']

        kernel_matrix = kernel_join(X, SVMs, self.entangler_map,
                                    self.coupling_map, self.initial_layout,
                                    self.shots, self._random_seed,
                                    self.num_of_qubits, self._backend)

        total_num_points = len(X)
        Lsign = np.zeros(total_num_points)
        for tin in range(total_num_points):
            Ltot = 0
            for sin in range(len(SVMs)):
                L = yin[sin] * alphas[sin] * kernel_matrix[tin][sin]
                Ltot += L
            Lsign[tin] = Ltot + bias

        return Lsign
Exemplo n.º 2
0
    def predict(self, test_points):
        """
        predict using the svm
        Args:
            test_points (numpy.ndarray): the points
        """
        alphas = self.ret['svm']['alphas']
        bias = self.ret['svm']['bias']
        SVMs = self.ret['svm']['support_vectors']
        yin = self.ret['svm']['yin']

        kernel_matrix = kernel_join(test_points, SVMs, self.entangler_map, self.coupling_map,
                                    self.initial_layout, self.shots, self._random_seed,
                                    self.num_of_qubits, self._backend)

        self.ret['kernel_matrix_prediction'] = kernel_matrix

        total_num_points = len(test_points)
        Lsign = np.zeros(total_num_points)
        for tin in range(total_num_points):
            Ltot = 0
            for sin in range(len(SVMs)):
                L = yin[sin] * alphas[sin] * kernel_matrix[tin][sin]
                Ltot += L
            Lsign[tin] = np.int(np.sign(Ltot + bias))
        return Lsign
Exemplo n.º 3
0
    def train(self, training_input, class_labels):
        """
        train the svm
        Args:
            training_input (dict): dictionary which maps each class to the points in the class
            class_labels (list): list of classes. For example: ['A', 'B']
        """
        training_points, training_points_labels, label_to_class = get_points_and_labels(training_input, class_labels)

        kernel_matrix = kernel_join(training_points, training_points, self.entangler_map,
                                    self.coupling_map, self.initial_layout, self.shots,
                                    self._random_seed, self.num_of_qubits, self._backend)

        self.ret['kernel_matrix_training'] = kernel_matrix

        [alpha, b, support] = optimize_SVM(kernel_matrix, training_points_labels)
        alphas = np.array([])
        SVMs = np.array([])
        yin = np.array([])
        for alphindex in range(len(support)):
            if support[alphindex]:
                alphas = np.vstack([alphas, alpha[alphindex]]) if alphas.size else alpha[alphindex]
                SVMs = np.vstack([SVMs, training_points[alphindex]]) if SVMs.size else training_points[alphindex]
                yin = np.vstack([yin, training_points_labels[alphindex]]
                                ) if yin.size else training_points_labels[alphindex]

        self.ret['svm'] = {}
        self.ret['svm']['alphas'] = alphas
        self.ret['svm']['bias'] = b
        self.ret['svm']['support_vectors'] = SVMs
        self.ret['svm']['yin'] = yin
Exemplo n.º 4
0
    def test(self, test_input, class_labels):
        """
        test the svm
        Args:
            test_input (dict): dictionary which maps each class to the points in the class
            class_labels (list): list of classes. For example: ['A', 'B']
        """

        test_points, test_points_labels, label_to_labelclass = get_points_and_labels(test_input, class_labels)

        alphas = self.ret['svm']['alphas']
        bias = self.ret['svm']['bias']
        SVMs = self.ret['svm']['support_vectors']
        yin = self.ret['svm']['yin']

        kernel_matrix = kernel_join(test_points, SVMs, self.entangler_map, self.coupling_map,
                                    self.initial_layout, self.shots, self._random_seed,
                                    self.num_of_qubits, self._backend)

        self.ret['kernel_matrix_testing'] = kernel_matrix

        success_ratio = 0
        L = 0
        total_num_points = len(test_points)
        Lsign = np.zeros(total_num_points)
        for tin in range(total_num_points):
            Ltot = 0
            for sin in range(len(SVMs)):
                L = yin[sin] * alphas[sin] * kernel_matrix[tin][sin]
                Ltot += L

            Lsign[tin] = np.sign(Ltot + bias)



            logger.debug("\n=============================================")
            logger.debug('classifying' + str(test_points[tin]))
            logger.debug('Label should be ' + str(label_to_labelclass[np.int(test_points_labels[tin])]))
            logger.debug('Predicted label is ' + str(label_to_labelclass[np.int(Lsign[tin])]))
            if np.int(test_points_labels[tin]) == np.int(Lsign[tin]):
                logger.debug('CORRECT')
            else:
                logger.debug('INCORRECT')

            if Lsign[tin] == test_points_labels[tin]:
                success_ratio += 1
        final_success_ratio = success_ratio / total_num_points

        logger.debug('Classification success for this set is %s %% \n' % (100 * final_success_ratio))
        return final_success_ratio
Exemplo n.º 5
0
    def fit(self, X, y):
        """
        fit values for the points and the labels
        Args:
            X (numpy.ndarray): input points
            y (numpy.ndarray): input labels
        """
        y = y.astype(float)

        self.class_labels = np.unique(y)
        if len(self.class_labels) == 1:
            raise ValueError(" can not be fit when only one"
                             " class is present.")

        self.num_of_qubits = X.shape[1]
        self.entangler_map = entangler_map_creator(self.num_of_qubits)
        self.coupling_map = None
        self.initial_layout = None
        if self._backend is None:
            self._backend = 'local_qasm_simulator'
        if self.shots is None:
            self.shots = 1000

        kernel_matrix = kernel_join(X, X, self.entangler_map,
                                    self.coupling_map, self.initial_layout,
                                    self.shots, self._random_seed,
                                    self.num_of_qubits, self._backend)

        [alpha, b, support] = optimize_SVM(kernel_matrix, y)
        alphas = np.array([])
        SVMs = np.array([])
        yin = np.array([])
        for alphindex in range(len(support)):
            if support[alphindex]:
                alphas = np.vstack([alphas, alpha[alphindex]
                                    ]) if alphas.size else alpha[alphindex]
                SVMs = np.vstack([SVMs, X[alphindex]
                                  ]) if SVMs.size else X[alphindex]
                yin = np.vstack([yin, y[alphindex]
                                 ]) if yin.size else y[alphindex]

        self._ret['svm'] = {}
        self._ret['svm']['alphas'] = alphas
        self._ret['svm']['bias'] = b
        self._ret['svm']['support_vectors'] = SVMs
        self._ret['svm']['yin'] = yin