When I tried to hybrid quantum optics neural network with classical one, the Error raised, it says that: QuantumFunctionError: Continuous and discrete operations are not allowed in the same quantum circuit.
But I don’t know why, could you please help me modify this incorrect code? My previous codes are as follows:
import tensorflow as tf
import pennylane as qml
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons
# Set random seeds
np.random.seed(42)
tf.random.set_seed(42)
X, y = make_moons(n_samples=200, noise=0.1)
y_hot = tf.keras.utils.to_categorical(y, num_classes=2) # one-hot encoded labels
c = ["#1f77b4" if y_ == 0 else "#ff7f0e" for y_ in y] # colours for each class
plt.axis("off")
plt.scatter(X[:, 0], X[:, 1], c=c)
plt.show()
tf.keras.backend.set_floatx('float64')
layer_1 = tf.keras.layers.Dense(2, activation="relu")
layer_2 = tf.keras.layers.Dense(2, activation="softmax")
model = tf.keras.Sequential([layer_1, layer_2])
model.compile(loss="mae")
n_qubits = 2
n_layers = 6
dev = qml.device("default.qubit", wires=n_qubits)
def layer(theta, phi, wires):
M = len(wires)
phi_nonlinear = np.pi / 2
qml.templates.Interferometer(
theta, phi, np.zeros(M), wires=wires, mesh="rectangular", beamsplitter="pennylane"
)
for i in wires:
qml.Kerr(phi_nonlinear, wires=i)
@qml.qnode(dev)
def quantum_neural_net(inputs, weights):
wires = list(range(len(inputs)))
# Encode input x into a sequence of quantum fock states
qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
# "layer" subcircuits
for i, v in enumerate(weights):
layer(v[: len(v) // 2], v[len(v) // 2 :], wires)
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
M = 2
num_variables_per_layer = M * (M - 1)
weight_shapes = {"weights": (n_layers, num_variables_per_layer)}
qlayer = qml.qnn.KerasLayer(quantum_neural_net, weight_shapes, output_dim=n_qubits)
clayer_1 = tf.keras.layers.Dense(2)
clayer_2 = tf.keras.layers.Dense(2, activation="softmax")
model = tf.keras.models.Sequential([clayer_1, qlayer, clayer_2])
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="mae", metrics=["accuracy"])
fitting = model.fit(X, y_hot, epochs=6, batch_size=5, validation_split=0.25, verbose=2)