def optimize_circuit(params): """Minimize the variational circuit and return its minimum value. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. You should create a device and convert the variational_circuit function into an executable QNode. Next, you should minimize the variational circuit using gradient-based optimization to update the input params. Return the optimized value of the QNode as a single floating-point number. Args: params (np.ndarray): Input parameters to be optimized, of dimension 30 Returns: float: the value of the optimized QNode """ optimal_value = 0.0 # QHACK # # Initialize the device # dev = ... dev = qml.device('default.qubit', wires=2) # Instantiate the QNode # circuit = qml.QNode(variational_circuit, dev) circuit = qml.QNode(variational_circuit, dev) # Minimize the circuit # Using default params var = params opt = AdamOptimizer(stepsize=0.01) for it in range(250): var, optimal_value = opt.step_and_cost(circuit, var) # print("Iter: {:5d} | Cost: {:0.7f} ".format(it, optimal_value)) # print(circuit.draw()) # QHACK # # Return the value of the minimized QNode return optimal_value
# # .. code-block:: none # # array([[ 0.08820262, 0.02000786, 0.0489369 , 0.11204466, 0.0933779 ], # [-0.04886389, 0.04750442, -0.00756786, -0.00516094, 0.02052993], # [ 0.00720218, 0.07271368, 0.03805189, 0.00608375, 0.02219316], # [ 0.01668372, 0.07470395, -0.01025791, 0.01565339, -0.04270479]]) # # Using the Adam optimizer, we update the weights for 500 steps (this # takes some time). More steps will lead to a better fit. opt = AdamOptimizer(0.01, beta1=0.9, beta2=0.999) var = var_init for it in range(500): var, _cost = opt.step_and_cost(lambda v: cost(v, X, Y), var) print("Iter: {:5d} | Cost: {:0.7f} ".format(it, _cost)) ############################################################################## # .. rst-class:: sphx-glr-script-out # # Out: # # .. code-block:: none # # Iter: 0 | Cost: 0.3006065 # Iter: 1 | Cost: 0.2689702 # Iter: 2 | Cost: 0.2472125 # Iter: 3 | Cost: 0.2300139 # Iter: 4 | Cost: 0.2157100 # Iter: 5 | Cost: 0.2035455