# Tensorflow\_quantum hybrid models tf-quantum

**URL:** <https://discuss.ai.google.dev/t/tensorflow-quantum-hybrid-models-tf-quantum/29613>\
**Category:** General Discussion\
**Tags:** models, tf-quantum\
**Created:** [October 3, 2023, 4:17am UTC](https://discuss.ai.google.dev/t/tensorflow-quantum-hybrid-models-tf-quantum/29613 "2023-10-03T04:17:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kieran\_mcdowall](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/kieran_mcdowall/32/7564_2.png) [@kieran\_mcdowall](https://discuss.ai.google.dev/u/kieran_mcdowall)\
**Post date:** [October 3, 2023, 4:17am UTC](https://discuss.ai.google.dev/t/tensorflow-quantum-hybrid-models-tf-quantum/29613/1 "2023-10-03T04:17:32Z")

</div>

Hello,

I am trying to QCNN for MNIST classification equivalent to that built in [Torch Connector and Hybrid QNNs - Qiskit Machine Learning 0.7.2](https://qiskit.org/ecosystem/machine-learning/tutorials/05_torch_connector.html#Part-2:-MNIST-Classification,-Hybrid-QNNs)

I’m having problems trying to pass my quantum circuit built with cirq as a keras layer. Here’s what I have:

```auto
# Parameters that the classical NN will feed values into.
control_params = sympy.symbols('theta_1 theta_2 theta_3 theta_4')

# Create the parameterized circuit.
qubits = cirq.GridQubit.rect(2,1)
model_circuit = cirq.Circuit(
    cirq.rx(control_params[0])(qubits[0]),
    cirq.rx(control_params[1])(qubits[1]),
    cirq.rx(control_params[2])(qubits[0]),
    cirq.rx(control_params[3])(qubits[1]),
    cirq.CNOT(qubits[0],qubits[1]))

qlayer = tfq.convert_to_tensor([model_circuit])

SVGCircuit(model_circuit)

```

```auto
width = np.shape(x_train)[1]
height = np.shape(x_train)[2]

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(width, height, 1)), # Specify the input shape correctly
    tf.keras.layers.Conv2D(filters=2, kernel_size=5),
    tf.keras.layers.Conv2D(filters=16, kernel_size=5),
    tf.keras.layers.SpatialDropout2D(rate=0.2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(2, activation='relu'),
    tfq.layers.PQC(model_circuit, [cirq.Z(qubits[1])]) # Use qubits[1] for measurement
])

```

Which returns the error:

```auto
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[72], line 26
      2 height = np.shape(x_train)[2]
      7 # model = tf.keras.Sequential([
      8     
      9 # # tf.keras.layers.Input(shape=(()), dtype=tf.string), #, dtype=tf.string (28,28,1)
   (...)
     23     
     24 # ])
---> 26 model = tf.keras.Sequential([
     27 tf.keras.layers.Input(shape=(width, height, 1)), # Specify the input shape correctly
     28 tf.keras.layers.Conv2D(filters=2, kernel_size=5),
     29 tf.keras.layers.Conv2D(filters=16, kernel_size=5),
     30 tf.keras.layers.SpatialDropout2D(rate=0.2),
     31 tf.keras.layers.Flatten(),
     32 tf.keras.layers.Dense(64, activation='relu'),
     33 tf.keras.layers.Dense(2, activation='relu'),
     34 tfq.layers.PQC(model_circuit, [cirq.Z(qubits[1])]) # Use qubits[1] for measurement
     35 ])

File ~/.local/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py:530, in no_automatic_dependency_tracking.<locals>._method_wrapper(self, *args, **kwargs)
    528 self._self_setattr_tracking = False # pylint: disable=protected-access
    529 try:
--> 530 result = method(self, *args, **kwargs)
    531 finally:
    532 self._self_setattr_tracking = previous_value # pylint: disable=protected-access

File ~/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e: # pylint: disable=broad-except
     66 filtered_tb = _process_traceback_frames(e. __traceback__ )
---> 67 raise e.with_traceback(filtered_tb) from None
     68 finally:
     69 del filtered_tb

File ~/.local/lib/python3.8/site-packages/tensorflow/python/autograph/impl/api.py:699, in convert.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
    697 except Exception as e: # pylint:disable=broad-except
    698 if hasattr(e, 'ag_error_metadata'):
--> 699 raise e.ag_error_metadata.to_exception(e)
    700 else:
    701 raise

TypeError: Exception encountered when calling layer "pqc_38" (type PQC).

in user code:

    File "/home/zhk26714/.local/lib/python3.8/site-packages/tensorflow_quantum/python/layers/high_level/pqc.py", line 299, in call *
        model_appended = self._append_layer(inputs, append=tiled_up_model)
    File "/home/zhk26714/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler **
        raise e.with_traceback(filtered_tb) from None

    TypeError: Exception encountered when calling layer "add_circuit_40" (type AddCircuit).
    
    in user code:
    
        File "/home/zhk26714/.local/lib/python3.8/site-packages/tensorflow_quantum/python/layers/circuit_construction/elementary.py", line 128, in call *
            return tfq_utility_ops.append_circuit(inputs, append)
        File "/home/zhk26714/.local/lib/python3.8/site-packages/tensorflow_quantum/core/ops/tfq_utility_ops.py", line 65, in append_circuit *
            return UTILITY_OP_MODULE.tfq_append_circuit(programs, programs_to_append)
        File "<string>", line 73, in tfq_append_circuit **
            
    
        TypeError: Input 'programs' of 'TfqAppendCircuit' Op has type float32 that does not match expected type of string.
    
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None, 2), dtype=float32)
      • append=tf.Tensor(shape=(None,), dtype=string)
      • prepend=None

Call arguments received:
  • inputs=tf.Tensor(shape=(None, 2), dtype=float32)

```

The documentation on QCNNs using tensorflow is pretty limited ([Quantum Convolutional Neural Network &nbsp;|&nbsp; TensorFlow Quantum](https://www.tensorflow.org/quantum/tutorials/qcnn)) and instead here they are actually using the quantum layer to reduce dimensionality which I’m not trying to do.

Any help would be greatly appreciated.
