0
$\begingroup$

I am new to quantum machine learning and I am trying to build a VQR with Qiskit. The input and target data to my model both have shape (32,4), where 32 is the number of samples and 4 is the number of features per sample (so I have 32 vectors with 4 features each). I want to use ZZFeatureMap as my feature map but i have problems setting the input and target data dimensions correctly so that the ZZFeatureMap processes correctly the input and prepares the desired state. Here's my code which i based on the code from qiskit's vqr example. Here is my code:

def callback_graph(weights, obj_func_eval):
    clear_output(wait=True)
    objective_func_vals.append(obj_func_eval)
    plt.title("Objective function value against iteration")
    plt.xlabel("Epochs")
    plt.ylabel("Objective function value")
    plt.plot(range(len(objective_func_vals)), objective_func_vals)
   #plt.yscale('log')
    plt.show()

algorithm_globals.random_seed = 42

num_features= 4
num_samples = 32

xdef = np.array([i for i in range(1,num_features*num_samples+1)]) # Features are dict indices in my case (no 0 idx desired)
xdef = xdef/np.linalg.norm(xdef)
xdef = xdef.reshape(num_samples, num_features)

ydef = np.array([i**2 for i in range(1,num_features*num_samples+1)]) # As if the function f in y=f(x) is f(x) = x**2
ydef = ydef/np.linalg.norm(ydef)
ydef = ydef.reshape(num_samples, num_features)

xpred = np.array([i for i in range(100,228)]) # Considering features the model has never seen
xpred = xpred/np.linalg.norm(xpred)
xpred = xpred.reshape(num_samples,num_features)

num_qubits = int(np.log2(num_samples*num_features))
feature_map = ZZFeatureMap(feature_dimension=num_qubits, reps=1)
ansatz = RealAmplitudes(num_qubits=num_qubits, entanglement='full')

vqr = VQR(feature_map=feature_map,
          ansatz = ansatz,
    optimizer=COBYLA(maxiter=50),
    callback=callback_graph,
)

# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (20, 6)

# fit regressor
vqr.fit(xdef, ydef)

# return to default figsize
plt.rcParams["figure.figsize"] = (20, 4)

# score result
print(vqr.score(xdef, ydef))

# plot target function
plt.plot(list(xdef), list(ydef), "r--")
plt.show()

# plot fitted line
y_ = vqr.predict(xpred)

plt.plot(list(xpred), list(y_), "g-")
plt.show()

but i get get this error:

QiskitMachineLearningError: 'Input data has incorrect shape, last dimension is not equal to the number of inputs: 7, but got: 4.'

When i try

num_qubits = 4

i get this error

ValueError: cannot reshape array of size 128 into shape (32,1)

Im confused as to what shape does the VQR class object expects for xdef and ydef... Anyone has an idea how should i reshape my input data so that the amplitude encoding gets done properly by the ZZFeatureMap ?

$\endgroup$

0

Your Answer

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