【问题标题】:Inverse of covariance matrix in time series时间序列中协方差矩阵的逆
【发布时间】:2021-10-16 11:41:12
【问题描述】:

我正在尝试将基于马氏距离(适用于图像)的方法转换为我的代码,该代码必须处理时间序列。这是 Matlab 代码,用户将图像作为输入传递,然后首先对其进行整形,然后计算均值、协方差矩阵及其逆矩阵(他使用的是图像大小):

function out = rxd(X)

% X input size = (126, 150, 204)

sizes = size(X);

X = reshape(X, [sizes(1)*sizes(2), sizes(3)]);

% X input size = (18900, 204)

M = mean(X);
% M size = (1, 204)
C = cov(X);
% M size = (204, 204)
Q = inv(C);
% M size = (204, 204)

这是我的代码,我用 Python 实现了第一部分。我没有图像,而是时间序列,其形状为 (24230, 30),这就是我避免重塑部分的原因:

import os
import numpy as np
X = np.load('dataset.npy')
# dataset shape: (24230, 30)
# 1. Calculate the mean of the matrix
M = np.mean(X, axis=0) # shape = (30,)
# 2. Calculate the Covariance matrix
C = np.cov(X) #shape = (24230, 24230)
# 3. Calculate the inverse of the Covariance matrix
Q = np.linalg.inv(C) #Error

如果我尝试运行它,我会收到错误:

LinAlgError:奇异矩阵

可能是什么问题?我注意到与 Matlab 输出的唯一区别在于平均形状,但我不明白我的转换是否有误。

【问题讨论】:

    标签: python matlab time-series pca covariance


    【解决方案1】:

    忽略关于 MATLAB 的一切,你的协方差矩阵 C can't be inverted;根据定义,这意味着矩阵C"singular",因此是Singular Matrix error.(所以这不是关于代码,而是关于数据)。

    如果你想计算这个矩阵的逆矩阵,the pseudo-inverse function np.linalg.pinv 可以这样做; 但一定要明白你为什么这样做。

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 2020-02-14
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      相关资源
      最近更新 更多