Hello All,
I am trying to compute the objective function for the Max-Cut QAOA from the sampled bitstring, instead of computing the expectation value via qml.expval
. However, when I run my code I get the error as:
p=1
Traceback (most recent call last):
File "<path>\autograd\core.py", line 238, in vspace
return VSpace.mappings[type(value)](value)
KeyError: <class 'numpy.int64'>
.
.
.
.
.
raise TypeError("Can't find vector space for value {} of type {}. "
TypeError: Can't find vector space for value 0 of type <class 'numpy.int64'>. Valid types are dict_keys([<class 'autograd.core.SparseObject'>, <class 'list'>, <class 'tuple'>, <class 'dict'>, <class 'numpy.ndarray'>, <class 'float'>, <class 'numpy.float64'>, <class 'numpy.float32'>, <class 'numpy.float16'>, <class 'complex'>, <class 'numpy.complex64'>, <class 'numpy.complex128'>, <class 'pennylane.numpy.tensor.tensor'>])
The cod is pasted below. Some help on this issue would be great. Thank you
@qml.qnode(dev)
def circuit(gammas, betas, n_layers=1):
# apply Hadamards to get the n qubit |+> state
for wire in range(n_wires):
qml.Hadamard(wires=wire)
# p instances of unitary operators
for i in range(n_layers):
U_C(gammas[i])
U_B(betas[i])
return qml.sample(wires=[0, 1, 2, 3])
def bitstring_to_int(bit_string_sample):
bit_string = np.array([float(bits) for bits in bit_string_sample])
return bit_string
def qaoa_maxcut(n_layers=1):
print("\np={:d}".format(n_layers))
# initialize the parameters
init_params = 0.1 * np.random.rand(2, n_layers, requires_grad=True)
def objective(params):
strings = circuit(params[0], params[1], n_layers=n_layers)
cost = 0.0
for x_i in strings:
for x_j in strings:
x1 = qml.math.cast(x_i, np.float64)
x2 = qml.math.cast(x_j, np.float64)
cost += -x1 - x2 + 2.0 * x1 * x2
return cost
# initialize optimizer
opt = qml.AdagradOptimizer(stepsize=0.01)
# optimize parameters in objective
params = init_params
steps = 10
for i in range(steps):
params = opt.step(objective, params)
if (i + 1) % 5 == 0:
print("Objective after step {:5d}: {: .7f}".format(i + 1, objective(params)))
return params
bitstrings1 = qaoa_maxcut(n_layers=1)[1]