arima模型python

    科技2026-08-26  15

    arima模型python

    Time Series forecasting is one of the most in-demand techniques of data science, be it in stock trading, predicting business sales or weather forecasting. It is clearly a very handy skill to have and I am gonna equip you with just that by the end of this article.

    时间序列预测是数据科学中最抢手的技术之一,无论是在股票交易,预测业务销售还是天气预报中。 显然,这是一项非常方便的技能,在本文结尾处,我将为您提供这些技能。

    In this tutorial, we are gonna build an ARIMA model(don’t worry if you do not exactly know how this works yet) to predict the future temperature values of a particular city using python. GitHub link for the code and data set can be found at the end of this blog. I have also attached my YouTube video at the end, in case you are interested in a video explanation. So without wasting any time let’s get started.

    在本教程中,我们将构建一个ARIMA模型(如果您还不完全了解它的工作原理,请不要担心),以使用python预测特定城市的未来温度值。 有关代码和数据集的GitHub链接,请参见此博客的末尾。 如果您对视频说明感兴趣,我还将在结尾处附加我的YouTube视频。 因此,不要浪费时间,让我们开始吧。

    读取数据 (Reading Your Data)

    The first step in any time series is to read your data and see how it looks like. The following code snippet demonstrates how to do that.

    任何时间序列的第一步都是读取数据并查看其外观。 以下代码段演示了如何执行此操作。

    import pandas as pddf=pd.read_csv('/content/MaunaLoaDailyTemps.csv',index_col='DATE' ,parse_dates=True)df=df.dropna()print('Shape of data',df.shape)df.head()df

    The code is pretty straightforward. We read the data using pd.read_csv and writing parse_date=True, makes sure that pandas understands that it is dealing with date values and not string values.

    该代码非常简单。 我们使用pd.read_csv读取数据并编写parse_date = True,以确保pandas理解它是在处理日期值而不是字符串值。

    Next we drop any missing values and print the shape of the data. df.head() prints the first 5 rows of the dataset. Here is the output you should see for this:

    接下来,我们删除所有缺失的值并打印数据的形状。 df.head()打印数据集的前5行。 这是您应该看到的输出:

    绘制您的数据 (Plot Your data)

    The next is to plot out your data. This gives you an idea of whether the data is stationary or not. For those who don’t what stationarity means, let me give you a gist of it. Although i have made several videos on this topic, it all boils down to this:

    接下来是绘制数据。 这使您可以了解数据是否稳定。 对于那些不了解平稳性的人,让我向您介绍其中的要点。 尽管我已经制作了一些有关此主题的视频,但这些都可以归结为:

    Any time series data that has to be modeled needs to be stationary. Stationary means that it’s statistical properties are more or less constant with time. Makes sense, right? How else are you supposed to make predictions if the statistical properties are varying with time? These are the following properties that any stationarity model will have:

    必须建模的任何时间序列数据都必须是固定的。 平稳的意味着它的统计属性或多或少随时间而变化。 有道理吧? 如果统计属性随时间变化,您还应该如何进行预测? 这些是任何平稳模型都具有的以下属性:

    Constant Mean

    恒定均值 Constant Variance(There can be variations, but the variations shouldn’t be irregular)

    恒定方差(可以有变化,但变化不应不规则)No seasonality(No repeating patterns in the data set)

    没有季节性(数据集中没有重复模式)

    So first step is to check for stationarity. If your data set is not stationary, you’ll have to convert it to a stationary series. Now before you start worrying about all of this, relax! We have a fixed easy test to check for stationarity called the ADF(Augmented Dickey Fuller Test). But before showing that, lets plot the data first.

    因此,第一步是检查平稳性。 如果您的数据集不稳定,则必须将其转换为平稳序列。 现在,在您开始担心所有这些之前,放松一下! 我们有一个固定的简单测试来检查平稳性,称为ADF(增强迪基·富勒测试)。 但是在显示之前,让我们先绘制数据。

    Since I am only interested in predicting the average temperature, that is the only column I will be plotting.

    因为我只对预测平均温度感兴趣,所以这是我将要绘制的唯一一列。

    df['AvgTemp'].plot(figsize=(12,5))

    检查平稳性 (Checking For Stationarity)

    Right off the bat, we can see that it seems to have somewhat of a constant mean around 45. And the fluctuations also seem to be more or less the same. However to be sure if the data is stationary or not, we run a fixed statistical test using the following code:

    马上,我们可以看到它似乎在45左右具有恒定的均值。而且波动似乎也差不多。 但是,为了确保数据是否稳定,我们使用以下代码运行固定的统计测试:

    from statsmodels.tsa.stattools import adfullerdef ad_test(dataset): dftest = adfuller(dataset, autolag = 'AIC') print("1. ADF : ",dftest[0]) print("2. P-Value : ", dftest[1]) print("3. Num Of Lags : ", dftest[2]) print("4. Num Of Observations Used For ADF Regression:", dftest[3]) print("5. Critical Values :") for key, val in dftest[4].items(): print("\t",key, ": ", val)adf_test(df['AvgTemp'])

    You will get the output as follows:

    您将获得如下输出:

    You don’t need to worry about all the complex statistics. To interpret the test results, you only need to look at the p value. And you use the following simple method:

    您无需担心所有复杂的统计信息。 要解释测试结果,您只需要查看p值即可。 然后您使用以下简单方法:

    If p< 0.05 ; Data is stationary

    如果p <0.05; 数据是固定的

    if p>0.05; Data is not stationary

    如果p> 0.05; 数据不稳定

    It’s not a hard and fast rule, but a stationary data should have a small p value. Larger p value could indicate presence of certain trends(varying mean) or seasonality as well.

    这不是硬性规定,但是固定数据应该具有较小的p值。 较大的p值可能表示存在某些趋势(均值)或季节性。

    最后,确定您的ARIMA模型 (Finally, Decide your ARIMA Model)

    Now although I have made several YouTube videos on this topic, if you do not fully understand what an ARIMA model, allow me to present an easy overview:

    现在,尽管我已经制作了一些有关此主题的YouTube视频,但是如果您不完全了解ARIMA模型,请允许我给出一个简单的概述:

    ARIMA is composed of 3 terms(Auto-Regression + Integrated+Moving-Average)

    ARIMA由3个项组成(自回归+集成+移动平均)

    Auto-Regression:

    自回归:

    This basically means that you are using the previous values of the time series in order to predict the future. How many past values you use, determine the order of the AR model. Here’s how an AR(1) model looks like:

    这基本上意味着您正在使用时间序列的先前值来预测未来。 您使用多少个过去值确定AR模型的顺序。 这是AR(1)模型的样子:

    Y(t)= Some_Constant*Y(t-1)+ Another_Constant +Error(t)

    Y(t)= Some_Constant * Y(t-1)+ Another_Constant + Error(t)

    Simple enough, right?

    很简单,对不对?

    2. Integrated:

    2.集成:

    So, remember our talk on stationarity, and how it’s extremely important? Well if you are data set is not stationary, you most often need to perform some sort of difference operation to make it stationary. If you are differencing with previous value, its order 1 and so on. Here’s an example of that:

    因此,请记住我们关于平稳性的讨论,以及它如何极其重要? 好吧,如果您的数据集不是固定的,则通常需要执行某种差分操作以使其固定。 如果您与先前的值,其阶数1依此类推。 这是一个例子:

    Forgive my bad drawing. But as you can the series Y(t) was not stationary, because of an increasing trend resulting in a varying mean. We simply subtract it from previous values and voila! It becomes stationary. Depending on your data, you might have to repeat the differencing to get a second order differencing , third order and so on..

    原谅我的画图不好。 但是您可以尽可能地将序列Y(t)固定下来,因为趋势不断增加,导致均值变化。 我们只需从以前的值中减去它,瞧! 它变得静止。 根据您的数据,您可能必须重复进行差分以获得二阶差分,三阶等等。

    3. Moving Average:

    3.移动平均线:

    This basically means that you are using previous errors to make the future prediction. Also makes sense, right? By seeing how wrong you were in your prediction, you take that into account to make a better prediction. And just like in an AR model, the number of previous errors(also called number of lags) you use, determines the order of the model.

    这基本上意味着您正在使用以前的错误来进行将来的预测。 也有道理吧? 通过查看您的预测有多错误,可以将其考虑在内以做出更好的预测。 就像在AR模型中一样,您使用的先前错误数(也称为滞后数)决定了模型的顺序。

    Here’s how MA(1) order equation looks like:Y(t)= Mean + Some_Constant*Error(t-1) +Error(t)

    MA(1)阶方程如下所示:Y(t)=平均值+ Some_Constant * Error(t-1)+ Error(t)

    So our main job is to decide the order of the AR, I, MA parts which are donated by(p,d,q) respectively.

    因此,我们的主要工作是确定分别由(p,d,q)捐赠的AR,I,MA零件的顺序。

    And before you start worrying, let me tell everything is gonna be done automatically. pmdarima library comes to our rescue! It does the job of figuring out the order of the ARIMA all by itself. Here’s how the code snippet looks like:

    在开始担心之前,让我告诉您一切将自动完成。 pmdarima库可为我们提供帮助! 它本身就可以确定ARIMA的顺序。 这是代码段的样子:

    from pmdarima import auto_arimastepwise_fit = auto_arima(df['AvgTemp'], trace=True,suppress_warnings=True)

    (Make sure to install the pmdarima library first using pip install pmdarima)

    (确保首先使用pip install pmdarima安装pmdarima库)

    The code is pretty self explanatory. We simple supply our data to the auto_arima function. The function basically uses something called as the AIC score to judge how good a particular order model is. It simply tries to minimize the AIC score, and here’s how the output looks like:

    该代码很容易解释。 我们简单地将数据提供给auto_arima函数。 该函数基本上使用称为AIC分数的东西来判断特定订单模型的质量。 它只是试图最小化AIC得分,这是输出的样子:

    Model performance for different combination of orders 不同订单组合的模型效果

    We can see the best ARIMA model seems to be of the order (1,0,5) with the minimum AIC score=8294.785. With this knowledge we can finally proceed to train and fit the model to start making prediction!

    我们可以看到,最好的ARIMA模型似乎是(1,0,5)的量级,最小AIC得分= 8294.785。 有了这些知识,我们最终可以继续训练和拟合模型以开始进行预测!

    分割数据集 (Split Your Dataset)

    Before we actually train the model, we have to split the data set into a training and testing section. We do this because we first train the model on the data and keep the testing section hidden from the model. Once model is ready, we ask it to make predictions on the test data and see how well it performs.

    在实际训练模型之前,我们必须将数据集划分为训练和测试部分。 我们之所以这样做,是因为我们首先在数据上训练模型,并使测试部分对模型隐藏。 模型准备好后,我们要求它对测试数据进行预测,并查看其性能如何。

    The following code snippet illustrates how to do that:

    以下代码段说明了如何执行此操作:

    print(df.shape)train=df.iloc[:-30]test=df.iloc[-30:]print(train.shape,test.shape)

    So as you can probably tell, we reserving the last 30 days of the data as the testing section. You can see the shapes of the actual data, and the testing and training sections in the output.

    如您所知,我们将数据的最后30天保留为测试部分。 您可以在输出中看到实际数据的形状以及测试和培训部分。

    Shape of training and testing section 培训测试科的形状

    最后,我们进入多汁的东西!(Finally, We get to the Juicy Stuff!)

    Surprisingly, creating the ARIMA model is actually one of the easiest steps once you have done all the prerequisite steps. It’s as simple as shown in the code snippet below:

    出乎意料的是,一旦完成所有必要步骤,创建ARIMA模型实际上就是最简单的步骤之一。 就像下面的代码片段所示一样简单:

    from statsmodels.tsa.arima_model import ARIMAmodel=ARIMA(train['AvgTemp'],order=(1,0,5))model=model.fit()model.summary()

    As you can see we simply call the ARIMA function, supply it our data set and mention the order of the ARIMA model we want. You will be able to see the summary of the model in your output as well.

    如您所见,我们只需调用ARIMA函数,向它提供我们的数据集,并提及所需的ARIMA模型的顺序。 您还将能够在输出中看到模型的摘要。

    Model Summary 型号汇总

    You can see a whole lot of information about your model over here. Also you will be able to see the coefficients of each AR and MA term. These are nothing but the value of the variables that you saw in the previous AR/MA model equation which were labelled as ‘Some_Constant’. Generally a higher magnitude of this variable means that it has a larger impact on the output.

    您可以在此处查看有关模型的大量信息。 您还将能够看到每个AR和MA项的系数。 这些不过是您在先前的AR / MA模型方程式中看到的变量的值,这些变量标记为“ Some_Constant”。 通常,此变量的值越高,意味着它对输出的影响越大。

    检查您的模型有多好 (Check How Good Your Model Is)

    Here’s where our test data comes in. We first make prediction for temperature on the test data. Then we plot out to see how our predictions compared to the actual data.

    这是我们的测试数据的来源。我们首先对测试数据进行温度预测。 然后,我们进行绘图以查看我们的预测与实际数据之间的比较。

    start=len(train)end=len(train)+len(test)-1pred=model.predict(start=start,end=end,typ='levels').rename('ARIMA Predictions')pred.plot(legend=True)test['AvgTemp'].plot(legend=True)

    To actually make predictions, we need to use the model.predict function and tell it the starting and ending index in which we want to make the predictions.

    要实际进行预测,我们需要使用model.predict函数并将其要进行预测的起始索引和结束索引告诉它。

    Since we want to start making predictions where the training data ends , that is what i have written in the start variable. We want to stop making predictions when the data set ends, which explains the end variable. If you want to make future predictions as well, you can just change that accordingly in the start and end variable to the indexes you want. Your output plot should look like this:

    由于我们要开始对训练数据的结束位置进行预测,因此我已经在start变量中编写了内容。 我们想在数据集结束时停止做出预测,这说明了结束变量。 如果您还想进行将来的预测,则只需在start和end变量中相应地将其更改为所需的索引即可。 您的输出图应如下所示:

    Test values vs Predictions Plot 测试值与预测图

    As you can see the predictions does a pretty good job of matching with the actual trend all though there is a certain acceptable lag.

    如您所见,尽管存在一定的可接受的滞后,但预测与实际趋势的匹配非常好。

    检查您的准确度指标 (Check your Accuracy Metric)

    To actually ascertain how good or bad your model is we find the root mean squared error for it. The following code snippet shows that:

    为了真正确定模型的优劣,我们找到其均方根误差。 以下代码段显示:

    from sklearn.metrics import mean_squared_errorfrom math import sqrttest['AvgTemp'].mean()rmse=sqrt(mean_squared_error(pred,test['AvgTemp']))print(rmse)

    First we check the mean value of the data set which comes out to be 45. And the root mean squared error for this particular model should come to around 2.3. Also you should care about is that your root mean squared should be very smaller than the mean value of test set. In this case we can see the average error is gonna be roughly 2.3/45 *100=5.1% of the actual value.

    首先,我们检查数据集的平均值为45。此特定模型的均方根误差应约为2.3。 您还应该注意的是,您的均方根应该比测试集的平均值小得多。 在这种情况下,我们可以看到平均误差大约是实际值的2.3 / 45 * 100 = 5.1%。

    So with that your ARIMA model is ready to go! In future blogs I am gonna talk about different models and how you can increase the accuracy of the model further.

    因此,您的ARIMA模型已准备就绪! 在以后的博客中,我将讨论不同的模型以及如何进一步提高模型的准确性。

    If you are interested in the video explanation of the same, head over to my YouTube channel for more such content! You can find the GitHub link for the code and data set here: https://github.com/nachi-hebbar/ARIMA-Temperature_Forecasting

    如果您对相同的视频解释感兴趣,请转到我的YouTube频道以获取更多此类内容! 您可以在此处找到代码和数据集的GitHub链接: https : //github.com/nachi-hebbar/ARIMA-Temperature_Forecasting

    演示地址

    翻译自: https://medium.com/@nachihebbar/temperature-forecasting-with-arima-model-in-python-427b2d3bcb53

    arima模型python

    相关资源:ARIMA模型算法原理
    Processed: 0.013, SQL: 9