在python3.11中使用‘C:\Users\lenovo\Desktop\data.csv’中的数据严格按照步骤进行ARIMA模型调参并预测
时间: 2023-06-30 19:07:53 浏览: 53
好的,下面是使用Python 3.11进行ARIMA模型调参和预测的步骤:
1. 导入必要的库:
```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. 读取数据:
```python
data = pd.read_csv('C:/Users/lenovo/Desktop/data.csv', index_col=0, parse_dates=True)
```
这里假设数据文件为csv格式,路径为C:/Users/lenovo/Desktop/data.csv,第一列为日期,因此使用index_col=0将其作为索引,parse_dates=True用于将日期解析为datetime格式。
3. 数据预处理:
```python
# 将数据按照月份进行聚合
data_month = data.resample('M').mean()
# 对数据进行差分
diff = data_month.diff().dropna()
# 绘制差分后的时序图
plt.plot(diff)
plt.show()
```
这里将数据按照月份进行聚合得到月均值,然后对数据进行一阶差分,得到平稳的时间序列数据。
4. 确定ARIMA模型的参数:
```python
# 设置ARIMA模型参数的取值范围
p = range(0, 3)
d = range(0, 2)
q = range(0, 3)
# 遍历参数空间,选择最优的ARIMA模型
best_score, best_cfg = float("inf"), None
for i in p:
for j in d:
for k in q:
order = (i, j, k)
try:
model = ARIMA(data_month, order=order)
model_fit = model.fit()
y_pred = model_fit.predict()
mse = mean_squared_error(data_month, y_pred)
if mse < best_score:
best_score, best_cfg = mse, order
print('ARIMA%s MSE=%.3f' % (order, mse))
except:
continue
print('Best ARIMA%s MSE=%.3f' % (best_cfg, best_score))
```
这里使用了一个简单的网格搜索方法,遍历ARIMA模型参数空间中的所有组合,选择MSE最小的模型作为最优模型。
5. 训练并预测ARIMA模型:
```python
# 训练最优的ARIMA模型
model = ARIMA(data_month, order=best_cfg)
model_fit = model.fit()
# 预测未来12个月的数据
y_pred = model_fit.forecast(steps=12)
# 绘制预测结果和原始数据
plt.plot(data_month)
plt.plot(y_pred, color='red')
plt.show()
```
这里使用最优的ARIMA模型进行训练,并预测未来12个月的数据,然后将预测结果和原始数据绘制在同一张图上,以便对比。
完整代码如下:
```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
# 读取数据
data = pd.read_csv('C:/Users/lenovo/Desktop/data.csv', index_col=0, parse_dates=True)
# 将数据按照月份进行聚合
data_month = data.resample('M').mean()
# 对数据进行差分
diff = data_month.diff().dropna()
# 绘制差分后的时序图
plt.plot(diff)
plt.show()
# 设置ARIMA模型参数的取值范围
p = range(0, 3)
d = range(0, 2)
q = range(0, 3)
# 遍历参数空间,选择最优的ARIMA模型
best_score, best_cfg = float("inf"), None
for i in p:
for j in d:
for k in q:
order = (i, j, k)
try:
model = ARIMA(data_month, order=order)
model_fit = model.fit()
y_pred = model_fit.predict()
mse = mean_squared_error(data_month, y_pred)
if mse < best_score:
best_score, best_cfg = mse, order
print('ARIMA%s MSE=%.3f' % (order, mse))
except:
continue
print('Best ARIMA%s MSE=%.3f' % (best_cfg, best_score))
# 训练最优的ARIMA模型
model = ARIMA(data_month, order=best_cfg)
model_fit = model.fit()
# 预测未来12个月的数据
y_pred = model_fit.forecast(steps=12)
# 绘制预测结果和原始数据
plt.plot(data_month)
plt.plot(y_pred, color='red')
plt.show()
```
执行完毕后,就可以得到ARIMA模型的预测结果了。