Ejemplo n.º 1
0
    def construct_kernel_matrix(self, x1_vec, x2_vec=None):
        """
        Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted.

        Args:
            x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data,
                                    D is the feature dimension
            x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data,
                                    D is the feature dimension

        Returns:
            numpy.ndarray: 2-D matrix, N1xN2
        """
        if x2_vec is None:
            is_symmetric = True
            x2_vec = x1_vec
        else:
            is_symmetric = False

        is_statevector_sim = QuantumAlgorithm.is_statevector_backend(
            self.qalgo.backend)

        measurement_basis = '0' * self.num_qubits
        circuits = {}
        to_be_simulated_circuits = []
        for i in np.arange(0, x1_vec.shape[0]):
            for j in np.arange(i + 1 if is_symmetric else 0, x2_vec.shape[0]):
                x1 = x1_vec[i]
                x2 = x2_vec[j]
                circuit = None if np.all(x1 == x2) else self.inner_product(
                    x1, x2, not is_statevector_sim)
                circuits["{}:{}".format(i, j)] = circuit
                if circuit is not None:
                    to_be_simulated_circuits.append(circuit)

        results = self.qalgo.execute(to_be_simulated_circuits)

        # element on the diagonal is always 1: point*point=|point|^2
        if is_symmetric:
            mat = np.eye(x1_vec.shape[0])
        else:
            mat = np.zeros((x1_vec.shape[0], x2_vec.shape[0]))
        for idx, circuit in circuits.items():
            i, j = [int(x) for x in idx.split(":")]
            if circuit is None:
                kernel_value = 1.0
            else:
                if is_statevector_sim:
                    temp = np.asarray(results.get_statevector(circuit))[0]
                    #  |<0|Psi^daggar(y) x Psi(x)|0>|^2,
                    kernel_value = np.dot(temp.T.conj(), temp).real
                else:
                    result = results.get_counts(circuit)
                    kernel_value = result.get(measurement_basis, 0) / \
                        self.qalgo._execute_config['shots']
            mat[i, j] = kernel_value
            if is_symmetric:
                mat[j, i] = mat[i, j]

        return mat
Ejemplo n.º 2
0
    def init_args(self,
                  operator,
                  operator_mode,
                  var_form,
                  optimizer,
                  opt_init_point=None,
                  batch_mode=False,
                  aux_operators=[]):
        """
        Args:
            operator (Operator): Qubit operator
            operator_mode (str): operator mode, used for eval of operator
            var_form (VariationalForm) : parametrized variational form.
            optimizer (Optimizer) : the classical optimization algorithm.
            opt_init_point (numpy.ndarray) : optimizer initial point.
            aux_operators ([Operator]): Auxiliary operators to be evaluated at each eigenvalue
        """

        if not QuantumAlgorithm.is_statevector_backend(
                self.backend) and operator_mode == 'matrix':
            logger.warning(
                'Qasm simulation does not work on {} mode, changing \
                           the operator_mode to paulis'.format(operator_mode))
            operator_mode = 'paulis'

        self._operator = operator
        self._operator_mode = operator_mode
        self._var_form = var_form
        self._optimizer = optimizer
        self._opt_init_point = opt_init_point
        self._aux_operators = aux_operators
        self._ret = {}
        if opt_init_point is None:
            self._opt_init_point = var_form.preferred_init_points
        self._optimizer.set_batch_mode(batch_mode)
Ejemplo n.º 3
0
    def train(self, data, labels):
        """
        train the svm
        Args:
            data (numpy.ndarray): NxD array, where N is the number of data,
                                  D is the feature dimension.
            labels (numpy.ndarray): Nx1 array, where N is the number of data
        """
        scaling = 1.0 if QuantumAlgorithm.is_statevector_backend(
            self.qalgo.backend) else None
        kernel_matrix = self.construct_kernel_matrix(data)
        labels = labels * 2 - 1  # map label from 0 --> -1 and 1 --> 1
        labels = labels.astype(np.float)
        [alpha, b, support] = optimize_svm(kernel_matrix,
                                           labels,
                                           scaling=scaling)
        support_index = np.where(support)
        alphas = alpha[support_index]
        svms = data[support_index]
        yin = labels[support_index]

        self._ret['kernel_matrix_training'] = kernel_matrix
        self._ret['svm'] = {}
        self._ret['svm']['alphas'] = alphas
        self._ret['svm']['bias'] = b
        self._ret['svm']['support_vectors'] = svms
        self._ret['svm']['yin'] = yin
Ejemplo n.º 4
0
 def _get_available_backends(self):
     try:
         self._available_backends = QuantumAlgorithm.register_and_get_operational_backends(
         )
     except Exception as e:
         logger.debug(str(e))
     finally:
         self._backendsthread = None
Ejemplo n.º 5
0
 def init_args(self, oracle, incremental=False, num_iterations=1):
     if QuantumAlgorithm.is_statevector_backend(self.backend):
         raise ValueError(
             'Selected backend  "{}" does not support measurements.'.format(
                 QuantumAlgorithm.backend_name(self.backend)))
     self._oracle = oracle
     self._max_num_iterations = 2**(len(self._oracle.variable_register()) /
                                    2)
     self._incremental = incremental
     self._num_iterations = num_iterations
     if incremental:
         logger.debug(
             'Incremental mode specified, ignoring "num_iterations".')
     else:
         if num_iterations > self._max_num_iterations:
             logger.warning(
                 'The specified value {} for "num_iterations" might be too high.'
                 .format(num_iterations))
Ejemplo n.º 6
0
    def init_args(self, training_dataset, test_dataset, datapoints, optimizer,
                  feature_map, var_form):
        """Initialize the object
        Args:
            training_dataset (dict): {'A': numpy.ndarray, 'B': numpy.ndarray, ...}
            test_dataset (dict): the same format as `training_dataset`
            datapoints (numpy.ndarray): NxD array, N is the number of data and D is data dimension
            optimizer (Optimizer): Optimizer instance
            feature_map (FeatureMap): FeatureMap instance
            var_form (VariationalForm): VariationalForm instance
        Notes:
            We used `label` denotes numeric results and `class` means the name of that class (str).
        """

        if QuantumAlgorithm.is_statevector_backend(self.backend):
            raise ValueError('Selected backend  "{}" is not supported.'.format(
                QuantumAlgorithm.backend_name(self.backend)))

        if training_dataset is None:
            raise AlgorithmError('Training dataset must be provided')

        self._training_dataset, self._class_to_label = split_dataset_to_data_and_labels(
            training_dataset)
        if test_dataset is not None:
            self._test_dataset = split_dataset_to_data_and_labels(
                test_dataset, self._class_to_label)

        self._label_to_class = {
            label: class_name
            for class_name, label in self._class_to_label.items()
        }
        self._num_classes = len(list(self._class_to_label.keys()))

        self._datapoints = datapoints
        self._optimizer = optimizer
        self._feature_map = feature_map
        self._var_form = var_form
        self._num_qubits = self._feature_map.num_qubits
Ejemplo n.º 7
0
 def init_args(self, operator, state_in, num_time_slices, num_iterations,
               paulis_grouping='default', expansion_mode='trotter', expansion_order=1,
               shallow_circuit_concat=False):
     if QuantumAlgorithm.is_statevector_backend(self.backend):
         raise ValueError('Selected backend does not support measurements.')
     self._operator = operator
     self._state_in = state_in
     self._num_time_slices = num_time_slices
     self._num_iterations = num_iterations
     self._paulis_grouping = paulis_grouping
     self._expansion_mode = expansion_mode
     self._expansion_order = expansion_order
     self._shallow_circuit_concat = shallow_circuit_concat
     self._ret = {}
Ejemplo n.º 8
0
 def _get_available_backends(self):
     try:
         qconfig = get_qconfig() 
         if qconfig is None or \
             qconfig.APItoken is None or \
             len(qconfig.APItoken) == 0 or \
             'url' not in qconfig.config:
             qconfig = None
 
         self._available_backends = QuantumAlgorithm.register_and_get_operational_backends(qconfig)
     except Exception as e:
         logger.debug(str(e))
     finally:
         self._backendsthread = None
Ejemplo n.º 9
0
 def _solve(self):
     opt_params, opt_val = self.find_minimum_eigenvalue()
     self._ret['eigvals'] = np.asarray([opt_val])
     self._ret['opt_params'] = opt_params
     qc = self._var_form.construct_circuit(self._ret['opt_params'])
     if QuantumAlgorithm.is_statevector_backend(self.backend):
         ret = self.execute(qc)
         self._ret['eigvecs'] = np.asarray([ret.get_statevector(qc)])
     else:
         c = ClassicalRegister(self._operator.num_qubits, name='c')
         q = qc.get_qregs()['q']
         qc.add(c)
         qc.measure(q, c)
         ret = self.execute(qc)
         self._ret['eigvecs'] = np.asarray([ret.get_counts(qc)])