智慧交通数据分析系统 python 时间序列预测算法 爬虫 出行速度预测 拥堵预测
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from statsmodels.tsa.arima_model import ARIMA
from fbprophet import Prophet
# 读取数据
data = pd.read_csv('data.csv')
# 数据预处理
scaler = MinMaxScaler()
data_scaled = scaler.fit_transform(data['count'].values.reshape(-1, 1))
data_scaled = pd.DataFrame(data_scaled, columns=['count_scaled'])
# 训练ARIMA模型
def train_arima(data, p, d, q):
model = ARIMA(data, order=(p, d, q))
model_fit = model.fit()
return model_fit
# 使用Prophet模型
def train_prophet(data):
model = Prophet()
data['y'] = data['count_scaled']
model.fit(data[['ds', 'y']])
return model
# 预测
def predict(model, steps_ahead):
future = model.make_future_dataframe(periods=steps_ahead)
forecast = model.predict(future)
return scaler.inverse_transform(forecast['yhat'].values)
# 选择合适的ARIMA参数
p, d, q = 0, 1, 1 # 示例参数
model_arima = train_arima(data_scaled, p, d, q)
forecast_arima = predict(model_arima, 30) # 预测30天
# 使用Prophet模型进行预测
model_prophet = train_prophet(data_scaled)
forecast_prophet = predict(model_prophet, 30) # 预测30天
# 计算MSE
mse_arima = mean_squared_error(data_scaled['count_scaled'].values, forecast_arima)
mse_prophet = mean_squared_error(data_scaled['count_scaled'].values, forecast_prophet)
# 输出结果
print(f"ARIMA MSE: {mse_arima}")
print(f"Prophet MSE: {mse_prophet}")
这段代码展示了如何使用ARIMA和Prophet模型进行时间序列预测,并计算预测的平均平方误差(MSE)。这是一个实用的教学示例,可以帮助开发者理解如何在实际应用中应用时间序列分析方法。
评论已关闭