import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from pennylane.qnn.keras import KerasLayer
重定向stdout以捕获打印输出
class Tee(object):
def init(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
print("脚本执行完成。查看 'output.log' 获取打印输出,查看当前目录获取保存的图表。")
代码出现报错Traceback (most recent call last):
File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane - NewFacility\examples\yuanweihua_renew_usesoftmax_NQNN_newFacility.py", line 287, in
model = QuantumNeuralNetwork(
File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane - NewFacility\examples\yuanweihua_renew_usesoftmax_NQNN_newFacility.py", line 256, in init
self.quantum_layer = QuantumNeuralNetworkLayer(n_qubits, n_layers, num_classes)
File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane - NewFacility\examples\yuanweihua_renew_usesoftmax_NQNN_newFacility.py", line 234, in init
self.quantum_layer = KerasLayer(
File "C:\Users\liuwenjing.conda\envs\pennylane3\lib\site-packages\pennylane\qnn\keras.py", line 228, in init
self._signature_validation(qnode, weight_shapes)
File "C:\Users\liuwenjing.conda\envs\pennylane3\lib\site-packages\pennylane\qnn\keras.py", line 261, in _signature_validation
raise ValueError(
ValueError: inputs argument should not have its dimension specified in weight_shapes
Process finished with exit code 1
The error you're encountering is due to the incorrect inclusion of the inputs argument in the weight_shapes dictionary when initializing the KerasLayer. In the context of KerasLayer, only trainable parameters (weights) should be specified in weight_shapes. The inputs should be treated as data inputs, not as weights to be learned during training.
Here's a step-by-step guide to resolve the issue:
1. Remove inputs from weight_shapes
The weight_shapes dictionary should only include the trainable parameters of your quantum circuit. In your case, encoding_weights and rot_weights are the parameters that the model will learn. inputs should not be included here.
Since inputs are now treated as data inputs rather than weights, you need to modify your QNode to accept inputs separately. One effective approach is to encapsulate the data input encoding within the QNode itself without treating it as a trainable parameter.
You need to update the QuantumNeuralNetworkLayer class to properly handle input data and pass it to the QNode. Since KerasLayer will no longer receive inputs as a weight, you can modify the call method to accept inputs and pass them alongside the trainable weights.
Updated QuantumNeuralNetworkLayer:
python
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
def __init__(self, n_qubits, n_layers, num_classes, **kwargs):
super(QuantumNeuralNetworkLayer, self).__init__(**kwargs)
self.n_qubits = n_qubits
self.n_layers = n_layers
self.num_classes = num_classes
# Define Quantum Layer without 'inputs' in weight_shapes
self.quantum_layer = KerasLayer(
quantum_neural_network_for_keras,
weight_shapes={
"encoding_weights": (3, n_layers, 4),
"rot_weights": (n_layers, n_qubits, 3)
},
output_dim=3 # 根据测量结果数量设置输出维度
)
def call(self, inputs):
# The KerasLayer expects only the weights, so we need to create a combined input.
# One way is to concatenate the model inputs with the QNN weights.
# However, KerasLayer does not natively support additional inputs.
# Instead, you can modify the QNode to internally handle the data.
# Here, we can use a workaround by modifying the quantum_node to accept inputs as a separate parameter.
# Since KerasLayer doesn't support additional data inputs directly,
# we need to create a custom approach. One approach is to create a custom QNode that incorporates inputs.
# Alternatively, you might need to use separate encoding through classical layers.
# For simplicity, let's assume the inputs are part of the QNode's callable by using
# broadcasting or other TensorFlow operations within the QNode.
# Here, we'll pass inputs as an additional argument after unpacking weights
# This requires modifying the QNode to accept inputs as the last argument
return self.quantum_layer([inputs] + self.quantum_layer.trainable_weights)
Note: The above call method is a conceptual workaround. In practice, integrating data inputs with KerasLayer can be more involved. You might need to refactor your model architecture to ensure that the quantum layer receives both the data inputs and the trainable weights correctly.
4. Refactor the Model to Handle Data Inputs Appropriately
Given the complexities of integrating data inputs with KerasLayer, consider the following alternative approach:
Separate Encoding and Quantum Layers: Use classical layers to encode your data into a suitable format before passing it to the quantum layer. This way, the quantum layer only handles trainable weights without directly taking data inputs.
Use Functional API: Leverage Keras' Functional API to manage the flow of data through classical encoding layers and then into the quantum layer.
Finally, make sure that during training, your data flows correctly through the classical encoding layers (if any), into the quantum layer, and then through any subsequent classical layers. This ensures that inputs are handled as data and not as trainable parameters.
6. Complete Modified Code Example
Here's a concise version of the necessary modifications:
python
# ... [imports and utility functions as in your original script] ...
# Modify the QNode without 'inputs' as a weight
@qml.qnode(dev, interface='tf', diff_method='parameter-shift')
def quantum_neural_network_for_keras(encoding_weights, rot_weights, inputs):
# [Quantum circuit implementation using inputs]
# Ensure inputs are used internally for encoding and not treated as weights
# ... [rest of your QNode implementation] ...
return results
# Update QuantumNeuralNetworkLayer without 'inputs' in weight_shapes
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
def __init__(self, n_qubits, n_layers, num_classes, **kwargs):
super(QuantumNeuralNetworkLayer, self).__init__(**kwargs)
self.quantum_layer = KerasLayer(
quantum_neural_network_for_keras,
weight_shapes={
"encoding_weights": (3, n_layers, 4),
"rot_weights": (n_layers, n_qubits, 3)
},
output_dim=3
)
def call(self, inputs):
# Pass inputs separately if possible
return self.quantum_layer([inputs])
# ... [rest of your model and training code] ...
if __name__ == "__main__":
# ... [data loading and preprocessing] ...
model = QuantumNeuralNetwork(
n_qubits=n_qubits,
n_layers=n_layers,
num_classes=num_classes
)
# ... [optimizer and compilation] ...
# Ensure the model architecture aligns with the updated QuantumNeuralNetworkLayer
# ... [training and evaluation] ...
7. Consider Alternative Approaches
If integrating inputs directly within the KerasLayer continues to pose challenges, consider alternative methods such as:
Hybrid Models: Combine classical and quantum layers where classical layers handle data encoding before passing to quantum layers.
Custom Layers: Create custom Keras layers that manage the flow of data and quantum operations more seamlessly.
Pennylane Tutorials: Refer to Pennylane's QNN with Keras Tutorial for more detailed examples and best practices.
8. Final Notes
Model Complexity: Ensure that the number of qubits and layers aligns with your computational resources. More qubits and layers increase computational demands.
Debugging: After making these changes, monitor the model's behavior to ensure that data flows correctly and that the quantum layer interacts as expected with other parts of the model.
By following these steps, you should be able to resolve the ValueError related to the inputs argument and successfully train your Quantum Neural Network on the Iris dataset.