Пример #1
0
 def ADAMOPT():
     for x_idx, shotnum in enumerate(SHOTRANGE):
         circuit = initialize(shotnum)
         opt = qml.AdamOptimizer(0.01)
         thetaadam = init_params
         for y_idx in range(STEPS):
             thetaadam = opt.step(circuit, thetaadam)
             ADAM_COST[x_idx, y_idx] = circuit(thetaadam)
     np.save("./datafiles/adamshotcosttoy.npy", ADAM_COST)
Пример #2
0
    def ROTOOPT():
        for x_idx, shotnum in enumerate(SHOTRANGE):
            circuit = initialize(shotnum)
            print("Doing rotosolve")
            opt = qml.RotosolveOptimizer()

            thetart = init_params
            for y_idx in range(STEPS):
                thetart = opt.step(circuit, thetart)
                ROTO_COST[x_idx, y_idx] = circuit(thetart)
        np.save("./datafiles/rotoshotcosttoy.npy", ROTO_COST)

        print("Doing adam")
Пример #3
0
    def GDOPT():
        for x_idx, shotnum in enumerate(SHOTRANGE):
            circuit = initialize(shotnum)
            print(f"round {x_idx} of {DENSITY} with {shotnum} shots")

            opt = qml.GradientDescentOptimizer(0.01)
            print("Doing the gradient descent")
            thetagd = init_params
            for y_idx in range(STEPS):
                thetagd = opt.step(circuit, thetagd)
                GD_COST[x_idx, y_idx] = circuit(thetagd)
        print("finally save GD cost file")
        np.save("./datafiles/gdshotcosttoy.npy", GD_COST)
        return  # exit for GC
Пример #4
0
    def QNGOPT():
        for x_idx, shotnum in enumerate(SHOTRANGE):
            #%% Quantum natural gradient
            circuit = initialize(shotnum)
            print("Doing the quantum natural gradient")
            thetaqng = init_params
            opt = qml.QNGOptimizer(0.01)

            for y_idx in range(STEPS):
                working = False
                while not working:
                    try:
                        thetaqng = opt.step(circuit, thetaqng)
                        QNG_COST[x_idx, y_idx] = circuit(thetaqng)
                        working = True
                    except:
                        pass
                working = False
        np.save("./datafiles/qngshotcosttoy.npy", QNG_COST)
Пример #5
0
    q_train_images = []
    print("Quantum pre-processing of train images:")
    for idx, img in enumerate(train_images):
        print("{}/{}        ".format(idx + 1, n_train), end="\r")
        q_train_images.append(quanv(img))
    q_train_images = np.asarray(q_train_images)

    q_test_images = []
    print("\nQuantum pre-processing of test images:")
    for idx, img in enumerate(test_images):
        print("{}/{}        ".format(idx + 1, n_test), end="\r")
        q_test_images.append(quanv(img))
    q_test_images = np.asarray(q_test_images)

    # Save pre-processed images
    np.save(SAVE_PATH + "q_train_images.npy", q_train_images)
    np.save(SAVE_PATH + "q_test_images.npy", q_test_images)

# Load pre-processed images
q_train_images = np.load(SAVE_PATH + "q_train_images.npy")
q_test_images = np.load(SAVE_PATH + "q_test_images.npy")

##############################################################################
# Let us visualize the effect of the quantum convolution
# layer on a batch of samples:

n_samples = 4
n_channels = 4
fig, axes = plt.subplots(1 + n_channels, n_samples, figsize=(10, 10))
for k in range(n_samples):
    axes[0, 0].set_ylabel("Input")
Пример #6
0
                X_test[np.where(y_train == 1)[0], 1],
                color="b",
                marker="x",
                label="test, zero")
    plt.scatter(X_test[np.where(y_train == -1)[0], 0],
                X_test[np.where(y_train == -1)[0], 1],
                color="r",
                marker="x",
                label="test, not zero")
    plt.ylim([0, 1])
    plt.xlim([0, 1])
    plt.legend()

    filename = "data/dataset_MNIST_23_zero_untrained.npy"
    with open(filename, 'wb') as f:
        np.save(f, X_dummy)
        np.save(f, y_dummy)
        np.save(f, X_train)
        np.save(f, y_train)
        np.save(f, X_test)
        np.save(f, y_test)
"""
Currently, the function ``qml.kernels.target_alignment`` is not
differentiable yet, making it unfit for gradient descent optimization.
We therefore first define a differentiable version of this function.
"""


def target_alignment(
    X,
    Y,
Пример #7
0
        import pickle as pkl
        with open("./datafiles/outputprime.pkl", "wb") as f:
            pkl.dump(output,f)


    if SHOTS_TEST:
        shot_arr = range(5,101,2)
        OUTPUT_ARR = np.zeros((len(shot_arr), NUM_STEPS+1))
        GRAPH = gnp_random_connected_graph(4,0.2,42)
        args = [("roto", GRAPH, 3, False, shots, False) for shots in shot_arr]
        results = pool.starmap(qaoa_maxcut, args)
        pool.close()
        pool.join()
        for idx, result in enumerate(results):
            OUTPUT_ARR[idx] = result[1]
        np.save("./datafiles/shotsmaxcutroto2.npy", OUTPUT_ARR)

    if NOISE_TEST:
        noise_arr = np.linspace(0.001,0.3,100)
        OUTPUT_ARR = np.zeros((len(noise_arr), NUM_STEPS+1))
        GRAPH = gnp_random_connected_graph(8,0.3,42)
        NOISE_MODELS = [noise.NoiseModel() for i in range(len(noise_arr))]
        for NoiseModel, NoiseStrength in zip(NOISE_MODELS, noise_arr):
            NoiseModel.add_all_qubit_quantum_error(noise.depolarizing_error(NoiseStrength,1), ['u1','u2','u3'])
        args = [("adam", GRAPH, 6, False, None, False, NoiseModel) for NoiseModel in NOISE_MODELS] 
        results = pool.starmap(qaoa_maxcut, args)
        pool.close()
        pool.join()
        for idx, result in enumerate(results):
            OUTPUT_ARR[idx] = result[1]
        np.save("./datafiles/depolnoise1qubitadam.npy", OUTPUT_ARR)
print("Initial parameters ", init_pars)
cst = cost(pars, A=A, B=B)
print("Initial cost ", 0, " -- ", cst)

if save_featmap:
    featmap_settings = {
        'pars': pars,
        'step': 0,
        'featmap':
        pickle.dumps(featmap),  # serialise and save_featmap the feature map
        'n_layers': n_layers,
        'n_wires': n_inp,
        'X': X,
        'Y': Y
    }
    np.save(name_output + ".npy", featmap_settings)

for i in range(n_steps):

    # Sample a batch of pairs
    selectA = np.random.choice(range(len(A)),
                               size=(batch_size, ),
                               replace=True)
    selectB = np.random.choice(range(len(B)),
                               size=(batch_size, ),
                               replace=True)
    A_batch = [A[s] for s in selectA]
    B_batch = [B[s] for s in selectB]

    # Walk one optimization step (using all training samples)
    pars = optimizer.step(lambda w: cost(w, A=A_batch, B=B_batch), pars)
Пример #9
0
    params, cost_before = optimizer.step_and_cost(cost_function, params)

    t1 = time.time()

    if i == 0:
        print("Initial cost:", cost_before)
    else:
        print(f"Cost at step {i}:", cost_before)

    print(f"Completed iteration {i + 1}")
    print(f"Time to complete iteration: {t1 - t0} seconds")

print(f"Cost at step {iterations}:", cost_function(params))

np.save("params.npy", params)
print("Parameters saved to params.npy")

##############################################################################
# .. rst-class:: sphx-glr-script-out
#
#  Out:
#
#  .. code-block:: none
#
#    Initial cost: -29.98570234095951
#    Completed iteration 1
#    Time to complete iteration: 93.96246099472046 seconds
#    Cost at step 1: -27.154071768632154
#    Completed iteration 2
#    Time to complete iteration: 84.80994844436646 seconds