我有一些时间数据(一天中的几小时)。我想为这些数据拟合von mises分布,并找到周期均值。我如何在python中使用scipy来做到这一点?
例如 :
from scipy.stats import vonmises
data = [1, 2, 22, 23]
A = vonmises.fit(data)
我不知道如何使用拟合或均值或区间方法获得此数据的分布(可能是间隔)和周期均值。
找到VM分发的好工作。这是战斗的一半。但除非我被scipy.stats.vonmises docs中的公式弄错,否则该公式假设数据以0为中心,可能并非如此。所以我们应该建立自己的VM分发。对于我们的Vm发行版,我们将确保它在24小时范围内是周期性的,而不是传统的2pi范围。请参阅下面的代码和评论。此外,我假设您的数据是您看到某些事件发生的时间,如果不是这样,您将需要重新调整。
from scipy.optimize import curve_fit
import numpy as np
from matplotlib import pyplot as plt
# Define the von mises kernel density estimator
def circular_von_mises_kde(x,mu,sigma):
# Adjust data to take it to range of 2pi
x = [(hr)*2*np.pi/24 for hr in x]
mu*=2*np.pi/24
sigma*=2*np.pi/24
# Compute kappa for vm kde
kappa = 1/sigma**2
return np.exp((kappa)*np.cos((x-mu)))/(2*np.pi*i0(kappa))
# Assuming your data is occurences of some event at the given hour of the day
frequencies= np.zeros((24))
frequencies[data]=1
hr_data = np.linspace(1,24, 24)
fit_params, cov = curve_fit(circular_von_mises_kde, hr_data, data_to_fit, bounds=(0,24))
plt.plot(hr_data, frequencies, 'k.',label='Raw data')
plt.plot(np.linspace(1,25, 1000), circular_von_mises_kde(np.linspace(1,25, 1000), *fit_params), 'r-',label='Von Mises Fit')
plt.legend()
plt.xlabel('Hours (0-24)')
plt.show()
print('The predicted mean is {mu} and the standard deviation is {sigma}'.format( mu=round(fit_params[0],3), sigma=round(fit_params[1], 3)))
Click to see the result of the above code *作为一个快速警告,你可能需要一个更大的数据集来做一些适当的拟合并真正建立一个人口趋势。