maiyuren / Quantum-Random-Forest

The model is based off the paper Srikumar et al., "A kernel-based quantum random forest for improved classification", (2022).
MIT License
9 stars 9 forks source link

Issue while training #1

Open bindulam opened 1 year ago

bindulam commented 1 year ago

hello,

I was trying to replicate your results, running into below error when I start training. can you please help?

Training tree 1 of 3 ------------------------------------------------------------

---Training sub-tree of depth: 1 (180 instances) 100%|██████████| 25/25 [00:02<00:00, 11.39it/s] 100%|██████████| 900/900 [01:03<00:00, 14.21it/s] Info gain: 0.4558 Accuracy for binary dataset: 0.1111 Number of SV: [32 31] ----> Selected SVM info gain: 0.4558

---Training sub-tree of depth: 2 (114 instances) 0%| | 0/25 [00:00<?, ?it/s]

TypeError Traceback (most recent call last) /usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, *kwds) 56 try: ---> 57 return bound(args, **kwds) 58 except TypeError:

TypeError: round() got an unexpected keyword argument 'decimals'

During handling of the above exception, another exception occurred:

AttributeError Traceback (most recent call last) AttributeError: 'Mul' object has no attribute 'rint'

The above exception was the direct cause of the following exception:

TypeError Traceback (most recent call last) 30 frames in 1 cores = 3 2 set_multiprocessing(False, cores) # Set to False if you don't want parallel computation ----> 3 qrf.train(training_set, 4 partition_sample_size=180)

/content/quantum_random_forest.py in train(self, data_df, epochs, partition_sample_size, pca_dim, **kwargs) 162 else: 163 kern_el_dict = None --> 164 qdt.train(data_df=data_df[i], kern_el_dict=kern_el_dict) 165 166 def predict(self, instances, return_unc=False, parallel=PARALLEL, calc_tree_corr=False, ret_pred_distr=False):

/content/quantum_decision_tree.py in train(self, data_df, criterion, return_qdt, kern_el_dict) 76 split_df_list = self.split_fn.train(data_df=data_df, split_type=self.dt_type, num_rand_gen=self.num_rand_gen, 77 ret_split_list=True, svm_num_train=svm_num_train, kern_el_dict=self.kern_el_dict) ---> 78 self.child_dts = [self._init_and_train_child(split_df) for split_df in split_df_list] 79 assert len(self.child_dts) == self.split_num, "Error in splitting children. " 80 except ImpossibleSVMTrainError:

/content/quantum_decision_tree.py in (.0) 76 split_df_list = self.split_fn.train(data_df=data_df, split_type=self.dt_type, num_rand_gen=self.num_rand_gen, 77 ret_split_list=True, svm_num_train=svm_num_train, kern_el_dict=self.kern_el_dict) ---> 78 self.child_dts = [self._init_and_train_child(split_df) for split_df in split_df_list] 79 assert len(self.child_dts) == self.split_num, "Error in splitting children. " 80 except ImpossibleSVMTrainError:

/content/quantum_decision_tree.py in _init_and_train_child(self, data_df) 93 94 child = self._init_child() ---> 95 child.train(data_df) 96 97 return child

/content/quantum_decision_tree.py in train(self, data_df, criterion, return_qdt, kern_el_dict) 74 svm_num_train = self.svm_num_train[self.depth - 1] # Note depth starts at 1 while index starts at 0 75 svm_num_train = len(data_df) if svm_num_train is not None and len(data_df) < svm_num_train else svm_num_train # Accounts for RP ---> 76 split_df_list = self.split_fn.train(data_df=data_df, split_type=self.dt_type, num_rand_gen=self.num_rand_gen, 77 ret_split_list=True, svm_num_train=svm_num_train, kern_el_dict=self.kern_el_dict) 78 self.child_dts = [self._init_and_train_child(split_df) for split_df in split_df_list]

/content/split_function.py in train(self, data_df, split_type, num_rand_gen, ret_split_list, svm_num_train, kern_el_dict) 102 self.pqc, childindxs = self.select_best_pqc(pqc_list=random_pqcs, data_df=data_df) 103 elif split_type == 'qke': --> 104 childindxs = self.select_best_svm_pqc(data_df, num_train=svm_num_train, num_rand_gen=num_rand_gen, 105 pqc_arch_type=self.branch_var, kern_el_dict=kern_el_dict) 106 else:

/content/split_function.py in select_best_svm_pqc(self, data_df, num_train, num_rand_gen, pqc_arch_type, kern_el_dict) 216 if self.nystrom: 217 self.reset_nystrom_transform() --> 218 self._svm_train(data_df, num_train=num_train, kern_el_dict=kern_el_dict) 219 indxs = self(data_df.X, kern_el_dict=kern_el_dict) 220 # print(indxs)

/content/split_function.py in _svm_train(self, data_df, num_train, kern_el_dict) 253 X = np.array(list(data_df.X.values)) 254 # Randomly chooses landmark points and constructs the Nystrom embedding. --> 255 X = self.feat_map_nystrom.fit_transform(X, kern_el_dict=kern_el_dict) 256 257 self.select_best_base_class_and_train(X, data_df)

/content/nystrom.py in fit_transform(self, X, kern_el_dict, gram_matrix) 49 50 def fit_transform(self, X, kern_el_dict=None, gram_matrix=None): ---> 51 self.fit(X, kern_el_dict=kern_el_dict, gram_matrix=gram_matrix) 52 self._prev_transform = self.transform(X, kern_el_dict=kern_el_dict, gram_matrix=gram_matrix) 53 return self._prev_transform

/content/nystrom.py in fit(self, X, kern_el_dict, gram_matrix) 26 27 if gram_matrix is None: ---> 28 basiskernel = self.kernel(self.basis, self.basis_, kern_el_dict=kern_el_dict) 29 else: 30 basis_kernel = gram_matrix[self.basisindxs]

/content/split_function.py in kernel(self, X1, X2, parallel, kern_el_dict) 124 pqc_out = _parallel_compute_kernel(X, self.pqc, cores=parallel, kern_el_dict=kern_el_dict) 125 else: --> 126 pqc_out = self.pqc(X, ret_prob_0=True, kern_el_dict=kern_el_dict) 127 128 K = np.array(pqc_out).reshape((len(X1), len(X2)))

/content/pqc.py in call(self, states, ret_prob_0, kern_el_dict) 56 """ This method runs the PQC and returns a real number for each state in the list of states. If ret_prob_0=True, 57 then the probability of the all 0 measurement is returned - for QKE. """ ---> 58 counts_list = self.get_counts(states, kern_el_dict=kern_el_dict) 59 if ret_prob_0: 60 return prob_0_from_counts_list(counts_list, self.pqc_sample_num)

/content/pqc.py in get_counts(self, states, kern_el_dict) 96 # The following conditions depend on the type of encoding 97 if self.embed is not False and 'as_params' in self.embed: ---> 98 run_circ = self.param_resolver(embed_as_params_vals=state) 99 results = self.device.run(run_circ, observed_q_label=self.observed_q_label, qubits=self.qubits) 100 elif self.embed:

/content/pqc.py in param_resolver(self, params, param_vals, circ, embed_as_params_vals) 131 else: 132 resolver = cirq.ParamResolver(c_param_dict) --> 133 return cirq.resolve_parameters(circ, resolver) 134 135 def gen_rand(self, num_gen, param_init_type='param_rand'):

/usr/local/lib/python3.8/dist-packages/cirq/protocols/resolve_parameters.py in resolve_parameters(val, param_resolver, recursive) 182 result = NotImplemented 183 else: --> 184 result = getter(param_resolver, recursive) 185 186 if result is not NotImplemented:

/usr/local/lib/python3.8/dist-packages/cirq/circuits/circuit.py in _resolveparameters(self, resolver, recursive) 1291 resolved_moments: List['cirq.Moment'] = [] 1292 for moment in self: -> 1293 resolved_moment = protocols.resolve_parameters(moment, resolver, recursive) 1294 if resolved_moment is not moment: 1295 changed = True

/usr/local/lib/python3.8/dist-packages/cirq/protocols/resolve_parameters.py in resolve_parameters(val, param_resolver, recursive) 182 result = NotImplemented 183 else: --> 184 result = getter(param_resolver, recursive) 185 186 if result is not NotImplemented:

/usr/local/lib/python3.8/dist-packages/cirq/circuits/moment.py in _resolveparameters(self, resolver, recursive) 252 for op in self: 253 resolved_op = protocols.resolve_parameters(op, resolver, recursive) --> 254 if resolved_op != op: 255 changed = True 256 resolved_ops.append(resolved_op)

/usr/local/lib/python3.8/dist-packages/cirq/value/value_equality_attr.py in _value_equality_ne(self, other) 83 84 def _value_equality_ne(self: _SupportsValueEquality, other: _SupportsValueEquality) -> bool: ---> 85 return not self == other 86 87

/usr/local/lib/python3.8/dist-packages/cirq/value/value_equality_attr.py in _value_equality_eq(self, other) 79 if cls_self != cls_other: 80 return False ---> 81 return self._value_equalityvalues() == other._value_equalityvalues() 82 83

/usr/local/lib/python3.8/dist-packages/cirq/value/value_equality_attr.py in _value_equality_eq(self, other) 79 if cls_self != cls_other: 80 return False ---> 81 return self._value_equalityvalues() == other._value_equalityvalues() 82 83

/usr/local/lib/python3.8/dist-packages/cirq/ops/eigen_gate.py in _value_equalityvalues(self) 319 320 def _value_equalityvalues(self): --> 321 return self._canonical_exponent, self._global_shift 322 323 def _value_equality_approximatevalues(self):

/usr/local/lib/python3.8/dist-packages/cirq/ops/eigen_gate.py in _canonical_exponent(self) 311 def _canonical_exponent(self): 312 if self._canonical_exponent_cached is None: --> 313 period = self._period() 314 if not period or protocols.is_parameterized(self._exponent): 315 self._canonical_exponent_cached = self._exponent

/usr/local/lib/python3.8/dist-packages/cirq/ops/eigen_gate.py in _period(self) 300 exponents = {e + self._global_shift for e in self._eigen_shifts()} 301 real_periods = [abs(2 / e) for e in exponents if e != 0] --> 302 return _approximate_common_period(real_periods) 303 304 def pow(self: TSelf, exponent: Union[float, sympy.Symbol]) -> 'EigenGate':

/usr/local/lib/python3.8/dist-packages/cirq/ops/eigen_gate.py in _approximate_common_period(periods, approx_denom, reject_atol) 440 if len(periods) == 1: 441 return abs(periods[0]) --> 442 approx_rational_periods = [ 443 fractions.Fraction(int(np.round(abs(p) * approx_denom)), approx_denom) for p in periods 444 ]

/usr/local/lib/python3.8/dist-packages/cirq/ops/eigen_gate.py in (.0) 441 return abs(periods[0]) 442 approx_rational_periods = [ --> 443 fractions.Fraction(int(np.round(abs(p) * approx_denom)), approx_denom) for p in periods 444 ] 445 common = float(_common_rational_period(approx_rational_periods))

<__array_function__ internals> in round_(*args, **kwargs) [/usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py](https://localhost:8080/#) in round_(a, decimals, out) 3737 around : equivalent function; see for details. 3738 """ -> 3739 return around(a, decimals=decimals, out=out) 3740 3741 <__array_function__ internals> in around(*args, **kwargs) [/usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py](https://localhost:8080/#) in around(a, decimals, out) 3312 3313 """ -> 3314 return _wrapfunc(a, 'round', decimals=decimals, out=out) 3315 3316 [/usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py](https://localhost:8080/#) in _wrapfunc(obj, method, *args, **kwds) 64 # Call _wrapit from within the except clause to ensure a potential 65 # exception has a traceback chain. ---> 66 return _wrapit(obj, method, *args, **kwds) 67 68 [/usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py](https://localhost:8080/#) in _wrapit(obj, method, *args, **kwds) 41 except AttributeError: 42 wrap = None ---> 43 result = getattr(asarray(obj), method)(*args, **kwds) 44 if wrap: 45 if not isinstance(result, mu.ndarray): TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable rint method Regards, Bindu
maiyuren commented 1 year ago

Hi Bindu,

Yes this error occurs with the latest version of cirq. Make sure you install the exact versions of the libraries and it should work!

Regards, Maiyuren