tensorflow / quantum

Hybrid Quantum-Classical Machine Learning in TensorFlow
https://www.tensorflow.org/quantum
Apache License 2.0
1.77k stars 567 forks source link

About the input of quantum neural network in tensorflow quantum #377

Open SSSSSCV opened 3 years ago

SSSSSCV commented 3 years ago

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
zaqqwerty commented 3 years ago

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.

SSSSSCV commented 3 years ago

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

MichaelBroughton commented 3 years ago

Any updates on this @zaqqwerty ?

lockwo commented 1 year ago

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?