您遇到的错误是由于模型的输出形状与标签的形状不匹配引起的。具体来说,错误信息显示模型输出的形状为 [2, 3],而标签的形状为 [8, 3]。这通常意味着模型在处理批次时出现了问题,导致输出的批次大小与输入数据的批次大小不一致。
让我们详细分析您的代码并找出问题所在:
错误信息摘要
logits_size=[2,3] labels_size=[8,3]
这表示模型在一个训练步骤中输出了大小为 [2, 3] 的张量,而实际的标签大小为 [8, 3]。理想情况下,输出的批次大小应与标签的批次大小一致,即 [8, 3]。
问题根源
问题出在 QuantumNeuralNetworkLayer 自定义层中的 call 方法。具体来说,您在处理量子神经网络的输出时对形状进行了错误的重塑(reshape),导致批次维度被错误地处理。
以下是相关代码段:
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
# ... 省略部分代码 ...
def call(self, inputs):
def apply_qnode(x):
x = tf.cast(x, dtype=tf.float64)
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
return tf.cast(result, dtype=tf.float32)
# Reshape inputs to be compatible with tf.map_fn
inputs = tf.reshape(inputs, (-1, self.n_features))
outputs = tf.map_fn(
apply_qnode,
inputs,
fn_output_signature=tf.float32
)
# 错误的 reshape 导致批次维度不正确
return tf.reshape(outputs, (-1, self.n_layers))
在上述代码中,tf.map_fn 已经将每个批次样本映射到量子神经网络,并返回一个形状为 [batch_size, self.n_layers] 的张量。然后,您再次对输出进行了 reshape:
return tf.reshape(outputs, (-1, self.n_layers))
这里的 -1 会自动推断出一个维度,但由于 outputs 已经是 [batch_size, self.n_layers],再次 reshape 可能会导致批次维度被错误地合并或改变。
解决方法
为了确保模型的输出形状与标签形状一致,您需要移除或修改错误的 reshape 操作。具体修改如下:
-
移除不必要的 reshape:
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
# ... 省略部分代码 ...
def call(self, inputs):
def apply_qnode(x):
x = tf.cast(x, dtype=tf.float64)
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
return tf.cast(result, dtype=tf.float32)
# Reshape inputs to be compatible with tf.map_fn
inputs = tf.reshape(inputs, (-1, self.n_features))
outputs = tf.map_fn(
apply_qnode,
inputs,
fn_output_signature=tf.float32
)
# 移除错误的 reshape
return outputs
-
确保 outputs 的形状保持为 [batch_size, self.n_layers]:
这样,经过多个量子层的堆叠后,最终的输出形状应该是 [batch_size, num_classes],这与标签的形状 [batch_size, num_classes] 是匹配的。
完整修正后的代码
以下是包含上述修正的完整代码片段:
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.keras.layers import Dense # 推荐使用 keras.layers 直接导入
# Redirect stdout to capture print outputs
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()
output_file = open('output.log', 'w', encoding='utf-8')
original_stdout = sys.stdout
sys.stdout = Tee(sys.stdout, output_file)
def save_plot(fig, filename):
fig.savefig(filename)
plt.close(fig)
def plot_history(history):
# Plot training and validation accuracy
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['accuracy'])
ax.plot(history.history['val_accuracy'])
ax.set_title('Model Accuracy')
ax.set_ylabel('Accuracy')
ax.set_xlabel('Epoch')
ax.legend(['Train', 'Validation'], loc='upper left')
save_plot(fig, 'accuracy_plot.png')
# Plot training and validation loss
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['loss'])
ax.plot(history.history['val_loss'])
ax.set_title('Model Loss')
ax.set_ylabel('Loss')
ax.set_xlabel('Epoch')
ax.legend(['Train', 'Validation'], loc='upper left')
save_plot(fig, 'loss_plot.png')
# Define the quantum device with 11 qubits
dev = qml.device("default.qubit", wires=11)
@qml.qnode(dev, interface='tf', diff_method='backprop')
def quantum_neural_network(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
num_layers = encoding_weights.shape[0]
# Define quantum qubit indices
data_qubits_per_layer = []
swap_control_qubits = []
qubit_idx = 2 # Start from the 3rd qubit
for layer in range(num_layers):
data_qubits = [qubit_idx, qubit_idx + 1] # 2 qubits per layer
qubit_idx += 2
data_qubits_per_layer.append(data_qubits)
swap_control_qubit = qubit_idx
swap_control_qubits.append(swap_control_qubit)
qubit_idx += 1 # Add 1 for the swap control qubit
# Process each layer
for layer_idx, data_qubits in enumerate(data_qubits_per_layer):
swap_control_qubit = swap_control_qubits[layer_idx]
# Encode each feature
for cv_idx, cv in enumerate([[0, 0], [0, 1], [1, 0], [1, 1]]):
feature_value = inputs[cv_idx]
angle_weight = encoding_weights[layer_idx, cv_idx]
# Flip control qubits
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# Apply controlled RY gates with feature values and weights
for data_qubit in data_qubits:
qml.ctrl(qml.RY, control=control_qubits)(feature_value, wires=data_qubit)
qml.ctrl(qml.RY, control=control_qubits)(angle_weight, wires=data_qubit)
# Restore control qubits
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# Apply swap gate
qml.Hadamard(wires=swap_control_qubit)
qml.CSWAP(wires=[swap_control_qubit, data_qubits[0], data_qubits[1]])
qml.Hadamard(wires=swap_control_qubit)
# Apply rotation layers
total_qubits = qubit_idx
for layer in range(rot_weights.shape[0]):
for qubit in range(total_qubits):
rot_angles = rot_weights[layer, qubit, :]
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# Measure swap control qubits
results = []
for swap_control_qubit in swap_control_qubits:
results.append(qml.expval(qml.PauliZ(wires=swap_control_qubit)))
return results
# Define a quantum neural network layer
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
def __init__(self, n_layers, n_features=4, **kwargs):
super(QuantumNeuralNetworkLayer, self).__init__(**kwargs)
self.n_layers = n_layers
self.n_features = n_features
# Define encoding weights
self.encoding_weights = self.add_weight(
shape=(n_layers, n_features),
initializer=tf.keras.initializers.GlorotUniform(),
trainable=True,
name='encoding_weights',
dtype=tf.float64
)
# Calculate total qubits = 2 control qubits + n_layers * (2 data qubits + 1 swap control qubit)
total_qubits = 2 + n_layers * (2 + 1)
self.rot_weights = self.add_weight(
shape=(n_layers, total_qubits, 3),
initializer=tf.keras.initializers.GlorotUniform(),
trainable=True,
name='rot_weights',
dtype=tf.float64
)
def call(self, inputs):
def apply_qnode(x):
x = tf.cast(x, dtype=tf.float64)
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
return tf.cast(result, dtype=tf.float32)
# Reshape inputs to be compatible with tf.map_fn
inputs = tf.reshape(inputs, (-1, self.n_features))
outputs = tf.map_fn(
apply_qnode,
inputs,
fn_output_signature=tf.float32
)
# 移除错误的 reshape,确保输出形状为 [batch_size, self.n_layers]
return outputs
# Define a deep quantum neural network model
class DeepQuantumNeuralNetwork(tf.keras.Model):
def __init__(self, n_quantum_layers, n_layers_per_qnn, num_classes, n_features=4, **kwargs):
super(DeepQuantumNeuralNetwork, self).__init__(**kwargs)
self.n_quantum_layers = n_quantum_layers
# Stack multiple quantum layers
self.quantum_layers = [
QuantumNeuralNetworkLayer(n_layers=n_layers_per_qnn, n_features=n_features)
for _ in range(n_quantum_layers)
]
# Final classical dense layer
self.dense = Dense(num_classes, activation='softmax')
def call(self, inputs):
# Pass through each quantum layer
x = inputs
for layer in self.quantum_layers:
x = layer(x)
# Apply the final dense layer
return self.dense(x)
# Create an instance of the deep quantum neural network
n_quantum_layers = 3 # Number of quantum layers to stack
n_layers_per_qnn = 2 # Number of rotation layers per quantum neural network
num_classes = 3 # 3个类别
model = DeepQuantumNeuralNetwork(
n_quantum_layers=n_quantum_layers,
n_layers_per_qnn=n_layers_per_qnn,
num_classes=num_classes
)
# Compile and train the model
learning_rate = 0.1
epochs = 100
batch_size = 8
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Load and preprocess data
iris = load_iris()
X = iris['data'].astype(np.float32)
y = iris['target'].reshape(-1, 1)
# One-hot encode the labels
encoder = OneHotEncoder(sparse_output=False)
y = encoder.fit_transform(y).astype(np.float32)
# Split the data into training and testing sets
x_train, x_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=116
)
# Train the model
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('Test loss:', score[0])
print('Test accuracy:', score[1])
plot_history(history)
# Close the output file and restore stdout
sys.stdout = original_stdout
output_file.close()
print("脚本执行完成。查看 'output.log' 获取打印输出,查看当前目录获取保存的图表。")
关键修改点
-
移除错误的 reshape 操作:
在 QuantumNeuralNetworkLayer 的 call 方法中,移除了 tf.reshape(outputs, (-1, self.n_layers)),改为直接返回 outputs,这样可以确保输出的形状为 [batch_size, self.n_layers],保持批次维度的一致性。
-
确保 Dense 层正确处理输入:
由于每个量子层的输出形状为 [batch_size, n_layers_per_qnn],多层量子网络堆叠后,最终输入到 Dense 层的形状应该仍然是 [batch_size, n_layers_per_qnn],从而 Dense 层能够正确输出 [batch_size, num_classes]。
其他建议
-
调试和验证形状: 在模型的 call 方法中,可以临时添加调试信息,如 print(x.shape),以确保每一层的输出形状符合预期。不过,由于您重定向了 stdout,需要在 output.log 中查看这些信息。
-
优化模型参数: 量子神经网络的设计和参数选择对模型的性能有显著影响。根据您的需求,可能需要调整量子层的数量、旋转层的数量等参数,以获得最佳性能。
-
确保兼容性: 确保所有的库和框架(如 TensorFlow、PennyLane)的版本与代码兼容,避免因版本问题导致的潜在错误。
通过上述修正,您的模型应该能够正确处理批次数据,并与标签形状匹配,从而解决当前的错误。