-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKernelGenerator.py
More file actions
54 lines (38 loc) · 1.62 KB
/
Copy pathKernelGenerator.py
File metadata and controls
54 lines (38 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Our proposed construction of local kernels
from qiskit.circuit.library import zz_feature_map
import numpy as np
from qiskit_machine_learning.kernels import FidelityQuantumKernel
def kernelsubcomputation(
x: np.ndarray,
y: np.ndarray | None = None,
feature_map=None,
cyclic: bool = True,
):
# Quantum local-kernel: average fidelity over windows
if y is None:
y = x
if feature_map is None:
feature_map = zz_feature_map(feature_dimension=3, reps=1, entanglement="linear")
dim = x.shape[1]
num_qubits = feature_map.num_qubits
if dim < num_qubits:
raise ValueError(f"Input dimension {dim} must be greater than or equal to feature_map.num_qubits ({num_qubits}).")
subkernel = FidelityQuantumKernel(feature_map=feature_map)
matrix = np.zeros((x.shape[0], y.shape[0]))
num_subkernels = 0
for i in range(dim - num_qubits + 1):
kernel_block = np.array(subkernel.evaluate(x[:, i : i + num_qubits], y[:, i : i + num_qubits]))
matrix = matrix + kernel_block
num_subkernels += 1
# Add the wrap-around combinations only when cyclic behavior is enabled.
if cyclic and num_qubits > 1:
for offset in range(1, num_qubits):
indices = [(dim - offset + j) % dim for j in range(num_qubits)]
dx = x[:, indices]
dy = y[:, indices]
kernel_block = np.array(subkernel.evaluate(dx, dy))
matrix = matrix + kernel_block
num_subkernels += 1
# Normalize by the number of subkernels that were actually evaluated.
matrix = matrix / num_subkernels
return matrix