quantum icon indicating copy to clipboard operation
quantum copied to clipboard

About the input of quantum neural network in tensorflow quantum

Open SSSSSCV opened this issue 4 years ago • 4 comments

I created a quantum neural network using tensorflow quantum,It's input is a tensor converted by circuit.About this input circuit,I found that if the parameters of the circuit are also specified by tensors, the quantum neural network cannot be trained. The circuit when using normal parameters can make the network train normally

theta_g=1
blob_size = abs(1 - 4) / 5
spread_x = np.random.uniform(-blob_size, blob_size)
spread_y = np.random.uniform(-blob_size, blob_size)
angle = theta_g + spread_y
cir=cirq.Circuit(cirq.ry(-angle)(qubit), cirq.rx(-spread_x)(qubit))
discriminator_network(tfq.convert_to_tensor([cir]))

But when I use the following code, the quantum neural network cannot be trained

theta_g=tf.constant([1])
blob_size = abs(1 - 4) / 5
spread_x = np.random.uniform(-blob_size, blob_size)
spread_y = np.random.uniform(-blob_size, blob_size)
spred_x = tf.constant(spread_x)
spred_y = tf.constant(spread_y)
angle = theta_g + spread_y
cir=cirq.Circuit(cirq.ry(-angle)(qubit), cirq.rx(-spread_x)(qubit))
discriminator_network(tfq.convert_to_tensor([cir]))

The discriminator_network

def discriminator():
    theta = sympy.Symbol('theta')
    q_model = cirq.Circuit(cirq.ry(theta)(qubit))
    q_data_input = tf.keras.Input(
        shape=(), dtype=tf.dtypes.string)
    expectation = tfq.layers.PQC(q_model, cirq.Z(qubit))
    expectation_output = expectation(q_data_input)

    classifier = tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid)
    classifier_output = classifier(expectation_output)
    model = tf.keras.Model(inputs=q_data_input, outputs=classifier_output)
    return model

SSSSSCV avatar Sep 09 '20 13:09 SSSSSCV

Without seeing the code for discriminator_network we won't be able to diagnose the issue, could you post more? I suspect the main issue is that, to use circuits converted to tensors, discriminator_network needs to be written in terms of the TensorFlow Quantum layers: https://www.tensorflow.org/quantum/api_docs/python/tfq/layers. Also, to be trainable, the circuits need to have free parameters specified in terms of sympy variables. I would recommend going through the tutorial: https://www.tensorflow.org/quantum/tutorials/hello_many_worlds, which compares running circuits with raw Cirq and with Tensorflow Quantum.

zaqqwerty avatar Sep 09 '20 13:09 zaqqwerty

@zaqqwerty ,Thank your help.I added the code about the discriminator_network

SSSSSCV avatar Sep 09 '20 13:09 SSSSSCV

Any updates on this @zaqqwerty ?

MichaelBroughton avatar Feb 25 '21 19:02 MichaelBroughton

This is similar to https://github.com/tensorflow/quantum/issues/712, it doesn't like tensors are parameters for cirq. Any other updates on this issue?

lockwo avatar Aug 24 '22 18:08 lockwo