我们如何在Python中测量RMSE?

时间:2018-12-29 14:47:07

标签: python-3.x numpy kalman-filter mean-square-error pykalman

我正在使用Kalman Filters做实验。我创建了一个非常小的时间序列数据,其中的三列格式如下。由于无法在stackoverflow上附加文件,因此此处附有完整的数据集以提高可重复性:

csv file

  time        X      Y
 0.040662  1.041667  1
 0.139757  1.760417  2
 0.144357  1.190104  1
 0.145341  1.047526  1
 0.145401  1.011882  1
 0.148465  1.002970  1
 ....      .....     .

我已阅读Kalman Filter中的the documetation并设法进行了简单的线性预测,这是我的代码

import matplotlib.pyplot as plt 
from pykalman import KalmanFilter 
import numpy as np
import pandas as pd



df = pd.read_csv('testdata.csv')
print(df)
pd.set_option('use_inf_as_null', True)

df.dropna(inplace=True)


X = df.drop('Y', axis=1)
y = df['Y']



estimated_value= np.array(X)
real_value = np.array(y)

measurements = np.asarray(estimated_value)



kf = KalmanFilter(n_dim_obs=1, n_dim_state=1, 
                  transition_matrices=[1],
                  observation_matrices=[1],
                  initial_state_mean=measurements[0,1], 
                  initial_state_covariance=1,
                  observation_covariance=5,
                  transition_covariance=1)

state_means, state_covariances = kf.filter(measurements[:,1]) 
state_std = np.sqrt(state_covariances[:,0])
print (state_std)
print (state_means)
print (state_covariances)


fig, ax = plt.subplots()
ax.margins(x=0, y=0.05)

plt.plot(measurements[:,0], measurements[:,1], '-r', label='Real Value Input') 
plt.plot(measurements[:,0], state_means, '-b', label='Kalman-Filter') 
plt.legend(loc='best')
ax.set_xlabel("Time")
ax.set_ylabel("Value")
plt.show()

哪个给出以下图表作为输出

enter image description here

从图中可以看出,该模式似乎被很好地捕获了。我们如何统计均方根误差(RMSE)(上图中红线和蓝线之间的误差距离)?任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:1)

尝试一下!

from sklearn.metrics import mean_squared_error

mean_squared_error( measurements[:,1], state_means)

答案 1 :(得分:0)

scikit-learn 0.22.0中,您可以传递mean_squared_error()参数squared=False来返回RMSE。

from sklearn.metrics import mean_squared_error
mean_squared_error(y_actual, y_predicted, squared=False)