1- # This code is part of a Qiskit project.
2- #
3- # (C) Copyright IBM 2021, 2025.
4- #
5- # This code is licensed under the Apache License, Version 2.0. You may
6- # obtain a copy of this license in the LICENSE.txt file in the root directory
7- # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8- #
9- # Any modifications or derivative works of this code must retain this
10- # copyright notice, and modified files need to carry a notice indicating
11- # that they have been altered from the originals.
12- """Test QSVR on fidelity quantum kernel."""
13-
14- import os
15- import tempfile
16- import unittest
17-
18- from test import QiskitMachineLearningTestCase
19-
20- import numpy as np
21- from sklearn .metrics import mean_squared_error
22-
23- from qiskit .primitives import Sampler
24- from qiskit .circuit .library import zz_feature_map
25-
26- from qiskit_machine_learning .utils import algorithm_globals
27- from qiskit_machine_learning .algorithms import QSVR , SerializableModelMixin
28- from qiskit_machine_learning .exceptions import QiskitMachineLearningWarning
29- from qiskit_machine_learning .kernels import FidelityQuantumKernel
30-
31-
32- class TestQSVR (QiskitMachineLearningTestCase ):
33- """Test QSVR Algorithm on fidelity quantum kernel."""
34-
35- def setUp (self ):
36- super ().setUp ()
37-
38- algorithm_globals .random_seed = 10598
39-
40- self .sampler = Sampler ()
41- self .feature_map = zz_feature_map (feature_dimension = 2 , reps = 2 )
42-
43- self .sample_train = np .asarray (
44- [
45- [- 0.36572221 , 0.90579879 ],
46- [- 0.41816432 , 0.03011426 ],
47- [- 0.48806982 , 0.87208714 ],
48- [- 0.67078436 , - 0.91017876 ],
49- [- 0.12980588 , 0.98475113 ],
50- [0.78335453 , 0.49721604 ],
51- [0.78158498 , 0.78689328 ],
52- [0.03771672 , - 0.3681419 ],
53- [0.54402486 , 0.32332253 ],
54- [- 0.25268454 , - 0.81106666 ],
55- ]
56- )
57- self .label_train = np .asarray (
58- [
59- 0.07045477 ,
60- 0.80047778 ,
61- 0.04493319 ,
62- - 0.30427998 ,
63- - 0.02430856 ,
64- 0.17224315 ,
65- - 0.26474769 ,
66- 0.83097582 ,
67- 0.60943777 ,
68- 0.31577759 ,
69- ]
70- )
71-
72- self .sample_test = np .asarray (
73- [
74- [- 0.60713067 , - 0.37935265 ],
75- [0.55480968 , 0.94365285 ],
76- [0.00148237 , - 0.71220499 ],
77- [- 0.97212742 , - 0.54068794 ],
78- ]
79- )
80- self .label_test = np .asarray ([0.45066614 , - 0.18052862 , 0.4549451 , - 0.23674218 ])
81-
82- def test_qsvr (self ):
83- """Test QSVR"""
84- qkernel = FidelityQuantumKernel (feature_map = self .feature_map )
85- qsvr = QSVR (quantum_kernel = qkernel )
86- qsvr .fit (self .sample_train , self .label_train )
87-
88- predictions = qsvr .predict (self .sample_test )
89- mse = mean_squared_error (self .label_test , predictions )
90- self .assertAlmostEqual (mse , 0.04964456790383482 , places = 4 )
91-
92- def test_change_kernel (self ):
93- """Test QSVR with QuantumKernel later"""
94- qkernel = FidelityQuantumKernel (feature_map = self .feature_map )
95-
96- qsvr = QSVR ()
97- qsvr .quantum_kernel = qkernel
98- qsvr .fit (self .sample_train , self .label_train )
99-
100- predictions = qsvr .predict (self .sample_test )
101- mse = mean_squared_error (self .label_test , predictions )
102- self .assertAlmostEqual (mse , 0.04964456790383482 , places = 4 )
103-
104- def test_qsvr_parameters (self ):
105- """Test QSVR with extra constructor parameters"""
106- qkernel = FidelityQuantumKernel (feature_map = self .feature_map )
107-
108- qsvr = QSVR (quantum_kernel = qkernel , tol = 1e-3 , C = 1.0 )
109- qsvr .fit (self .sample_train , self .label_train )
110-
111- predictions = qsvr .predict (self .sample_test )
112- mse = mean_squared_error (self .label_test , predictions )
113- self .assertAlmostEqual (mse , 0.04964456790383482 , places = 4 )
114-
115- def test_qsvc_to_string (self ):
116- """Test QSVR print works when no *args passed in"""
117- qsvr = QSVR ()
118- _ = str (qsvr )
119-
120- def test_with_kernel_parameter (self ):
121- """Test QSVC with the `kernel` argument."""
122- with self .assertWarns (QiskitMachineLearningWarning ):
123- QSVR (kernel = 1 )
124-
125- def test_save_load (self ):
126- """Tests save and load models."""
127- features = np .array ([[0 , 0 ], [0.1 , 0.1 ], [0.4 , 0.4 ], [1 , 1 ]])
128- labels = np .array ([0 , 0.1 , 0.4 , 1 ])
129-
130- quantum_kernel = FidelityQuantumKernel (feature_map = zz_feature_map (2 ))
131- regressor = QSVR (quantum_kernel = quantum_kernel )
132- regressor .fit (features , labels )
133-
134- test_features = np .array ([[0.5 , 0.5 ]])
135- original_predicts = regressor .predict (test_features )
136-
137- with tempfile .TemporaryDirectory () as dir_name :
138- file_name = os .path .join (dir_name , "qsvr.model" )
139- regressor .to_dill (file_name )
140-
141- regressor_load = QSVR .from_dill (file_name )
142- loaded_model_predicts = regressor_load .predict (test_features )
143-
144- np .testing .assert_array_almost_equal (original_predicts , loaded_model_predicts )
145-
146- class FakeModel (SerializableModelMixin ):
147- """Fake model class for test purposes."""
148-
149- pass
150-
151- with self .assertRaises (TypeError ):
152- FakeModel .from_dill (file_name )
153-
154-
155- if __name__ == "__main__" :
156- unittest .main ()
1+ # This code is part of a Qiskit project.
2+ #
3+ # (C) Copyright IBM 2021, 2025.
4+ #
5+ # This code is licensed under the Apache License, Version 2.0. You may
6+ # obtain a copy of this license in the LICENSE.txt file in the root directory
7+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8+ #
9+ # Any modifications or derivative works of this code must retain this
10+ # copyright notice, and modified files need to carry a notice indicating
11+ # that they have been altered from the originals.
12+ """Test QSVR on fidelity quantum kernel."""
13+
14+ import os
15+ import tempfile
16+ import unittest
17+
18+ from test import QiskitMachineLearningTestCase
19+
20+ import numpy as np
21+ from sklearn .metrics import mean_squared_error
22+
23+ from qiskit .primitives import BaseSamplerV2 # change: Sampler migrated to BaseSamplerV2
24+ from qiskit .circuit .library import zz_feature_map
25+
26+ from qiskit_machine_learning .utils import algorithm_globals
27+ from qiskit_machine_learning .algorithms import QSVR , SerializableModelMixin
28+ from qiskit_machine_learning .exceptions import QiskitMachineLearningWarning
29+ from qiskit_machine_learning .kernels import FidelityQuantumKernel
30+
31+ class TestQSVR (QiskitMachineLearningTestCase ):
32+ """Test QSVR Algorithm on fidelity quantum kernel."""
33+
34+ def setUp (self ):
35+ super ().setUp ()
36+
37+ algorithm_globals .random_seed = 10598
38+
39+ self .sampler = BaseSamplerV2 () # change: Sampler migrated to BaseSamplerV2
40+ self .feature_map = zz_feature_map (feature_dimension = 2 , reps = 2 )
41+
42+ self .sample_train = np .asarray (
43+ [
44+ [- 0.36572221 , 0.90579879 ],
45+ [- 0.41816432 , 0.03011426 ],
46+ [- 0.48806982 , 0.87208714 ],
47+ [- 0.67078436 , - 0.91017876 ],
48+ [- 0.12980588 , 0.98475113 ],
49+ [0.78335453 , 0.49721604 ],
50+ [0.78158498 , 0.78689328 ],
51+ [0.03771672 , - 0.3681419 ],
52+ [0.54402486 , 0.32332253 ],
53+ [- 0.25268454 , - 0.81106666 ],
54+ ]
55+ )
56+ self .label_train = np .asarray (
57+ [
58+ 0.07045477 ,
59+ 0.80047778 ,
60+ 0.04493319 ,
61+ - 0.30427998 ,
62+ - 0.02430856 ,
63+ 0.17224315 ,
64+ - 0.26474769 ,
65+ 0.83097582 ,
66+ 0.60943777 ,
67+ 0.31577759 ,
68+ ]
69+ )
70+
71+ self .sample_test = np .asarray (
72+ [
73+ [- 0.60713067 , - 0.37935265 ],
74+ [0.55480968 , 0.94365285 ],
75+ [0.00148237 , - 0.71220499 ],
76+ [- 0.97212742 , - 0.54068794 ],
77+ ]
78+ )
79+ self .label_test = np .asarray ([0.45066614 , - 0.18052862 , 0.4549451 , - 0.23674218 ])
80+
81+ def test_qsvr (self ):
82+ """Test QSVR"""
83+ qkernel = FidelityQuantumKernel (feature_map = self .feature_map )
84+ qsvr = QSVR (quantum_kernel = qkernel )
85+ qsvr .fit (self .sample_train , self .label_train )
86+
87+ predictions = qsvr .predict (self .sample_test )
88+ mse = mean_squared_error (self .label_test , predictions )
89+ self .assertAlmostEqual (mse , 0.04964456790383482 , places = 4 )
90+
91+ def test_change_kernel (self ):
92+ """Test QSVR with QuantumKernel later"""
93+ qkernel = FidelityQuantumKernel (feature_map = self .feature_map )
94+
95+ qsvr = QSVR ()
96+ qsvr .quantum_kernel = qkernel
97+ qsvr .fit (self .sample_train , self .label_train )
98+
99+ predictions = qsvr .predict (self .sample_test )
100+ mse = mean_squared_error (self .label_test , predictions )
101+ self .assertAlmostEqual (mse , 0.04964456790383482 , places = 4 )
102+
103+ def test_qsvr_parameters (self ):
104+ """Test QSVR with extra constructor parameters"""
105+ qkernel = FidelityQuantumKernel (feature_map = self .feature_map )
106+
107+ qsvr = QSVR (quantum_kernel = qkernel , tol = 1e-3 , C = 1.0 )
108+ qsvr .fit (self .sample_train , self .label_train )
109+
110+ predictions = qsvr .predict (self .sample_test )
111+ mse = mean_squared_error (self .label_test , predictions )
112+ self .assertAlmostEqual (mse , 0.04964456790383482 , places = 4 )
113+
114+ def test_qsvc_to_string (self ):
115+ """Test QSVR print works when no *args passed in"""
116+ qsvr = QSVR ()
117+ _ = str (qsvr )
118+
119+ def test_with_kernel_parameter (self ):
120+ """Test QSVC with the `kernel` argument."""
121+ with self .assertWarns (QiskitMachineLearningWarning ):
122+ QSVR (kernel = 1 )
123+
124+ def test_save_load (self ):
125+ """Tests save and load models."""
126+ features = np .array ([[0 , 0 ], [0.1 , 0.1 ], [0.4 , 0.4 ], [1 , 1 ]])
127+ labels = np .array ([0 , 0.1 , 0.4 , 1 ])
128+
129+ quantum_kernel = FidelityQuantumKernel (feature_map = zz_feature_map (2 ))
130+ regressor = QSVR (quantum_kernel = quantum_kernel )
131+ regressor .fit (features , labels )
132+
133+ test_features = np .array ([[0.5 , 0.5 ]])
134+ original_predicts = regressor .predict (test_features )
135+
136+ with tempfile .TemporaryDirectory () as dir_name :
137+ file_name = os .path .join (dir_name , "qsvr.model" )
138+ regressor .to_dill (file_name )
139+
140+ regressor_load = QSVR .from_dill (file_name )
141+ loaded_model_predicts = regressor_load .predict (test_features )
142+
143+ np .testing .assert_array_almost_equal (original_predicts , loaded_model_predicts )
144+
145+ class FakeModel (SerializableModelMixin ):
146+ """Fake model class for test purposes."""
147+
148+ pass
149+
150+ with self .assertRaises (TypeError ):
151+ FakeModel .from_dill (file_name )
152+
153+ if __name__ == "__main__" :
154+ unittest .main ()
0 commit comments