from future import printfunction import pennylane as qml import tensorflow as tf import…
- User
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
导入需要的模块
import pennylane as qml from pennylane.qnn.keras import KerasLayer def plot_history(history): plt.figure(figsize=(12, 5))
# 绘制训练集和验证集的准确率 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') # 绘制训练集和验证集的损失 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): # 获取每个 epoch 的验证集准确率 val_accuracies = history.history['val_accuracy']
# 计算平均准确率 mean_accuracy = np.mean(val_accuracies) # 计算每个 epoch 的准确率波动(与均值的绝对差值) fluctuation = np.sum(np.abs(val_accuracies - mean_accuracy)) return mean_accuracy, fluctuation定义量子神经网络模型
class QuantumNeuralNetwork(tf.keras.Model): def init(self, n_qubits, n_layers, num_classes): super(QuantumNeuralNetwork, self).init() self.n_qubits = n_qubits self.n_layers = n_layers self.num_classes = num_classes
# 定义量子设备 self.dev = qml.device('default.qubit', wires=self.n_qubits) # 定义量子电路 @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 # 直接返回测量值列表 self.quantum_circuit = quantum_circuit # 定义权重形状 weight_shapes = {"weights": (self.n_layers, self.n_qubits, 3)} # 将量子电路包装为 Keras 层 self.qnn_layer = qml.qnn.KerasLayer( self.quantum_circuit, weight_shapes, output_dim=self.num_classes, # 输出维度与测量值数量一致 dtype=tf.float32 ) # 定义经典神经网络层 self.dense = Dense(self.num_classes, activation='softmax') def call(self, inputs): x = self.qnn_layer(inputs) return self.dense(x)if name == "main": # 确保
get_parser函数的正确实现 parser = get_parser("训练模型于鸢尾花数据集") args = parser.parse_args()# 加载并预处理鸢尾花数据集 iris = load_iris() X = iris['data'] y = iris['target'].reshape(-1, 1) # One-hot 编码标签 encoder = OneHotEncoder(sparse_output=False) y = encoder.fit_transform(y) # 划分数据集 x_train, x_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=116 ) # 定义超参数 learning_rate = 0.1 epochs = 100 batch_size = 8 num_classes = 3 # 鸢尾花数据集有 3 个类别 n_qubits = 4 # 量子比特数量(应与特征数量匹配) n_layers = 2 # 创建模型 model = QuantumNeuralNetwork( n_qubits=n_qubits, n_layers=n_layers, num_classes=num_classes ) # 编译模型 model.compile( optimizer=tf.keras.optimizers.SGD(lr=learning_rate), # 使用公共 API 导入的 Adam loss='categorical_crossentropy', metrics=['accuracy'] ) # 添加函数来判断是否存在量子层 def is_quantum_model(model): for layer in model.layers: if isinstance(layer, KerasLayer): return True return False # 使用该函数检查模型是否包含量子层 if is_quantum_model(model): print("模型包含量子神经网络(QNN)层。") else: print("模型不包含量子神经网络(QNN)层。") # 根据是否启用重要性采样选择训练方法 if args.importance_training: # 使用重要性采样进行自定义训练 wrapped_model = ConstantTimeImportanceTraining(model) history = wrapped_model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test) ) else: # 使用标准的 Keras 训练 history = model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test) ) # 评估模型 score = model.evaluate(x_test, y_test, verbose=0) print('测试损失:', score[0]) print('测试准确率:', score[1]) # 计算并显示准确率波动 mean_accuracy, fluctuation = calculate_accuracy_fluctuation(history) print('平均验证准确率:', mean_accuracy) print('准确率波动:', fluctuation) # 绘制训练历史 plot_history(history) # 预测概率 y_pred = model.predict(x_test) # 绘制 ROC 曲线 plot_roc_curve(y_test, y_pred)如果我想使得上述代码能够打印出量子神经网络的全部信息以及图象,应该如何对代码进行修改
- Assistant
To print out all the information of the quantum neural network and display images in your code, you'll need to make several modifications:
-
Print the Model Summary and Trainable Variables: Since you are using a subclassed
tf.keras.Model, themodel.summary()might not work directly. However, you can still print out the trainable variables and other relevant information. -
Visualize the Quantum Circuit: Use PennyLane's
qml.draw()andqml.draw_mpl()functions to print and plot the quantum circuit. -
Ensure Plots are Displayed: Make sure that
plt.show()is called in your plotting functions and that your environment is configured to display plots.
Here's how you can modify your code:
1. Modify the
QuantumNeuralNetworkClass:Add methods to visualize and plot the quantum circuit. Also, override the
buildmethod to initialize layers properly so that you can get a summary.class QuantumNeuralNetwork(tf.keras.Model): def __init__(self, n_qubits, n_layers, num_classes): super(QuantumNeuralNetwork, self).__init__() self.n_qubits = n_qubits self.n_layers = n_layers self.num_classes = num_classes # Define quantum device self.dev = qml.device('default.qubit', wires=self.n_qubits) # Define 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 list of expectation 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 self.qnn_layer = qml.qnn.KerasLayer( self.quantum_circuit, weight_shapes, output_dim=self.num_classes, dtype=tf.float32 ) # Define classical neural network layer self.dense = Dense(self.num_classes, activation='softmax') def call(self, inputs): x = self.qnn_layer(inputs) return self.dense(x) def build(self, input_shape): # This overrides the build method to initialize the layers properly super(QuantumNeuralNetwork, self).build(input_shape) def visualize_circuit(self, inputs): # Visualize the quantum circuit using qml.draw qnode_draw = qml.draw(self.quantum_circuit) # Use random weights for visualization weights_shape = (self.n_layers, self.n_qubits, 3) weights = np.random.rand(*weights_shape) print(qnode_draw(inputs, weights)) def plot_circuit(self, inputs): # Plot the quantum circuit using qml.draw_mpl weights_shape = (self.n_layers, self.n_qubits, 3) weights = np.random.rand(*weights_shape) fig, ax = qml.draw_mpl(self.quantum_circuit)(inputs, weights) plt.show()2. Modify the Main Part of Your Code:
After creating the model, you can build it, print the summary, visualize the circuit, and plot the circuit.
if __name__ == "__main__": # ... existing code ... # Create the model model = QuantumNeuralNetwork( n_qubits=n_qubits, n_layers=n_layers, num_classes=num_classes ) # Build the model to initialize weights and layers model.build(input_shape=(None, x_train.shape[1])) # Print the model summary print("Model Summary:") try: model.summary() except ValueError as e: print("Cannot print summary for subclassed model without input shape. Error:", e) # Print the model's trainable variables print("\nModel's Trainable Variables:") for var in model.trainable_variables: print(f"{var.name}: shape={var.shape}") # Visualize and plot the quantum circuit using a sample input sample_input = x_train[0] # Ensure the sample input has the correct shape sample_input = np.expand_dims(sample_input, axis=0) print("\nQuantum Circuit Visualization:") model.visualize_circuit(sample_input) print("\nQuantum Circuit Plot:") model.plot_circuit(sample_input) # ... remaining code ...3. Ensure Plots are Displayed and Save Them if Necessary:
Adjust your plotting functions to both show and save the plots. This is useful if you're running the code in an environment that doesn't display plots automatically (like a script).
def plot_history(history): plt.figure(figsize=(12, 5)) # Plot training & validation accuracy values 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 & validation loss values 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.savefig('training_history.png') plt.show() def plot_roc_curve(y_test, y_pred): # ... existing code ... plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc="lower right") plt.savefig('roc_curve.png') plt.show()Note: Saving the plots ensures that you have a copy even if
plt.show()doesn't display them due to environment constraints.4. Add Any Additional Prints as Needed:
If you need more detailed information about weights or layers, you can add more print statements as needed.
# Print the weights of the quantum layer print("\nQuantum Layer Weights:") quantum_weights = model.qnn_layer.get_weights() for i, weight in enumerate(quantum_weights): print(f"Weight {i}: shape={weight.shape}") print(weight)Full Modified Code Snippet:
Below is the complete modified code that incorporates all the changes:
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 # Use public API from example_utils import get_parser from importance_sampling.training import ConstantTimeImportanceTraining from sklearn.metrics import roc_curve, auc import pennylane as qml from pennylane.qnn.keras import KerasLayer def plot_history(history): plt.figure(figsize=(12, 5)) # Plot training & validation accuracy values 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 & validation loss values 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.savefig('training_history.png') 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.savefig('roc_curve.png') 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 (sum of absolute differences from the mean) fluctuation = np.sum(np.abs(val_accuracies - mean_accuracy)) return mean_accuracy, fluctuation # Define the quantum neural network model class QuantumNeuralNetwork(tf.keras.Model): def __init__(self, n_qubits, n_layers, num_classes): super(QuantumNeuralNetwork, self).__init__() self.n_qubits = n_qubits self.n_layers = n_layers self.num_classes = num_classes # Define quantum device self.dev = qml.device('default.qubit', wires=self.n_qubits) # Define 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 list of expectation 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 self.qnn_layer = qml.qnn.KerasLayer( self.quantum_circuit, weight_shapes, output_dim=self.num_classes, # Output dimension matches number of measurements dtype=tf.float32 ) # Define classical neural network layer self.dense = Dense(self.num_classes, activation='softmax') def call(self, inputs): x = self.qnn_layer(inputs) return self.dense(x) def build(self, input_shape): # This overrides the build method to initialize the layers properly super(QuantumNeuralNetwork, self).build(input_shape) def visualize_circuit(self, inputs): # Visualize the quantum circuit using qml.draw qnode_draw = qml.draw(self.quantum_circuit) # Use random weights for visualization weights_shape = (self.n_layers, self.n_qubits, 3) weights = np.random.rand(*weights_shape) print(qnode_draw(inputs, weights)) def plot_circuit(self, inputs): # Plot the quantum circuit using qml.draw_mpl weights_shape = (self.n_layers, self.n_qubits, 3) weights = np.random.rand(*weights_shape) fig, ax = qml.draw_mpl(self.quantum_circuit)(inputs, weights) plt.show() if __name__ == "__main__": # Ensure `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 # Iris dataset has 3 classes 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 ) # Build the model to initialize weights and layers model.build(input_shape=(None, x_train.shape[1])) # Print the model summary print("Model Summary:") try: model.summary() except ValueError as e: print("Cannot print summary for subclassed model without input shape. Error:", e) # Print the model's trainable variables print("\nModel's Trainable Variables:") for var in model.trainable_variables: print(f"{var.name}: shape={var.shape}") # Visualize and plot the quantum circuit using a sample input sample_input = x_train[0] # Ensure the sample input has the correct shape sample_input = np.expand_dims(sample_input, axis=0) print("\nQuantum Circuit Visualization:") model.visualize_circuit(sample_input) print("\nQuantum Circuit Plot:") model.plot_circuit(sample_input) # 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.layers: if isinstance(layer, KerasLayer): return True return False # Check if the model contains a quantum layer if is_quantum_model(model): print("\n模型包含量子神经网络(QNN)层。") else: print("\n模型不包含量子神经网络(QNN)层。") # Choose training method based on importance sampling if args.importance_training: # Use custom training with importance sampling wrapped_model = ConstantTimeImportanceTraining(model) history = wrapped_model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test) ) else: # Use 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('\n测试损失:', 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)Additional Notes:
- Environment Configuration: Ensure that your environment (e.g., Jupyter notebook, Python script, or IDE) is configured to display plots. If you're running a script and the plots are not showing up, they might be saved to the current directory due to
plt.savefig(). - Quantum Circuit Visualization: The visualized circuit uses random weights for demonstration purposes. During actual inference, the trained weights would be used.
- Model Summary: Subclassed models in TensorFlow may not provide a detailed summary because the layers are defined in the
callmethod. The trainable variables provide detailed information about the parameters. - Error Handling: In the
model.summary(), an exception is caught in case the model hasn't been built properly. Adjustments can be made based on your TensorFlow version.
By making these modifications, your code will print out comprehensive information about the quantum neural network and display the corresponding images and plots.
-