Python实现灰色预测模型:城市用水量预测与代码实战
Python实现灰色预测模型:城市用水量预测与代码实战
本文将介绍如何使用Python构建灰色预测模型,并将其应用于城市用水量预测。文章包含完整的代码示例,涵盖数据读取、模型构建、模型检验、未来预测以及结果可视化等步骤,帮助您快速掌握灰色预测模型的应用。
1. 数据准备
首先,我们需要准备历史的城市用水量数据。假设数据存储在名为'water_data.csv'的CSV文件中,包含'Year'和'Water Consumption'两列,分别表示年份和对应年份的用水量。pythonimport numpy as npimport pandas as pdfrom matplotlib import pyplot as plt
读取数据data = pd.read_csv('water_data.csv')x = data['Year'].valuesy = data['Water Consumption'].values
2. 构建灰色预测模型
灰色预测模型是一种适用于小样本、贫信息数据预测的模型。其核心思想是利用原始数据序列累加生成新的数据序列,建立微分方程模型,并通过求解微分方程实现预测。python# 灰色预测模型def grey_model(x, y): n = len(x) X = np.array([x, np.ones(n)]).T Y = np.array(y).reshape(-1, 1) theta = np.linalg.inv(X.T @ X) @ X.T @ Y a = theta[0][0] b = theta[1][0] y_predict = (y[0] - b/a) * np.exp(-a * x) + b/a return y_predict
模型构建y_predict = grey_model(x, y)
3. 模型检验
构建模型后,我们需要对模型的预测精度进行评估。常用的指标包括残差、平均残差、相对误差、平均相对误差和模型精度等。python# 检验模型def model_check(y, y_predict): n = len(y) e = np.abs(y - y_predict) # 残差 e_average = np.mean(e) # 残差平均值 relative_error = e / y # 相对误差 relative_error_average = np.mean(relative_error) # 相对误差平均值 model_accuracy = 1 - relative_error_average # 模型精度 return e, e_average, relative_error, relative_error_average, model_accuracy
e, e_average, relative_error, relative_error_average, model_accuracy = model_check(y, y_predict)
打印检验结果print('残差:', e)print('平均残差:', e_average)print('相对误差:', relative_error)print('平均相对误差:', relative_error_average)print('模型精度:', model_accuracy)
4. 未来预测
模型检验通过后,我们可以使用模型预测未来的城市用水量。python# 预测未来数据future_years = np.array(range(2022, 2030))future_predict = grey_model(future_years, y)
print('未来预测值:', future_predict)
5. 结果可视化
为了更直观地展示预测结果,我们可以使用matplotlib库绘制折线图。python# 绘图plt.figure(figsize=(10, 6))plt.plot(x, y, marker='o', label='实际值')plt.plot(x, y_predict, marker='x', linestyle='--', label='预测值')plt.plot(future_years, future_predict, marker='s', linestyle='--', label='未来预测值')plt.xlabel('年份')plt.ylabel('城市用水量')plt.title('灰色预测模型预测城市用水量')plt.legend()plt.show()
总结
本文介绍了如何使用Python构建灰色预测模型,并以城市用水量预测为例,详细讲解了模型构建、检验、预测以及结果可视化的步骤。灰色预测模型适用于小样本、贫信息数据的预测,在实际应用中具有较高的价值。
需要注意的是:
- 以上代码中的CSV文件'water_data.csv'应与代码文件在同一目录下。* 数据应按照年份顺序排列。* 可以根据实际情况修改文件名、列名以及预测的未来年份。
原文地址: https://www.cveoy.top/t/topic/1xZ 著作权归作者所有。请勿转载和采集!