from __future__ import print_function
# import os
# os.environ['TF_USE_LEGACY_KERAS'] = '1'
from tensorflow.python.keras.layers import Dense, Activation
from tensorflow.python.keras import backend as K, Input
from tensorflow.python.keras.optimizer_v2.adam import Adam
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import roc_curve, auc
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.python.keras.models import Model
from importance_sampling.training import ConstantTimeImportanceTraining
from example_utils import get_parser
import pennylane as qml
import tensorflow as tf
# tf.compat.v1.disable_eager_execution()

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


if __name__ == "__main__":
    parser = get_parser("训练模型于鸢尾花数据集")
    args = parser.parse_args()

    # 加载并预处理鸢尾花数据集
    iris = datasets.load_iris()
    x_data = iris.data
    y_data = iris.target.reshape(-1, 1)

    # One-hot 编码标签
    encoder = OneHotEncoder(sparse_output=False)
    y_data = encoder.fit_transform(y_data)

    # 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(
        x_data, y_data, 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
    dev = qml.device('default.qubit', wires=n_qubits, shots=None)

    @qml.qnode(dev, interface='tf', diff_method='backprop')
    def quantum_circuit(inputs, weights):
        # 确保输入为 float32
        inputs = tf.cast(inputs, tf.float32)
        # 数据编码
        qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
        # 变分层
        qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
        # 测量
        return [qml.expval(qml.PauliZ(i)) for i in range(num_classes)]

    # 定义权重形状
    weight_shapes = {"weights": (n_layers, n_qubits, 3)}

    # 将量子电路包装为 Keras 层
    qlayer = qml.qnn.KerasLayer(quantum_circuit, weight_shapes, output_dim=num_classes, dtype=tf.float32)

    # 使用 Functional API 构建模型
    inputs = Input(shape=(4,), dtype=tf.float32)
    x = qlayer(inputs)
    outputs = Activation('softmax')(x)
    model = Model(inputs=inputs, outputs=outputs)

    # 编译模型
    model.compile(
        optimizer=Adam(learning_rate=learning_rate),
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )

    # 训练模型
    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)
上述代码报错Traceback (most recent call last):
  File "C:\代码备份库\importance-sampling-master-yuanweihua-QNN-pennylane\examples\yuanweihua.py", line 139, in <module>
    x = qlayer(inputs)
  File "C:\Users\liuwenjing\.conda\envs\pennylane_qiskit\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\liuwenjing\.conda\envs\pennylane_qiskit\lib\site-packages\pennylane\qnn\keras.py", line 414, in call
    results = self._evaluate_qnode(inputs)
  File "C:\Users\liuwenjing\.conda\envs\pennylane_qiskit\lib\site-packages\pennylane\qnn\keras.py", line 445, in _evaluate_qnode
    return tf.experimental.numpy.hstack(res)
TypeError: Exception encountered when calling layer "keras_layer" "                 f"(type KerasLayer).

Cannot interpret '<KerasTensor: shape=(None, 1) dtype=float64 (created by layer 'tf.reshape_14')>' as a data type

Call arguments received by layer "keras_layer" "                 f"(type KerasLayer):
  • inputs=<KerasTensor: shape=(None, 4) dtype=float32 (created by layer 'input_1')>
下述是我的环境内容absl-py                      2.1.0
appdirs                      1.4.4
array-record                 0.4.1
astunparse                   1.6.3
autograd                     1.7.0
autoray                      0.6.12
blinker                      1.8.2
cached-property              1.5.2
cachetools                   5.5.0
certifi                      2024.8.30
charset-normalizer           3.3.2
click                        8.1.7
colorama                     0.4.6
contourpy                    1.3.0
cycler                       0.12.1
dill                         0.3.8
dm-tree                      0.1.8
docplex                      2.28.240
etils                        1.5.2
flatbuffers                  24.3.25
fonttools                    4.54.1
fsspec                       2024.9.0
gast                         0.4.0
google-auth                  2.35.0
google-auth-oauthlib         0.4.6
google-pasta                 0.2.0
grpcio                       1.66.1
h5py                         3.11.0
idna                         3.10
importlib_metadata           8.5.0
importlib_resources          6.4.5
joblib                       1.4.2
keras                        2.10.0
Keras-Preprocessing          1.1.2
kiwisolver                   1.4.7
libclang                     18.1.1
Markdown                     3.7
markdown-it-py               3.0.0
MarkupSafe                   2.1.5
matplotlib                   3.9.1
mdurl                        0.1.2
ml-dtypes                    0.3.2
mpmath                       1.3.0
munkres                      1.1.4
namex                        0.0.8
networkx                     3.2.1
numpy                        1.26.4
oauthlib                     3.2.2
olefile                      0.47
opt-einsum                   3.3.0
optree                       0.12.1
packaging                    24.1
pbr                          6.1.0
PennyLane                    0.38.0
PennyLane_Lightning          0.38.0
Pillow                       8.4.0
pip                          24.2
promise                      2.3
protobuf                     3.20.3
psutil                       6.0.0
pyasn1                       0.6.1
pyasn1_modules               0.4.1
Pygments                     2.18.0
pyparsing                    3.1.4
PyQt5                        5.12.3
PyQt5_sip                    4.19.18
PyQtChart                    5.12
PyQtWebEngine                5.12.1
python-dateutil              2.9.0
qiskit                       1.0.2
qiskit-aer                   0.14.0.1
qiskit-algorithms            0.3.0
qiskit-optimization          0.6.1
requests                     2.32.3
requests-oauthlib            2.0.0
rich                         13.8.1
rsa                          4.9
rustworkx                    0.15.1
scikit-learn                 1.5.2
scipy                        1.13.1
semantic-version             2.6.0
setuptools                   75.1.0
six                          1.16.0
stevedore                    5.3.0
symengine                    0.11.0
sympy                        1.13.3
tensorboard                  2.10.1
tensorboard-data-server      0.6.1
tensorboard-plugin-wit       1.8.1
tensorflow                   2.10.0
tensorflow-datasets          4.9.3
tensorflow-estimator         2.10.0
tensorflow-io-gcs-filesystem 0.31.0
tensorflow-metadata          1.15.0
termcolor                    2.4.0
threadpoolctl                3.5.0
toml                         0.10.2
tornado                      6.4.1
tqdm                         4.66.5
typing_extensions            4.12.2
unicodedata2                 15.1.0
urllib3                      2.2.3
Werkzeug                     3.0.4
wheel                        0.35.1
wrapt                        1.16.0
zipp                         3.20.2
如何进行解决,用中文表述