ansatz = mera_circuit(num_qubits, periodic, fix_layers)
        cost_fn = qml.ExpvalCost(ansatz, H, dev)
        grad = qml.grad(cost_fn)

        num_params_per_gate = 15
        num_gates = get_num_mera_gates(num_qubits, periodic, fix_layers)
        num_params = num_params_per_gate * num_gates
        params = np.pi * (np.random.rand(num_params) - 1.0)

        gradient = np.array(grad(params)[0])
        grad_vals.append(gradient)
    variances.append(np.mean(np.var(grad_vals, axis=0)))

print(variances)
#variances = np.array(np.mean(variances, axis=1))
qubits = np.array(qubits)

# Fit the semilog plot to a straight line
p = np.polyfit(qubits, np.log(variances), 1)

# Plot the straight line fit to the semilog
plt.semilogy(qubits, variances, "o")
plt.semilogy(qubits,
             np.exp(p[0] * qubits + p[1]),
             "o-.",
             label="Slope {:3.2f}".format(p[0]))
plt.xlabel(r"N Qubits")
plt.ylabel(r"$\langle \partial \theta_{1, 1} E\rangle$ variance")
plt.legend()
plt.show()
Beispiel #2
0
#
# For a better comparison, we can scale the time required for computing the quantum
# gradients against the time taken for the corresponding forward pass:

gradient_shift[1] /= forward_shift[1, 1:]
gradient_backprop[1] /= forward_backprop[1, 1:]

fig, ax = plt.subplots(1, 1, figsize=(6, 4))

ax.plot(*gradient_shift, '.-', label="Parameter-shift")
ax.plot(*gradient_backprop, '.-', label="Backprop")

# perform a least squares regression to determine the linear best fit/gradient
# for the normalized time vs. number of parameters
x = gradient_shift[0]
m_shift, c_shift = np.polyfit(*gradient_shift, deg=1)
m_back, c_back = np.polyfit(*gradient_backprop, deg=1)

ax.plot(x, m_shift * x + c_shift, '--', label=f"{m_shift:.2f}p{c_shift:+.2f}")
ax.plot(x, m_back * x + c_back, '--', label=f"{m_back:.2f}p{c_back:+.2f}")

ax.set_ylabel("Normalized time")
ax.set_xlabel("Number of parameters")
ax.set_xscale("log")
ax.set_yscale("log")
ax.legend()

plt.show()

##############################################################################
# .. raw:: html