qiskit-community / qiskit-machine-learning

Quantum Machine Learning
https://qiskit-community.github.io/qiskit-machine-learning/
Apache License 2.0
647 stars 316 forks source link

API for extracting train and test kernel matrices and support vectors from QSVC upon completed training #129

Closed zoplex closed 3 years ago

zoplex commented 3 years ago

What is the expected enhancement?

Provide way to extract train and test kernel matrices after the QSVC is fit/predicted, without having to invoke evaluate - since that doubles the run time needed:

qsvc = QSVC(quantum_kernel=qkernel) qsvc.fit(sample_train,label_train) qsvc.predict(sample_test)

next code/api would be great to have without having to run evaluate:

train_kernel = qsvc.get_train_kernel() # returns train x train kernel matrix test_kernel = qsvc.get_test_kernel() # returns test x train kernel matrix spvec = qsvc.get_support_vectors(). # return actual support vectors

attp commented 3 years ago

@zoplex as QSVC extends the scikit-learn svc class, we are restricted with what that returns.

You to get the indices of the support vectors using qsvc.support_, but I don't believe it is possible to get the kernel matrices from svc, or at least I haven't been able to find it in the documentation.

The quantum kernel machine learning tutorial shows you how to calculate the matrices and provide them to scikit-learn svc.

If you want to be more efficient, and not create the full test x train matrix, you could retrain a new svc using just the support vectors:

train_matrix = adhoc_kernel.evaluate(x_vec=train_data)
svc_initial = SVC(kernel='precomputed')
svc_initial.fit(train_matrix, train_labels)
svc_support = svc_initial.support_
train_matrix_support = train_matrix[svc_support,:][:,svc_support]
test_matrix_support = adhoc_kernel.evaluate(x_vec=test_data, y_vec=train_data[svc_support])
svc = SVC(kernel='precomputed')
svc.fit(train_matrix_support, train_labels[svc_support])
svc_score = svc.score(test_matrix_support, test_labels)
zoplex commented 3 years ago

Thank you for the quick response. We already upgraded the code to the latest qiskit version and we are using .evaluate to calculate both train and test kernel matrices (full size) just like in the same code on qiskit site/above in your example, we were not sure how to get support vectors. This solution above resolves it, I will try this approach. Using support vectors dimension instead of full train in test x train will save some time too.

Best regards