如何在Python中计算自相关
相关性通常决定了两个变量之间的关系。相关性是指在以前的时间步骤中,计算出变量与自身之间的相关性,这样的相关性被称为自相关。
方法1:使用lagplot()
本例使用的是每日最低气温数据集。作为第一步,可以使用pandas提供的lagplot()函数快速检查自相关。
语法 :
pd.plotting.lag_plot(data, lag=1)
其中,
- data是输入数据帧
- lag指定整数,以获得滞后期。
使用的数据:每日最低气温–BR
# import modules
import pandas as pd
# read the data from the csv
data = pd.read_csv("daily-minimum-temperatures-in-blr.csv",
header=0, index_col=0, parse_dates=True,
squeeze=True)
# display top 15 data
data.head(15)
# lagplot
pd.plotting.lag_plot(data, lag=1)
输出:
方法2:在不同的时间步骤创建滞后变量
我们知道,在当前和之前的时间步骤中的观察值对于预测未来的步骤是非常重要的,所以我们在不同的时间步骤中创建滞后变量,比如t+1,t+2,t+3。这是用pandas.concat()和shift()函数完成的。Shift函数将时间段移动一个指定的值,Concat函数将不同时间段的滞后变量连接起来,如下所示。
在新的数据框架上使用pandas.corr()函数来计算相关矩阵。
语法:
pandas.DataFrame.corr(method = 'pearson')
其中,方法–Pearson,用于计算标准相关系数。
示例:
data = pd.read_csv("daily-minimum-temperatures-in-blr.csv",
header=0, index_col=0, parse_dates=True,
squeeze=True)
# extracting only the temperature values
values = pd.DataFrame(data.values)
# using shift function to shift the values.
dataframe = pd.concat([values.shift(3), values.shift(2),
values.shift(1), values], axis=1)
# naming the columns
dataframe.columns = ['t', 't+1', 't+2', 't+3']
# using corr() function to compute the correlation
result = dataframe.corr()
print(result)
输出 :
方法3:使用 plot_acf()
一个时间序列按滞后期的自相关图被称为自相关函数(ACF)。这种图也被称为相关图。相关图绘制了所有可能的时间段的相关性。具有最高相关度的滞后变量可以被考虑用于建模。下面是一个为所选数据集计算和绘制自相关图的例子。
Statsmodel库为此提供了一个名为plot_acf()的函数。
语法:
statsmodels.graphics.tsaplots.plot_acf(x,lags,alpha)
where,
- x – 一个时间序列值的数组
- lags – 一个int或数组的滞后值,在横轴上使用。当lags是一个int时,使用np.range(lags)。
- alpha – 如果给了一个数字,将返回给定水平的置信区间。例如,如果α=.05,将返回95%的置信区间,其中的标准偏差是根据Bartlett的公式计算的。如果没有,则不画出置信区间。
示例 :
# import the required modules
import pandas as pd
from statsmodels.graphics.tsaplots import plot_acf
# read the csv data
data = pd.read_csv("daily-minimum-temperatures-in-blr.csv",
header=0, index_col=0, parse_dates=True,
squeeze=True)
# plot the auto correlation
plot_acf(data)
输出: