aboks/power-iteration

使用 math-php 实现了幂迭代方法,用于求解矩阵的特征值

v1.1.0 2022-06-27 18:50 UTC

This package is auto-updated.

Last update: 2024-08-28 00:02:29 UTC


README

Continuous Integration Latest Stable Version

PowerIteration

使用优秀的 math-php 库实现了幂迭代方法,用于求解矩阵的(主)特征值及其对应的特征向量。

安装

使用 composer 安装

$ composer require aboks/power-iteration

基本用法

<?php
use Aboks\PowerIteration\PowerIteration;
use MathPHP\LinearAlgebra\MatrixFactory;

$power_iteration = new PowerIteration();
$dominant_eigenpair = $power_iteration->getDominantEigenpair(MatrixFactory::create([
    [2, 1],
    [0, 1]
 ]));
var_dump($dominant_eigenpair->getEigenvalue()); // 2
var_dump($dominant_eigenpair->getEigenvector()); // Vector([1, 0]), or a scalar multiple

高级用法

计算最小特征对

在大多数情况下,人们感兴趣的是主导特征值及其对应的特征向量。然而,也可以计算最小特征对。

<?php
use Aboks\PowerIteration\PowerIteration;
use MathPHP\LinearAlgebra\Matrix;

$power_iteration = new PowerIteration();
$dominant_eigenpair = $power_iteration->getLeastDominantEigenpair(MatrixFactory::create([
    [2, 1],
    [0, 1]
 ]));
var_dump($dominant_eigenpair->getEigenvalue()); // 1
var_dump($dominant_eigenpair->getEigenvector()); // Vector([√2, -√2]), or a scalar multiple

自定义

停止准则

默认情况下,幂迭代运行1000次。可以通过将 StoppingCriterion 的实例作为 PowerIteration 的第一个参数传递来更改停止准则。

<?php
use Aboks\PowerIteration\PowerIteration;
use Aboks\PowerIteration\StoppingCriterion\MaxIterations;
use Aboks\PowerIteration\StoppingCriterion\EigenvectorTolerance;

new PowerIteration(new MaxIterations(10));           // will stop after 10 iterations
new PowerIteration(new EigenvectorTolerance(0.01));  // will stop when ‖Av - λv‖ < 0.01

缩放方法

为了防止在非常大的特征值(或非常小的特征值时的下溢)情况下溢出,每次迭代后都会缩放/归一化特征向量估计。使用相同的方法也使用缩放来缩放最终的特征向量估计。默认情况下,估计缩放为单位向量,基于L2范数。要使用不同的方法,提供 ScalingMethod 的实例作为 PowerIteration 的第二个参数。

<?php
use Aboks\PowerIteration\PowerIteration;
use Aboks\PowerIteration\ScalingMethod\NormBased;
use Aboks\PowerIteration\Norm\MaxNorm;

new PowerIteration(null, new NormBased(new MaxNorm()));  // will scale to a unit vector based on the max-norm

运行测试

使用 Composer 安装依赖项(包括开发依赖项)后,运行

$ ./vendor/bin/phpunit

从项目根目录。

贡献

非常欢迎对这个库的贡献!请确保你的更改有足够的测试覆盖,并且代码遵循 PSR-2

版本控制

本项目遵循 语义版本控制

许可

代码在MIT许可下发布。