【问题标题】:How to Implementating This EgienVector Code Python Code into Java如何在 Java 中实现这个 EigenVector 代码 Python 代码
【发布时间】:2018-06-19 04:09:27
【问题描述】:

我找到了算法的正确结果 我可以将这段代码实现到 Java 中吗?

import numpy as np
from scipy.linalg import eig 
transition_mat = np.matrix([
    [0.8, 0.15, 0.05],\
    [0.075, 0.85, 0.075],\
    [0.05, 0.15,0.8 ]])

S, U = eig(transition_mat.T)
stationary = np.array(U[:, np.where(np.abs(S - 1.) < 1e-8)[0][0]].flat)
print stationary
print np.sum(stationary)
stationary = stationary / np.sum(stationary)

print stationary

我在 Java 中实现了这段代码,但结果是错误的

Matrix A = new Matrix(transition);
        A = A.transpose();
        Matrix x = new Matrix(N, 1, 1.0 / N); // initial guess for eigenvector
        for (int i = 0; i < 50; i++) {
            x = A.times(x);
            x = x.times(1.0 / x.norm1());       // rescale
        }

        // compute by finding eigenvector corresponding to eigenvalue = 1
        EigenvalueDecomposition eig = new EigenvalueDecomposition(A);
        Matrix V = eig.getV();
        double[] real = eig.getRealEigenvalues();
        for (int i = 0; i < N; i++) {
            if (Math.abs(real[i] - 1.0) < 1E-8) {
                x = V.getMatrix(0, N-1, i, i);
                x = x.times(1.0 / x.norm1());
                System.out.println("Stationary distribution using eigenvector:");
                x.print(9, 6);
            }
        }

【问题讨论】:

  • 您当前/预期的结果是什么? (编辑您的问题以添加它)
  • 结果为空
  • 如果我删除 if (Math.abs(real[i] - 1.0)
  • 在 Java 中 -0.040173, -0.147368, 0.812459 在 Python 中 -0.40824829 -0.81649658 -0.40824829

标签: java eigenvalue markov-chains


【解决方案1】:

快速查看代码似乎正确,前提是

  1. 您的矩阵transition 与python 示例中的相同。从你的结果我假设
  2. Matrix.times 方法执行向量乘法,而不是逐项乘法
  3. 50 次迭代的次数对于本示例应该足够了。如果您的第二个特征值也接近 1,则此数字将大大更大
  4. 函数EigenvalueDecomposition.getV以您期望的方向(行/列)返回特征向量

请注意,有效的转移矩阵(跳跃概率矩阵)的行或列总和为 1(定义问题),因为停留或切换的机会必须是 100%。这意味着存在 1 的特征向量。从您使用矩阵的初始转置来看,我假设您需要一个的行和。

由于您似乎没有 1 的特征值,因此最符合逻辑的错误是矩阵中的拼写错误。

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 2014-12-10
    • 2015-09-06
    • 2022-09-29
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多