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 # 读取csv文件 data = pd.read_csv("77.csv", header=None) # 划分训练集和测试集 train_size = int(len(data) * 0.7) train_data, test_data = data[:train_size], data[train_size:] # 将时间编号设置为索引 train_data.set_index(0, inplace=True) test_data.set_index(0, inplace=True) # 删除原来的索引列 train_data.index.name = None test_data.index.name = None # 转换为时间序列 train_ts = train_data[1] test_ts = test_data[1] # 训练ARIMA模型 model = ARIMA(train_ts, order=(1, 1, 1)) model_fit = model.fit() # 预测测试集数据 predictions = model_fit.forecast(steps=len(test_ts))[0] # 计算rmse rmse = np.sqrt(mean_squared_error(test_ts, predictions)) print('Test RMSE: %.3f' % rmse) # 绘制图像 plt.figure(figsize=(10, 6)) plt.plot(train_ts, label='Train') plt.plot(test_ts, label='Test') plt.plot(test_ts.index, predictions, label='Predictions') plt.xlabel('Time(h)') plt.ylabel('kwh') plt.title('ARIMA Model Predictions') plt.legend() plt.show()以上代码报错如下,请解释并给出修改后的代码KeyError: 0
时间: 2024-02-01 22:02:27 浏览: 60
这个 KeyError 报错是因为你在设置索引的时候使用了一个不存在的列名 0 ,因此需要修改代码中的索引设置。可以将以下两行代码:
```python
train_data.set_index(0, inplace=True)
test_data.set_index(0, inplace=True)
```
修改为:
```python
train_data.set_index(train_data.columns[0], inplace=True)
test_data.set_index(test_data.columns[0], inplace=True)
```
这样就会将索引设置为第一列的列名,而不是使用数字索引。这个问题解决后,还需要将最后一行的图像绘制代码修改一下,因为预测结果的时间索引与测试集数据的时间索引是相同的,所以需要将以下代码:
```python
plt.plot(test_ts.index, predictions, label='Predictions')
```
修改为:
```python
plt.plot(test_data.index, predictions, label='Predictions')
```
这样就可以正确绘制出预测结果的图像了。
相关问题
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.arima_model import ARIMAfrom sklearn.metrics import mean_squared_errorimport pymysqlimport time, osimport reimport requestsimport urllibfrom datetime import datetimefrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 导入模块import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.arima_model import ARIMAfrom sklearn.metrics import mean_squared_errorimport pymysqlfrom datetime import datetimefrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 连接数据库connect = pymysql.connect(host='localhost', # 本地数据库 user='root', password='123456', port=3306, charset='utf8', database='sheji') # 数据库名称cur = connect.cursor()# 读取数据try: select_sqli = "SELECT time,xiaoliang FROM sale where chexing='海豚';" cur.execute(select_sqli) data = pd.DataFrame(cur.fetchall(), columns=['time', 'xiaoliang'])except Exception as e: print("读取数据失败:", e)else: print("读取数据成功")# 转换时间格式data['time'] = pd.to_datetime(data['time'], format='%Y-%m')data = data.set_index('time')diff_data = data.diff().dropna()# 绘制自相关图和偏自相关图plot_acf(diff_data)plot_pacf(diff_data)# 确定 ARIMA 模型的参数p = 1d = 1q = 1model = ARIMA(data, order=(p, d, q))model_fit = model.fit(disp=0)# 预测销量y_pred = model_fit.predict(len(data), len(data) + 11, typ='levels')# 绘制预测结果plt.plot(data)plt.plot(y_pred, color='red')plt.show()# 关闭数据库连接cur.close()connect.close()请将这段代码改为移动平均模型
下面是将上述代码改为移动平均模型的示例:
```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
import pymysql
from datetime import datetime
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
# 连接数据库
connect = pymysql.connect(host='localhost', # 本地数据库
user='root',
password='123456',
port=3306,
charset='utf8',
database='sheji')
# 数据库查询语句
select_sql = "SELECT time, xiaoliang FROM sale WHERE chexing='海豚';"
# 读取数据
try:
data = pd.read_sql(select_sql, connect, index_col='time', parse_dates=True)
except Exception as e:
print("读取数据失败:", e)
else:
print("读取数据成功")
# 移动平均模型
window_size = 3
data_ma = data.rolling(window_size).mean()
data_ma.dropna(inplace=True)
# 绘制自相关图和偏自相关图
plot_acf(data_ma)
plot_pacf(data_ma)
# 选择移动平均模型的滞后阶数
q = 1
# 构建移动平均模型并拟合数据
model = ARIMA(data_ma, order=(0, 0, q))
model_fit = model.fit(disp=False)
# 预测销量并绘图
y_pred = model_fit.predict(len(data_ma), len(data_ma) + 11, typ='levels')
plt.plot(data_ma, label='Original Data')
plt.plot(y_pred, color='red', label='Predicted Data')
plt.legend()
plt.show()
# 关闭数据库连接
connect.close()
```
以上代码通过 rolling() 函数进行滑动窗口处理,计算移动平均值,并选择滞后阶数,然后构建移动平均模型,拟合数据,并进行预测和绘图。需要注意的是,移动平均模型需要对数据进行平稳化处理,否则预测结果可能会出现误差。
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 import pymysql import time,os import re import requests import pandas as pd import urllib # ---------连接-------------- connect = pymysql.connect(host='localhost', # 本地数据库 user='root', password='123456', port=3306, charset='utf8') #服务器名,账户,密码,数据库名称 cur = connect.cursor() print(cur) # 读取数据 try: select_sqli = "SELECT time,xiaoliang FROM sheji.sale where chexing='海豚' ;" cur.execute(select_sqli) data=cur.fetchall() except Exception as e: print("创建数据表失败:", e) else: print("创建数据表成功;") #data = pd.read_csv('car_sales.csv', index_col='Month', parse_dates=True) time=[] for i in range(len(data)): time.append(datetime.strptime(data[i][0], '%Y-%m')) print(time)哪里有错
在这段代码中,你没有导入 `datetime` 模块,所以不能使用 `datetime.strptime()` 函数。你可以在代码开头添加 `from datetime import datetime` 来导入 `datetime` 模块,并修正报错问题。此外,在读取 `data` 时,你可以直接使用 `pd.DataFrame()` 函数将其转化为 Pandas DataFrame 格式,而不需要手动解析时间和数据。修改后的代码如下:
```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
import pymysql
import time,os
import re
import requests
import urllib
from datetime import datetime
# ---------连接--------------
connect = pymysql.connect(host='localhost', # 本地数据库
user='root',
password='123456',
port=3306,
charset='utf8') #服务器名,账户,密码,数据库名称
cur = connect.cursor()
print(cur)
# 读取数据
try:
select_sqli = "SELECT time,xiaoliang FROM sheji.sale where chexing='海豚';"
cur.execute(select_sqli)
data = pd.DataFrame(cur.fetchall(), columns=['time', 'xiaoliang'])
except Exception as e:
print("读取数据失败:", e)
else:
print("读取数据成功")
# 转换时间格式
data['time'] = pd.to_datetime(data['time'], format='%Y-%m')
print(data)
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)