gpt4 book ai didi

python - SVD - 矩阵变换 Python

转载 作者:太空狗 更新时间:2023-10-29 18:26:35 26 4
gpt4 key购买 nike

尝试在 Python 中计算 SVD 以找到光谱中最重要的元素,并创建了一个仅包含最重要部分的矩阵。

在 python 中我有:

u,s,v = linalg.svd(Pxx, full_matrices=True)

返回 3 个矩阵;其中“s”包含对应于 u、v 的大小。

为了构造一个包含信号所有重要部分的新矩阵,我需要捕获“s”中的最高值并将它们与“u”和“v”中的列以及生成的矩阵相匹配应该给我最重要的数据部分。

问题是我不知道如何在 Python 中执行此操作,例如,我如何找到“s”中的最高数字并选择“u”和“v”中的列以创建一个新矩阵?

(我是 Python 和 numpy 的新手)所以非常感谢任何帮助

编辑:

import wave, struct, numpy as np, matplotlib.mlab as mlab, pylab as pl
from scipy import linalg, mat, dot;
def wavToArr(wavefile):
w = wave.open(wavefile,"rb")
p = w.getparams()
s = w.readframes(p[3])
w.close()
sd = np.fromstring(s, np.int16)
return sd,p

def wavToSpec(wavefile,log=False,norm=False):
wavArr,wavParams = wavToArr(wavefile)
print wavParams
return mlab.specgram(wavArr, NFFT=256,Fs=wavParams[2],detrend=mlab.detrend_mean,window=mlab.window_hanning,noverlap=128,sides='onesided',scale_by_freq=True)

wavArr,wavParams = wavToArr("wavBat1.wav")

Pxx, freqs, bins = wavToSpec("wavBat1.wav")
Pxx += 0.0001

U, s, Vh = linalg.svd(Pxx, full_matrices=True)
assert np.allclose(Pxx, np.dot(U, np.dot(np.diag(s), Vh)))

s[2:] = 0
new_a = np.dot(U, np.dot(np.diag(s), Vh))
print(new_a)

最佳答案

linalg.svd 以降序返回 s。因此,要选择 s 中的 n 个最高数字,您只需形成

s[:n]

如果将 s 的较小值设置为零,

s[n:] = 0

然后矩阵乘法将负责“选择” U 和 V 的适当列。

例如,

import numpy as np
LA = np.linalg

a = np.array([[1, 3, 4], [5, 6, 9], [1, 2, 3], [7, 6, 8]])
print(a)
# [[1 3 4]
# [5 6 9]
# [1 2 3]
# [7 6 8]]
U, s, Vh = LA.svd(a, full_matrices=False)
assert np.allclose(a, np.dot(U, np.dot(np.diag(s), Vh)))

s[2:] = 0
new_a = np.dot(U, np.dot(np.diag(s), Vh))
print(new_a)
# [[ 1.02206755 2.77276308 4.14651336]
# [ 4.9803474 6.20236935 8.86952026]
# [ 0.99786077 2.02202837 2.98579698]
# [ 7.01104783 5.88623677 8.07335002]]

鉴于 data here ,

import numpy as np
import scipy.linalg as SL
import matplotlib.pyplot as plt

Pxx = np.genfromtxt('mBtasJLD.txt')
U, s, Vh = SL.svd(Pxx, full_matrices=False)
assert np.allclose(Pxx, np.dot(U, np.dot(np.diag(s), Vh)))

s[2:] = 0
new_a = np.dot(U, np.dot(np.diag(s), Vh))
print(new_a)
plt.plot(new_a)
plt.show()

产生

enter image description here

关于python - SVD - 矩阵变换 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com