用高斯混合模型求波形的精确振幅

2024-05-16 10:15:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将波形分解为高斯混合。我正在生成波形的直方图,并将这些数据放入高斯混合模型。我能找到分量,但我不能正确地拟合它的振幅。请帮帮我

import matplotlib.pyplot as plt
import scipy.io as sio
import numpy as np
from sklearn.mixture import GaussianMixture


def gaussian(x, m, s, scale):
    sqrt_2pi = np.sqrt(2*np.pi)
    return scale * 1/(s*sqrt_2pi) * np.exp(-0.5*((x-m)/s)**2)

gaswin1 =  gaussian(np.arange(0,100),50,40,1)
gaswin2 = 1.5* gaussian(np.arange(0,100),70,10,1)
gaswin = gaswin1 + gaswin2
plt.plot(gaswin)

x = np.arange(0,100)
data = []
num_presision = 100
max_y = np.max(gaswin)
for x_, y_ in zip(x, gaswin):
      data += [x_]*int(y_/max_y*num_presision)
      #print(data) 
sy = np.array(data) 
#plt.hist(sy, bins=50, color='orange', label='histogram of generated data')
num_clusters = 2
gmm = GaussianMixture(num_clusters)
gmm.fit(X=np.expand_dims(sy,1))

# sort results in the order of the means
params = zip(gmm.means_.ravel(), gmm.covariances_.ravel(), gmm.weights_)
sorted_params = sorted([ (m, v, w) for m, v, w in params], key=lambda p:p[0])

# plot the results
gy_list = []
ty = np.zeros(len(gaswin))
for m, v, w in sorted_params:
    gy = gaussian(x, m, np.sqrt(v), w)
    gy_list.append(gy)
    ty += gy

plt.plot(ty, ':', color='red', linewidth=3, label='GMM fitted curve')
for k, gy in enumerate(gy_list):
    plt.plot(gy, ':', label='%d-th component' % k)

GMM fitted curve


Tags: inimportfordataplotasnpplt