# Demo 2:主特征向量 > 第 15 章 梯度、谱方法与量子机器学习 · [本章演示](index.md) · [代码演示总索引](../index.md) **可视化**:双图 —— 经典 power iter + 量子态制备 **对应教程**:[第 15 章 梯度、谱方法与量子机器学习 中相关小节](https://tutorial.chenzhaoyun.com/quantum-tutorial/ch15-learning-spectral/) · 依赖安装:`pip install "unified-quantum[visualization,simulation]"` ## 实现要点 核心: A 是 path graph P_4 的 adjacency matrix,归一化到 ||A||=1,主特征值 λ_max = 1.000。 经典 power iteration: x_t = A^t x_0 / ||...||,从 x_0 = (|00⟩+|01⟩)/√2 出发, Rayleigh 商 R(x_t) = ⟨x_t|A|x_t⟩ 单调收敛到 λ_max,|⟨v_1|x_t⟩|² 也 → 1。 量子端: 把收敛态 |v_1⟩ 用 5 个量子门 (H + 2·CNOT + RY + CNOT) 制备,再用 uniqc 测量 4 个基矢上的概率,验证与 numpy 算出的 v_1² 一致。这个 5-gate 分解依赖于 v_1 的对称性 (a=d, b=c),所以中间连续两次 CNOT 等价于 swap-and-restore, 最后一个 CNOT 再 swap 一次即可得到目标。 uniqc 坑: get_matrix 不能在 measure 之后调用,所以验证在 measure 之前做。 ## 完整源码 ```{literalinclude} 02_principal_eigenvector.py :language: python :linenos: :caption: demos/ch15-learning-spectral/02_principal_eigenvector.py ``` ## 运行结果 ![Demo 2:主特征向量](02_principal_eigenvector.png) ## 运行方式 ```bash # 仓库根目录执行;输出 PNG 到 demos/ch15-learning-spectral/02_principal_eigenvector.png,关键统计到 stdout .venv/bin/python3 demos/ch15-learning-spectral/02_principal_eigenvector.py ``` --- [← 本章演示](index.md) · [↑ 代码演示总索引](../index.md) · [⌂ 教程门户](https://tutorial.chenzhaoyun.com/)