from future import print_function
import pennylane as qml
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense # 使用公共 API 导入
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from sklearn.metrics import roc_curve, auc
上述代码报错模型摘要:
Traceback (most recent call last):
File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane\examples\yuanweihua.py", line 406, in
model.summary() # 打印模型摘要
File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane\examples\yuanweihua.py", line 338, in summary
outputs = self.call(inputs)
File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane\examples\yuanweihua.py", line 332, in call
return self.dense(x)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1044, in call
outputs = call_fn(inputs, *args, **kwargs)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\keras\layers\core.py", line 1239, in call
outputs = gen_math_ops.MatMul(a=inputs, b=self.kernel)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\util\tf_export.py", line 412, in wrapper
return f(**kwargs)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 6021, in mat_mul
return mat_mul_eager_fallback(
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 6056, in mat_mul_eager_fallback
_attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ])
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\eager\execute.py", line 256, in args_to_matching_eager
tensor = ops.convert_to_tensor(t, ctx=ctx)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\profiler\trace.py", line 183, in wrapped
return func(*args, **kwargs)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\framework\ops.py", line 1638, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\framework\constant_op.py", line 343, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\framework\constant_op.py", line 267, in constant
return _constant_impl(value, dtype, shape, name, verify_shape=False,
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\framework\constant_op.py", line 279, in _constant_impl
return _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\framework\constant_op.py", line 304, in _constant_eager_impl
t = convert_to_eager_tensor(value, ctx, dtype)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\tensorflow\python\framework\constant_op.py", line 102, in convert_to_eager_tensor
return ops.EagerTensor(value, ctx.device_name, dtype)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\keras\engine\keras_tensor.py", line 283, in array
raise TypeError(
TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(None, 3), dtype=tf.float32, name=None), description="created by layer 'keras_layer'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as tf.cond, tf.function, gradient tapes, or tf.map_fn. Keras Functional model construction only supports TF API calls that do support dispatching, such as tf.math.add or tf.reshape. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer call and calling that layer on this symbolic input/output.
我只想要添加输出量子神经网络的详细信息以及图象的内容,其余内容不做任何更改
The error you're encountering is due to using the tf.keras.Model subclassing approach in a way that's not fully compatible with Keras, especially in combination with custom layers like KerasLayer from PennyLane. When you try to call model.summary(), it internally requires a properly constructed Keras model.
To fix this issue and enable printing the model summary and quantum circuit diagram, you should restructure your code to build the model using the Keras Functional API. This approach is fully compatible with Keras' built-in methods like summary() and allows for seamless integration of custom layers like KerasLayer.
Here's how you can modify your code:
Remove Subclassing of tf.keras.Model: Instead of subclassing tf.keras.Model, define a regular Python class that encapsulates your model components.
Build the Model Using the Functional API: Inside your class, use the Keras Functional API to build the model. This involves defining the inputs, passing them through your layers, and creating a Keras Model instance.
Delegate Model Methods: Implement methods in your class that delegate calls to your internal model instance, such as compile(), fit(), evaluate(), and summary().
Below is your modified code with the necessary changes applied:
python
from __future__ import print_function
import pennylane as qml
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense # Adjusted import statement
from tensorflow.keras.utils import plot_model
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from sklearn.metrics import roc_curve, auc
# Import necessary modules
from pennylane.qnn.keras import KerasLayer # Already imported
def plot_history(history):
plt.figure(figsize=(12, 5))
# Plot training and validation accuracy
plt.subplot(121)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
# Plot training and validation loss
plt.subplot(122)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.tight_layout()
plt.show()
def plot_roc_curve(y_test, y_pred):
n_classes = y_test.shape[1]
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_pred[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_pred.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'.format(roc_auc["micro"]))
for i in range(n_classes):
plt.plot(fpr[i], tpr[i],
label='ROC curve of class {0} (area = {1:0.2f})'.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend(loc="lower right")
plt.show()
def calculate_accuracy_fluctuation(history):
# Get validation accuracies for each epoch
val_accuracies = history.history['val_accuracy']
# Calculate mean accuracy
mean_accuracy = np.mean(val_accuracies)
# Calculate fluctuation (absolute deviation from mean)
fluctuation = np.sum(np.abs(val_accuracies - mean_accuracy))
return mean_accuracy, fluctuation
# Define the quantum neural network model
class QuantumNeuralNetwork:
def __init__(self, n_qubits, n_layers, num_classes):
self.n_qubits = n_qubits
self.n_layers = n_layers
self.num_classes = num_classes
# Define the quantum device
self.dev = qml.device('default.qubit', wires=self.n_qubits)
# Define the quantum circuit
@qml.qnode(self.dev, interface='tf', diff_method='backprop')
def quantum_circuit(inputs, weights):
qml.templates.AngleEmbedding(inputs, wires=range(self.n_qubits))
qml.templates.StronglyEntanglingLayers(weights, wires=range(self.n_qubits))
expvals = [qml.expval(qml.PauliZ(i)) for i in range(self.num_classes)]
return expvals # Return a list of measurement values
self.quantum_circuit = quantum_circuit
# Define weight shapes
weight_shapes = {"weights": (self.n_layers, self.n_qubits, 3)}
# Wrap the quantum circuit as a Keras layer
qnn_layer = KerasLayer(
self.quantum_circuit,
weight_shapes,
output_dim=self.num_classes, # Output dimension matches number of measurements
dtype=tf.float32,
name='quantum_layer' # Add a name for clarity
)
# Define classical neural network layer
dense_layer = Dense(self.num_classes, activation='softmax', name='output_layer')
# Build the model using the Keras Functional API
inputs = tf.keras.Input(shape=(self.n_qubits,), name='input_layer')
x = qnn_layer(inputs)
outputs = dense_layer(x)
self.model = tf.keras.Model(inputs=inputs, outputs=outputs)
# Delegate methods to the internal Keras model
def summary(self):
return self.model.summary()
def compile(self, *args, **kwargs):
return self.model.compile(*args, **kwargs)
def fit(self, *args, **kwargs):
return self.model.fit(*args, **kwargs)
def evaluate(self, *args, **kwargs):
return self.model.evaluate(*args, **kwargs)
def predict(self, *args, **kwargs):
return self.model.predict(*args, **kwargs)
# Add a method to print the quantum circuit
def print_quantum_circuit(self):
sample_inputs = tf.zeros((self.n_qubits,))
sample_weights = {
"weights": tf.zeros((self.n_layers, self.n_qubits, 3))
}
print(qml.draw(self.quantum_circuit)(sample_inputs, sample_weights["weights"]))
# Add a method to plot and save the model diagram
def plot_model(self, filename='model.png'):
tf.keras.utils.plot_model(self.model, to_file=filename, show_shapes=True)
print(f"Model diagram saved to {filename}")
if __name__ == "__main__":
# Ensure the `get_parser` function is correctly implemented
parser = get_parser("训练模型于鸢尾花数据集")
args = parser.parse_args()
# Load and preprocess the Iris dataset
iris = load_iris()
X = iris['data']
y = iris['target'].reshape(-1, 1)
# One-hot encode the labels
encoder = OneHotEncoder(sparse_output=False)
y = encoder.fit_transform(y)
# Split the dataset
x_train, x_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=116
)
# Define hyperparameters
learning_rate = 0.1
epochs = 100
batch_size = 8
num_classes = 3 # Three classes in the Iris dataset
n_qubits = 4 # Number of qubits (should match the number of features)
n_layers = 2
# Create the model
model = QuantumNeuralNetwork(
n_qubits=n_qubits,
n_layers=n_layers,
num_classes=num_classes
)
# Compile the model
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Function to check if the model contains a quantum layer
def is_quantum_model(model):
for layer in model.model.layers: # Access the internal model
if isinstance(layer, KerasLayer):
return True
return False
# Use the function to check if the model contains a quantum layer
if is_quantum_model(model):
print("模型包含量子神经网络(QNN)层。")
else:
print("模型不包含量子神经网络(QNN)层。")
# **Print the model summary and quantum circuit before training**
print("\n模型摘要:")
model.summary() # Print the model summary
# Optionally, save the model diagram to a file
model.plot_model('quantum_model.png')
print("\n量子电路图:")
model.print_quantum_circuit() # Print the quantum circuit diagram
# Train the model using standard Keras training
history = model.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test)
)
# Evaluate the model
score = model.evaluate(x_test, y_test, verbose=0)
print('测试损失:', score[0])
print('测试准确率:', score[1])
# Calculate and display accuracy fluctuation
mean_accuracy, fluctuation = calculate_accuracy_fluctuation(history)
print('平均验证准确率:', mean_accuracy)
print('准确率波动:', fluctuation)
# Plot training history
plot_history(history)
# Predict probabilities
y_pred = model.predict(x_test)
# Plot ROC curve
plot_roc_curve(y_test, y_pred)
Explanation of Changes:
Removed Subclassing: The QuantumNeuralNetwork class no longer subclasses tf.keras.Model. Instead, it acts as a wrapper around a Keras Model instance (self.model).
Used Keras Functional API: Inside __init__, the model is built using the Functional API, which is fully compatible with Keras' built-in methods like summary().
Delegated Methods: Methods like compile(), fit(), evaluate(), and predict() are delegated to self.model.
Printed Model Summary: The summary() method now calls self.model.summary() directly, allowing you to print the model summary without errors.
Added Model Plotting: Included a plot_model() method to visualize the model architecture and save it to an image file.
Adjusted the is_quantum_model() Function: Updated to access the internal model layers (model.model.layers).
Adjusted Imports: Used tensorflow.keras.layers.Dense and tensorflow.keras.utils.plot_model for compatibility.
Result:
You can now print the detailed model summary using model.summary().
The quantum circuit diagram can be printed using model.print_quantum_circuit().
The model architecture can be visualized and saved as an image file using model.plot_model('quantum_model.png').
The rest of the code remains unchanged, and the model should train and evaluate as before.
Please make sure you have the necessary packages installed (like pydot and graphviz) to use plot_model() and render the model diagram.
Note: This restructuring ensures that your quantum neural network model fully integrates with Keras' functionalities, allowing you to explore and visualize your model's architecture and quantum components without encountering the previous errors.