I'm trying to use Cirq with TensorFlow Quantum to simulate a variational quantum classifier. There's a tutorial on the TFQ website on building a quantum neural network to classify a simplified version of MNIST, which I've been using for reference.
The classifier that I'm building requires building my own custom gates.
After encoding the data as quantum circuits, the next step is to convert these Cirq circuits to tensors using
I've found that this function works fine for any built-in Cirq gates, but when I pass my own custom gate as the argument, I get
ValueError: Cannot serialize op <__main__.Custom_Gate object at...
Here's some watered down code that gives the gist of my attempts:
def simple_func(x): return x*cirq.z class Custom_Gate(cirq.Gate): def __init__(self, x, n): self.x = x self.n = n def _unitary_(self): return simple_func(self.x) def _num_qubits_(self): return self.n def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs'): return ['U'] x = 3 n = 1 U = Custom_Gate(x, n) q0 = cirq.GridQubit(0, 0) test_circuit = cirq.Circuit() test_circuit.append(U.on(q0)) SVGCircuit(test_circuit) tfq.convert_to_tensor([test_circuit])
Am I making a mistake somewhere? Or does
tfq.convert_to_tensor just not work for custom gates?