You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中保存Seaborn的KDE曲线并用于互相关分析?

拟合脉冲直方图并导出可用于互相关的模型函数

一、高斯拟合(参数化模型)

用scipy.optimize.curve_fit拟合高斯分布,得到幅值、均值、标准差参数后,即可定义可复用的高斯函数,直接用于后续互相关计算。

示例代码:

import numpy as np
from scipy.optimize import curve_fit

# 定义高斯函数模板
def gaussian(x, amp, mu, sigma):
    return amp * np.exp(-(x - mu)**2 / (2 * sigma**2))

# 替换为你的实际脉冲直方图数据
hist_data = np.random.normal(loc=5, scale=1, size=1000)
hist, bins = np.histogram(hist_data, bins=30, density=True)
bin_centers = (bins[:-1] + bins[1:])/2

# 拟合高斯曲线,p0为初始参数猜测
popt, _ = curve_fit(gaussian, bin_centers, hist, p0=[1, np.mean(hist_data), np.std(hist_data)])
amp_fit, mu_fit, sigma_fit = popt

# 封装拟合后的可调用函数
def fitted_gaussian(x):
    return gaussian(x, amp_fit, mu_fit, sigma_fit)

# 演示:与小脉冲做互相关
small_pulse = np.random.normal(loc=0, scale=0.5, size=50)
x_vals = np.linspace(-2, 10, 200)
fit_curve = fitted_gaussian(x_vals)
cross_corr = np.correlate(fit_curve, small_pulse, mode='same')

二、KDE拟合(非参数化模型)

跳过Seaborn的绘图层,直接用scipy.stats.gaussian_kde生成KDE模型对象——这个对象本身就是可调用的函数,还能通过序列化保存,后续加载后可直接使用。

示例代码:

import numpy as np
from scipy.stats import gaussian_kde
import pickle

# 替换为你的实际脉冲数据
pulse_data = np.random.normal(loc=5, scale=1, size=1000)

# 创建KDE模型
kde_model = gaussian_kde(pulse_data)

# 保存模型到文件(可选,后续可直接加载复用)
with open('kde_pulse_model.pkl', 'wb') as f:
    pickle.dump(kde_model, f)

# 加载模型(后续使用时执行)
# with open('kde_pulse_model.pkl', 'rb') as f:
#     kde_model = pickle.load(f)

# 用模型计算任意x值的密度
x_vals = np.linspace(-2, 10, 200)
kde_curve = kde_model(x_vals)

# 演示互相关
small_pulse = np.random.normal(loc=0, scale=0.5, size=50)
cross_corr = np.correlate(kde_curve, small_pulse, mode='same')

三、经验分布函数(EF)拟合

如果EF指基于直方图的经验拟合,可通过插值将离散的直方图密度转换为连续函数,得到可调用的拟合函数。

示例代码:

import numpy as np
from scipy.interpolate import interp1d

# 替换为你的实际脉冲直方图数据
hist_data = np.random.normal(loc=5, scale=1, size=1000)
hist, bins = np.histogram(hist_data, bins=30, density=True)
bin_centers = (bins[:-1] + bins[1:])/2

# 生成连续插值函数(kind可选'linear'/'cubic'等)
ef_fit = interp1d(bin_centers, hist, kind='cubic', fill_value=0, bounds_error=False)

# 计算任意x值的密度
x_vals = np.linspace(-2, 10, 200)
ef_curve = ef_fit(x_vals)

# 演示互相关
small_pulse = np.random.normal(loc=0, scale=0.5, size=50)
cross_corr = np.correlate(ef_curve, small_pulse, mode='same')

内容的提问来源于stack exchange,提问作者Angel Barra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:52:38