1
$\begingroup$

I'm not sure how to bind the parameters in the Qiskit RawFeatureVector circuit. Here is my code:

feature_map = RawFeatureVector(feature_dimension = num_features)
feature_map = feature_map.assign_parameters(np.array([1,1]) / np.sqrt(2))
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
svm = OneClassSVM(kernel = kernel.evaluate, verbose=True, nu=outliers_fraction)
svm.fit(X)

I am probably missing something very obvious, but I think I bound the parameters when I assigned the paramters. Now when I run this with some data, I get the following error traceback.

QiskitError                               Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8160/3101503440.py in <module>
      4     dataset_count = dataset_count + 1
      5     print("For dataset: {}".format(dataset_count))
----> 6     Algorithm2(X, y, 1, outliers_fraction=outliers_fraction)
      7     break

~\AppData\Local\Temp/ipykernel_8160/1216541068.py in Algorithm2(X, y, shots, outliers_fraction, num_features, seed, predict, supervised)
     17     if supervised:
     18         X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=seed)
---> 19         svm.fit(X_train, y_train)
     20         y_pred = svm.predict(X_test)
     21         # TODO save to Matrix

~\anaconda3\lib\site-packages\sklearn\svm\_classes.py in fit(self, X, y, sample_weight, **params)
   1374 
   1375         """
-> 1376         super().fit(X, np.ones(_num_samples(X)),
   1377                     sample_weight=sample_weight, **params)
   1378         self.offset_ = -self._intercept_

~\anaconda3\lib\site-packages\sklearn\svm\_base.py in fit(self, X, y, sample_weight)
    224 
    225         seed = rnd.randint(np.iinfo('i').max)
--> 226         fit(X, y, sample_weight, solver_type, kernel, random_seed=seed)
    227         # see comment on the other call to np.iinfo in this file
    228 

~\anaconda3\lib\site-packages\sklearn\svm\_base.py in _dense_fit(self, X, y, sample_weight, solver_type, kernel, random_seed)
    264             # TODO: add keyword copy to copy on demand
    265             self.__Xfit = X
--> 266             X = self._compute_kernel(X)
    267 
    268             if X.shape[0] != X.shape[1]:

~\anaconda3\lib\site-packages\sklearn\svm\_base.py in _compute_kernel(self, X)
    394             # in the case of precomputed kernel given as a function, we
    395             # have to compute explicitly the kernel matrix
--> 396             kernel = self.kernel(X, self.__Xfit)
    397             if sp.issparse(kernel):
    398                 kernel = kernel.toarray()

~\anaconda3\lib\site-packages\qiskit_machine_learning\kernels\fidelity_quantum_kernel.py in evaluate(self, x_vec, y_vec)
    119         if is_symmetric:
    120             left_parameters, right_parameters, indices = self._get_symmetric_parameterization(x_vec)
--> 121             kernel_matrix = self._get_symmetric_kernel_matrix(
    122                 kernel_shape, left_parameters, right_parameters, indices
    123             )

~\anaconda3\lib\site-packages\qiskit_machine_learning\kernels\fidelity_quantum_kernel.py in _get_symmetric_kernel_matrix(self, kernel_shape, left_parameters, right_parameters, indices)
    210         Given a set of parameterization, this computes the kernel matrix.
    211         """
--> 212         kernel_entries = self._get_kernel_entries(left_parameters, right_parameters)
    213         kernel_matrix = np.ones(kernel_shape)
    214 

~\anaconda3\lib\site-packages\qiskit_machine_learning\kernels\fidelity_quantum_kernel.py in _get_kernel_entries(self, left_parameters, right_parameters)
    232                 right_parameters,
    233             )
--> 234             kernel_entries = np.real(job.result().fidelities)
    235         else:
    236             # trivial case, only identical samples

~\anaconda3\lib\site-packages\qiskit\primitives\primitive_job.py in result(self)
     48         """Return the results of the job."""
     49         self._check_submitted()
---> 50         return self._future.result()
     51 
     52     def cancel(self):

~\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
    436                     raise CancelledError()
    437                 elif self._state == FINISHED:
--> 438                     return self.__get_result()
    439 
    440                 self._condition.wait(timeout)

~\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
    388         if self._exception:
    389             try:
--> 390                 raise self._exception
    391             finally:
    392                 # Break a reference cycle with the exception in self._exception

~\anaconda3\lib\concurrent\futures\thread.py in run(self)
     50 
     51         try:
---> 52             result = self.fn(*self.args, **self.kwargs)
     53         except BaseException as exc:
     54             self.future.set_exception(exc)

~\anaconda3\lib\site-packages\qiskit\algorithms\state_fidelities\compute_uncompute.py in _run(self, circuits_1, circuits_2, values_1, values_2, **options)
    126         """
    127 
--> 128         circuits = self._construct_circuits(circuits_1, circuits_2)
    129         if len(circuits) == 0:
    130             raise ValueError(

~\anaconda3\lib\site-packages\qiskit\algorithms\state_fidelities\base_state_fidelity.py in _construct_circuits(self, circuits_1, circuits_2)
    186                 parametrized_circuit_2 = circuit_2.assign_parameters(parameters_2)
    187 
--> 188                 circuit = self.create_fidelity_circuit(
    189                     parametrized_circuit_1, parametrized_circuit_2
    190                 )

~\anaconda3\lib\site-packages\qiskit\algorithms\state_fidelities\compute_uncompute.py in create_fidelity_circuit(self, circuit_1, circuit_2)
     91             circuit_2.remove_final_measurements()
     92 
---> 93         circuit = circuit_1.compose(circuit_2.inverse())
     94         circuit.measure_all()
     95         return circuit

~\anaconda3\lib\site-packages\qiskit\circuit\library\blueprintcircuit.py in inverse(self)
    132         if not self._is_built:
    133             self._build()
--> 134         return super().inverse()
    135 
    136     def __len__(self):

~\anaconda3\lib\site-packages\qiskit\circuit\quantumcircuit.py in inverse(self)
    605 
    606         for instruction in reversed(self._data):
--> 607             inverse_circ._append(instruction.replace(operation=instruction.operation.inverse()))
    608         return inverse_circ
    609 

~\anaconda3\lib\site-packages\qiskit\circuit\instruction.py in inverse(self)
    364                 and an inverse has not been implemented for it.
    365         """
--> 366         if self.definition is None:
    367             raise CircuitError("inverse() not implemented for %s." % self.name)
    368 

~\anaconda3\lib\site-packages\qiskit\circuit\instruction.py in definition(self)
    235         """Return definition in terms of other basic gates."""
    236         if self._definition is None:
--> 237             self._define()
    238         return self._definition
    239 

~\anaconda3\lib\site-packages\qiskit_machine_learning\circuit\library\raw_feature_vector.py in _define(self)
    168                 cleaned_params.append(complex(param))
    169             else:
--> 170                 raise QiskitError("Cannot define a ParameterizedInitialize with unbound parameters")
    171 
    172         # normalize

QiskitError: 'Cannot define a ParameterizedInitialize with unbound parameters'

Thanks in advance!

$\endgroup$
2
  • $\begingroup$ Are you sure the problem is with RawFeatureVector and not with X? The backtrace makes it looks like there is some problem parsing it. $\endgroup$ Nov 30, 2022 at 19:34
  • $\begingroup$ I don't think there is anything wrong with X, I tried it with the other Feature maps and it works fine there. Maybe I am missing something? $\endgroup$
    – welremco
    Dec 1, 2022 at 11:35

1 Answer 1

0
$\begingroup$

Well, I'm facing a similar problem while using the RealFeatureVector with NN and some optimizer. This is my interpretation: In both cases the circuit needs to be transpiled/decomposed to be evaluated in each context (in my case was to build a gradient of the circuit for the sake of the optimizer). However, the RealFeatureVector is different from any other feature-map; that is, the circuit can't be constructed till the parameters are bound. The gates are added in a specific way to achieve the required initialization value.

Accordingly, I would recommend to try the following: 1- Change assign_parameters to bind_parameters 2- I can't see you using any parameters, so you may use a normal QuantumCircuit and then initialize it by the desired values.

regards, Ahmed

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.