Hello! If applicable, put your complete code example down below. Make sure that your code:
- is 100% self-contained — someone can copy-paste exactly what is here and run it to
reproduce the behaviour you are observing - includes comments
# Put code here
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import pennylane as qml
# Perform label encoding on y_train
le = LabelEncoder()
# Load and preprocess the dataset
X = dataset.iloc[:, 0:-1]
y = dataset['Churn']
scaler = StandardScaler()
X = scaler.fit_transform(X)
y = le.fit_transform(y)
# Split the dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Perform PCA on the training and test sets
pca = PCA(n_components=2)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
n_classes = len(np.unique(y))
n_qubits = X_train.shape[1]
n_layers = 3
n_wires=2
print("X_train shape:", X_train.shape)
print("X_test shape:", X_test.shape)
print("y_train shape:", y_train.shape)
print("y_test shape:", y_test.shape)
print("n_classes:", n_classes)
print("n_qubits:", n_qubits)
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def quantum_model(inputs, weights):
reshaped_inputs = tf.reshape(inputs, (-1, n_qubits)) # Reshape inputs to (batch_size, n_qubits)
print("Shape of inputs:", reshaped_inputs.shape)
qml.templates.AngleEmbedding(reshaped_inputs, wires=range(n_qubits))
qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]
weight_shapes = {"weights": (n_layers, n_wires, 3)}
quantum_layer = qml.qnn.KerasLayer(quantum_model, weight_shapes=weight_shapes, output_dim=n_qubits)
classical_model = tf.keras.Sequential([
tf.keras.layers.Dense(4, activation='relu', input_dim=n_qubits, trainable=False),
tf.keras.layers.Dense(n_classes, activation='softmax')
])
# Build the hybrid model
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(4, activation='relu', input_dim=n_qubits, trainable=False),
quantum_layer,
classical_model
])
# Add print statements to check the shape of inputs at different stages
print("Shape of inputs before quantum layer:", model.layers[1].input_shape)
print("Shape of inputs after quantum layer:", model.layers[1].output_shape)
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=10)
loss, accuracy = model.evaluate(X_test, y_test)
print("Loss:", loss)
print("Accuracy:", accuracy)
If you want help with diagnosing an error, please put the full error message below:
# Put full error message here
X_train shape: (80, 2)
X_test shape: (20, 2)
y_train shape: (80,)
y_test shape: (20,)
n_classes: 2
n_qubits: 2
Shape of inputs before quantum layer: (None, 4)
Shape of inputs after quantum layer: (None, 2)
Epoch 1/3
Shape of inputs: (20, 2)
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-5-c909f42750cc> in <cell line: 71>()
69 model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
70
---> 71 history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=10)
72
73 loss, accuracy = model.evaluate(X_test, y_test)
7 frames
/usr/local/lib/python3.10/dist-packages/pennylane/math/utils.py in requires_grad(tensor, interface)
456 from tensorflow.python.eager.tape import should_record_backprop
457 except ImportError: # pragma: no cover
--> 458 from tensorflow.python.eager.tape import should_record as should_record_backprop
459
460 return should_record_backprop([tf.convert_to_tensor(tensor)])
ImportError: Exception encountered when calling layer 'keras_layer' (type KerasLayer).
cannot import name 'should_record' from 'tensorflow.python.eager.tape' (/usr/local/lib/python3.10/dist-packages/tensorflow/python/eager/tape.py)
Call arguments received by layer 'keras_layer' (type KerasLayer):
• inputs=tf.Tensor(shape=(10, 4), dtype=float32)
And, finally, make sure to include the versions of your packages. Specifically, show us the output of qml.about()
.
Name: PennyLane
Version: 0.31.0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: GitHub - PennyLaneAI/pennylane: PennyLane is a cross-platform Python library for differentiable programming of quantum computers. Train a quantum computer the same way as a neural network.
Author:
Author-email:
License: Apache License 2.0
Location: /usr/local/lib/python3.10/dist-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml
Required-by: PennyLane-Lightning, PennyLane-qiskit
Platform info: Linux-5.15.107±x86_64-with-glibc2.31
Python version: 3.10.12
Numpy version: 1.22.4
Scipy version: 1.10.0
Installed devices:
- default.gaussian (PennyLane-0.31.0)
- default.mixed (PennyLane-0.31.0)
- default.qubit (PennyLane-0.31.0)
- default.qubit.autograd (PennyLane-0.31.0)
- default.qubit.jax (PennyLane-0.31.0)
- default.qubit.tf (PennyLane-0.31.0)
- default.qubit.torch (PennyLane-0.31.0)
- default.qutrit (PennyLane-0.31.0)
- null.qubit (PennyLane-0.31.0)
- lightning.qubit (PennyLane-Lightning-0.31.0)
- qiskit.aer (PennyLane-qiskit-0.31.0)
- qiskit.basicaer (PennyLane-qiskit-0.31.0)
- qiskit.ibmq (PennyLane-qiskit-0.31.0)
- qiskit.ibmq.circuit_runner (PennyLane-qiskit-0.31.0)
- qiskit.ibmq.sampler (PennyLane-qiskit-0.31.0)
- qiskit.remote (PennyLane-qiskit-0.31.0)
Tensorflow version: 2.13.0
PennyLane version: 0.31.0