协方差矩阵的主轴不与其角度对齐

问题描述 投票:1回答:1

我正在尝试获得协方差的主轴(渐变和截距)。我正在使用已排序的特征向量来计算椭圆的角度,但是当我将得到的椭圆绘制在主轴上时,它们不会对齐。

有没有人有任何想法?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

def eigsorted(cov):
    vals, vecs = np.linalg.eigh(cov)
    order = vals.argsort()[::-1]
    return vals[order], vecs[:,order]

def orientation_from_covariance(cov, sigma):
    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    w, h = 2 * sigma * np.sqrt(vals)
    return w, h, theta

def plot_ellipse(ax, mu, covariance, color, linewidth=2, alpha=0.5):
    x, y, angle = orientation_from_covariance(covariance, 2)
    e = Ellipse(mu, x, y, angle=angle)
    e.set_alpha(alpha)
    e.set_linewidth(linewidth)
    e.set_edgecolor(color)
    e.set_facecolor(color)
    e.set_fill(False)
    ax.add_artist(e)
    return e


from statsmodels.stats.moment_helpers import corr2cov
corr = np.eye(2)
corr[0, 1] = corr[1, 0] = 0.7
cov = corr2cov(corr, [1, 5])
mu = [1, 1]

vectors = eigsorted(cov)[1].T
gradients = [v[0] / v[1] for v in vectors]
intercepts = [mu[1] - (gradient*mu[0]) for gradient in gradients]

plt.scatter(*np.random.multivariate_normal(mu, cov, size=9000).T, s=1);
plot_ellipse(plt.gca(), mu, cov, 'k')
_x = np.linspace(*plt.xlim())
for i,g in zip(intercepts, gradients):
    plt.plot(_x, i + (_x * g), 'k');

covariance

python numpy statistics covariance eigenvector
1个回答
1
投票

问题是以下几行

# gradients = [v[0] / v[1] for v in vectors] # wrong
gradients = [v[1] / v[0] for v in vectors] # correct

因为梯度是yx变化的变化。那个数字看起来像这样。 Ellipse Plot

在密谋开始之前我还添加了plt.figure(),在plt.axis("equal")召唤之后加入了plot_ellipse

我还想引用numpy.linalg.eigh文档:

w :( ...,M)ndarray

特征值按升序排列,每个特征值根据其多样性重复。

因此可以省略eigsorted功能。

© www.soinside.com 2019 - 2024. All rights reserved.