# Demo 3:QNN 拟合 sin(x) > 第 2 章 量子神经网络 · [本章演示](index.md) · [代码演示总索引](../index.md) **可视化**:双图:MSE 等高线+拟合曲线 —— 1-qubit re-uploading ansatz 网格搜索最优点 **对应教程**:[第 2 章 量子神经网络 中相关小节](https://tutorial.chenzhaoyun.com/quantum-tutorial/ch02-quantum-nn/) · 依赖安装:`pip install "unified-quantum[visualization,simulation]"` ## 实现要点 核心:1-qubit data re-uploading ansatz |ψ(x, w)⟩ = RY(x) · RZ(w0) · RY(x) · RZ(w1) · |0⟩ 预测 f(x, w) = ⟨ψ(x, w)|Z|ψ(x, w)⟩ 用 4 个训练点 (x_i, sin(x_i)) 在 w ∈ [-π, π]² 上做网格搜索, 找到使 MSE 最小的 (w0*, w1*),然后在同一网格上画出预测曲线。 ## 完整源码 ```{literalinclude} 03_qnn_ansatz.py :language: python :linenos: :caption: demos/ch02-qnn/03_qnn_ansatz.py ``` ## 运行结果 ![Demo 3:QNN 拟合 sin(x)](03_qnn_ansatz.png) ## 运行方式 ```bash # 仓库根目录执行;输出 PNG 到 demos/ch02-qnn/03_qnn_ansatz.png,关键统计到 stdout .venv/bin/python3 demos/ch02-qnn/03_qnn_ansatz.py ``` --- [← 本章演示](index.md) · [↑ 代码演示总索引](../index.md) · [⌂ 教程门户](https://tutorial.chenzhaoyun.com/)