【问题标题】:How to make a plot of power iteration method approximations如何绘制幂迭代法近似图
【发布时间】:2020-05-25 19:08:29
【问题描述】:

我正在尝试使用以下代码绘制前 20 次迭代的特征值近似图:

def metoda_potegowa(A,X0,iterations):

  iteracje=[]
  aproks=[]
  ii=0

  while(1):
    for i in range (iterations):
      A = A*A

    x = A*X0
    aproks.append(x)
    iteracje.append(ii)
    ii=ii+1
    norm = np.linalg.norm(x)

    plt.scatter(iteracje,aproks)
    plt.xlabel('iteracja')
    plt.ylabel('aproksymacja')
    plt.grid
    plt.show

    break

  print (x/norm)
  print (np.linalg.eig(A)[1])

我收到以下警告:

ValueError                                Traceback (most recent call last)
<ipython-input-96-d18eef58c53a> in <module>()
----> 1 metoda_potegowa(a,x0,5)

4 frames
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4378         y = np.ma.ravel(y)
   4379         if x.size != y.size:
-> 4380             raise ValueError("x and y must be the same size")
   4381 
   4382         if s is None:

ValueError: x and y must be the same size

我该如何解决这个问题,以便它为我绘制一个情节?

【问题讨论】:

  • 你用什么参数来调用这个函数?
  • metoda_potegowa(a,x0,5) 其中 a = np.matrix([[1, 0, 3], [0, 2, 0], [3, 0, 1]]); x0 = np.matrix([1,1,1]).transpose();

标签: python python-3.x plot iteration


【解决方案1】:

首先,我告诉你代码

while(1):
   code...
   break

没有意义。因为和刚才一样

code...

根据Wikipedia,可以使用以下公式计算特征向量的下一个近似值:

iteracjeaproks 是散点图的错误选择,因为我们有向量。我们如何用一个点来表示一个向量? 我们可以选择以下方法:

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('ggplot')

def metoda_potegowa(A,X0,iterations):
    fig, ax = plt.subplots(figsize=(15,10))
    b_k = X0.copy()
    for i, _ in enumerate(range(iterations)):
        # calculate the product between A and b_k
        Ab_k = np.dot(A, b_k)

        # calculate the norm
        Ab_k_norm = np.linalg.norm(Ab_k)

        # get next aproximation of eigenvector
        b_k = Ab_k / Ab_k_norm

        # plot the current iteration i
        plt.scatter(list(range(1, len(b_k)+1)), b_k.ravel(), label=i)
    plt.xlabel('index')
    plt.ylabel('value') 
    # use colors to distinguish iteration
    plt.legend()
    plt.show()

    return b_k

然后您可以使用iterations = 20 调用该函数并绘制结果:

a = np.array([[1, 0, 3], [0, 2, 0], [3, 0, 1]])
x0 = np.array([1,1,1]).transpose()
eigenvector_20 = metoda_potegowa(a,x0,20)

【讨论】:

  • hm 当我像你说的那样称呼它时,它给了我一个错误:ValueError:连接轴的所有输入数组维度必须完全匹配,但是沿着维度 0,索引 0 处的数组具有大小3 并且索引 1 处的数组大小为 1
  • 你能检查一下你写的调用方法吗?好像功能不正常
  • 因为我使用了 np.matrix()。我需要使用 np.array()。我会编辑答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多