使用python進(jìn)行時間序列預(yù)測的流程
引言
使用 Python 進(jìn)行時間序列預(yù)測是一個非常常見的任務(wù),可以應(yīng)用于各種領(lǐng)域,如金融市場預(yù)測、銷售量預(yù)測、天氣預(yù)報等。時間序列預(yù)測的方法有很多,包括統(tǒng)計方法(如 ARIMA 模型)、機器學(xué)習(xí)方法(如支持向量機、決策樹)、以及深度學(xué)習(xí)方法(如 LSTM 網(wǎng)絡(luò))。
下面是一個簡單的時間序列預(yù)測流程示例,使用 Python 和 pandas、numpy、以及 statsmodels 庫來實現(xiàn) ARIMA 模型的時間序列預(yù)測。
1. 導(dǎo)入必要的庫
首先,我們需要導(dǎo)入一些常用的 Python 庫。
import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from sklearn.metrics import mean_squared_error
2. 準(zhǔn)備數(shù)據(jù)
我們將使用一個簡單的時間序列數(shù)據(jù)集。這個數(shù)據(jù)集可以是來自 CSV 文件的數(shù)據(jù),也可以是生成的模擬數(shù)據(jù)。在這里,我們將生成一些模擬數(shù)據(jù)。
# 生成模擬時間序列數(shù)據(jù) np.random.seed(0) date_range = pd.date_range(start='2020-01-01', periods=100, freq='D') data = np.random.normal(0, 1, size=(100,)).cumsum() time_series_data = pd.Series(data, index=date_range) # 可視化數(shù)據(jù) time_series_data.plot(title="Time Series Data", xlabel="Date", ylabel="Value") plt.show()
3. 檢查時間序列的平穩(wěn)性
ARIMA 模型要求時間序列是平穩(wěn)的。我們可以通過觀察時間序列圖或使用統(tǒng)計檢驗(如 ADF 檢驗)來檢查時間序列的平穩(wěn)性。
from statsmodels.tsa.stattools import adfuller # ADF 檢驗 result = adfuller(time_series_data) print(f'ADF Statistic: {result[0]}') print(f'p-value: {result[1]}')
如果 p-value
小于 0.05,說明時間序列是平穩(wěn)的。否則,我們可能需要對時間序列進(jìn)行差分操作來使其平穩(wěn)。
4. 拆分訓(xùn)練集和測試集
在進(jìn)行時間序列預(yù)測時,我們通常將數(shù)據(jù)集拆分為訓(xùn)練集和測試集。訓(xùn)練集用于訓(xùn)練模型,測試集用于評估模型性能。
# 拆分?jǐn)?shù)據(jù)集 train_size = int(len(time_series_data) * 0.8) train, test = time_series_data[:train_size], time_series_data[train_size:] # 可視化訓(xùn)練集和測試集 train.plot(label='Training Data') test.plot(label='Test Data') plt.legend() plt.show()
5. 構(gòu)建和訓(xùn)練 ARIMA 模型
ARIMA 模型的參數(shù)包括 p(自回歸部分的階數(shù))、d(差分階數(shù))、q(移動平均部分的階數(shù))??梢酝ㄟ^ ACF 和 PACF 圖或網(wǎng)格搜索來確定這些參數(shù)。在這里,我們將使用簡單的參數(shù)值。
# 創(chuàng)建 ARIMA 模型 model = ARIMA(train, order=(5, 1, 0)) # 這里 (p, d, q) = (5, 1, 0) model_fit = model.fit() # 打印模型總結(jié) print(model_fit.summary())
6. 進(jìn)行預(yù)測
訓(xùn)練好模型后,我們可以對測試集進(jìn)行預(yù)測,并與實際值進(jìn)行比較。
# 進(jìn)行預(yù)測 predictions = model_fit.forecast(steps=len(test)) predictions_series = pd.Series(predictions, index=test.index) # 可視化預(yù)測結(jié)果 train.plot(label='Training Data') test.plot(label='Test Data') predictions_series.plot(label='Predictions') plt.legend() plt.show()
7. 評估模型
最后,我們評估模型的性能,可以使用均方誤差(MSE)、平均絕對誤差(MAE)等指標(biāo)。
# 計算均方誤差 mse = mean_squared_error(test, predictions_series) print(f'Mean Squared Error: {mse}')
8. 完整代碼
import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from sklearn.metrics import mean_squared_error from statsmodels.tsa.stattools import adfuller # 生成模擬時間序列數(shù)據(jù) np.random.seed(0) date_range = pd.date_range(start='2020-01-01', periods=100, freq='D') data = np.random.normal(0, 1, size=(100,)).cumsum() time_series_data = pd.Series(data, index=date_range) # 檢查時間序列的平穩(wěn)性 result = adfuller(time_series_data) print(f'ADF Statistic: {result[0]}') print(f'p-value: {result[1]}') # 拆分?jǐn)?shù)據(jù)集 train_size = int(len(time_series_data) * 0.8) train, test = time_series_data[:train_size], time_series_data[train_size:] # 創(chuàng)建和訓(xùn)練 ARIMA 模型 model = ARIMA(train, order=(5, 1, 0)) model_fit = model.fit() # 進(jìn)行預(yù)測 predictions = model_fit.forecast(steps=len(test)) predictions_series = pd.Series(predictions, index=test.index) # 評估模型 mse = mean_squared_error(test, predictions_series) print(f'Mean Squared Error: {mse}') # 可視化 train.plot(label='Training Data') test.plot(label='Test Data') predictions_series.plot(label='Predictions') plt.legend() plt.show()
總結(jié)
上述步驟展示了一個簡單的時間序列預(yù)測流程。根據(jù)實際情況,你可以選擇更復(fù)雜的模型,如 SARIMA、季節(jié)性分解、或使用機器學(xué)習(xí)和深度學(xué)習(xí)模型(如 LSTM)。此外,可以使用更復(fù)雜的特征工程和模型選擇方法來進(jìn)一步提高預(yù)測的準(zhǔn)確性。
以上就是使用python進(jìn)行時間序列預(yù)測的流程的詳細(xì)內(nèi)容,更多關(guān)于python時間序列預(yù)測的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python 實現(xiàn)的發(fā)送郵件模板【普通郵件、帶附件、帶圖片郵件】
這篇文章主要介紹了python 實現(xiàn)的發(fā)送郵件模板,包含Python發(fā)送普通郵件、帶附件及帶圖片郵件相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2019-07-07python實現(xiàn)文本進(jìn)度條 程序進(jìn)度條 加載進(jìn)度條 單行刷新功能
這篇文章主要介紹了python實現(xiàn)文本進(jìn)度條 程序進(jìn)度條 加載進(jìn)度條 單行刷新功能,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07Python GUI教程之在PyQt5中使用數(shù)據(jù)庫的方法
Qt平臺對SQL編程有著良好的支持,PyQt5也一并繼承了過來,這篇文章主要介紹了Python GUI教程之在PyQt5中使用數(shù)據(jù)庫的方法,需要的朋友可以參考下2021-09-09python 實現(xiàn)網(wǎng)上商城,轉(zhuǎn)賬,存取款等功能的信用卡系統(tǒng)
本篇文章主要介紹 基于python 實現(xiàn)信用卡系統(tǒng),附有代碼實例,對于用python 開發(fā)網(wǎng)絡(luò)上傳系統(tǒng)具有參考價值,有需要的朋友可以看下2016-07-07教你學(xué)會通過python的matplotlib庫繪圖
今天教大家如何學(xué)會通過python的matplotlib庫繪圖,文中有非常詳細(xì)的圖文解說及代碼示例,對正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05