一、前言
随着大数据技术的发展,天气数据分析与预测在农业、交通、旅游等领域发挥着越来越重要的作用。本文介绍一个基于Python技术的天气数据分析与预测系统,采用Django+Vue3前后端分离架构,结合机器学习算法实现天气数据的可视化分析与温度预测。
二、系统架构设计
2.1 技术栈
-
前端框架:Vue3 + ElementPlus UI组件库
-
数据可视化:ECharts 5.0
-
后端框架:Django 5.0 + Django REST framework
-
机器学习:scikit-learn 1.2
-
数据库:MySQL 8.0
-
开发工具:PyCharm
2.2 系统架构图
┌─────────────────────────────────────────────────┐
│ 前端展示层 │
│ ┌───────────┐ ┌───────────┐ ┌─────────────┐ │
│ │ 登录注册 │ │ 数据可视化 │ │ 预测结果展示 │ │
│ └───────────┘ └───────────┘ └─────────────┘ │
└─────────────────────────────────────────────────┘
▲
│
┌─────────────────────────────────────────────────┐
│ Django后端API │
│ ┌───────────┐ ┌───────────┐ ┌─────────────┐ │
│ │ 用户认证 │ │ 数据处理 │ │ 模型预测接口 │ │
│ └───────────┘ └───────────┘ └─────────────┘ │
└─────────────────────────────────────────────────┘
▲
│
┌─────────────────────────────────────────────────┐
│ 数据存储层 │
│ ┌───────────────────────────────────────────┐ │
│ │ MySQL 8.0数据库 │ │
│ └───────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
三、核心功能实现
3.1 用户管理模块(部分代码展示)
3.2 天气数据爬取与存储(部分代码展示)
def get_weather_data(html):
data =[]
bs = BeautifulSoup(html, "html.parser")
try:
first_panel = bs.find('div', class_='c-panel')
tbody = first_panel.find('tbody')
if tbody:
trs = tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
week = tds[0].find('p', class_='week').text.strip()
date = tds[0].find('p', class_='date').text.strip()
weather_condition = tds[1].text.strip().replace('转', '-')
temperature = tds[2].text.strip().replace('℃', '')
min_temperature = temperature.split('~')[0].strip()
max_temperature = temperature.split('~')[1].strip()
wind = tds[3].text.strip()
wind_direction = wind.split('<')[0].strip().split('转')
if wind_direction[0]:
wind_direction = wind_direction[0].strip()
else:
wind_direction = wind_direction[1].strip()
if bool(re.search(r'\d', wind_direction)):
wind_direction = wind_direction.split('风')[0]+'风'
if '<' in wind:
wind_force = wind.split('<')[1].strip().split('级')[0] + '级'
else:
wind_force = wind[-2:]
print(week,date,weather_condition,min_temperature,max_temperature,wind_force,wind_direction)
data.append([date,week,weather_condition,min_temperature,max_temperature,wind_force,wind_direction])
print('*'*30)
else:
print("未找到<tbody>元素")
return data
except Exception as e:
print(e)
return data
3.3 数据可视化实现(部分代码展示)
def get_wind_force(city='北京', year=2024):
"""统计指定城市和年份的风力等级分布"""
# 筛选指定城市和年份的数据
city_data = Weather.objects.filter(
city=city,
date__year=year
)
# 统计各风力等级出现的天数
wind_stats = city_data.values('wind_force').annotate(
天数=Count('wind_force')
).order_by('-天数')
# 转换为列表
x = [item['wind_force'] for item in wind_stats]
y = [item['天数'] for item in wind_stats]
echarts_data = {
'toolbox': {
'feature': {
'saveAsImage': {},
'dataView': {},
'restore': {},
'dataZoom': {},
'magicType': {
'type': ['bar', 'line']
}
}
},
'xAxis': {
'type': 'category',
'data': x,
'axisLabel': {
'rotate': 30
}
},
'yAxis': {
'type': 'value',
'name': '天数'
},
'tooltip': {
'borderColor': '#FF0000',
'trigger': 'axis',
'axisPointer': {
'type': 'shadow'
},
'formatter': '{b}:{c}天'
},
'series': [
{
'data': y,
'type': 'bar',
'smooth': 'true',
'markPoint': {
'data': [
{'type': 'max', 'name': '最大值'},
{'type': 'min', 'name': '最小值'}
]
},
'markLine': {
'data': [{'type': 'average', 'name': '平均值'}]
},
}
]
}
return echarts_data
3.4 温度预测模型(部分代码展示)
def main(target_var, city, predict_date="2026-01-01", train=True, save=True):
sql = f"SELECT date, {target_var} FROM weather_data WHERE city = '{city}'"
if train:
# 1. 加载数据
print(f"执行SQL查询: {sql}")
records = get_mysql_data(sql)
df = pd.DataFrame(records, columns=['date', target_var])
# 检查数据是否为空
if df.empty:
raise ValueError("查询结果为空,请检查SQL语句")
# 2. 数据预处理
df = process_date_features(df)
# 3. 准备特征和目标
Y = df[target_var]
X = df.drop(['date', target_var], axis=1)
# 保存训练列名
training_columns = X.columns.tolist()
# 4. 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(
X, Y, test_size=0.2, random_state=1, shuffle=True
)
# 5. 网格搜索配置
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [None, 10, 20],
'max_features': ['sqrt', 0.7, 0.8]
}
# 初始化随机森林回归器
rf = RandomForestRegressor(random_state=1)
# 网格搜索+交叉验证
grid = GridSearchCV(
estimator=rf,
param_grid=param_grid,
cv=3,
n_jobs=-1,
scoring='r2'
)
grid.fit(x_train, y_train)
# 获取最优模型
best_rf = grid.best_estimator_
print("最优参数:", grid.best_params_)
# 模型评估
test_pred = best_rf.predict(x_test)
mse = mean_squared_error(y_test, test_pred)
rmse = np.sqrt(mse)
if save:
save_model(best_rf, target_var, rmse, training_columns, city)
model = best_rf
else:
# 加载已保存的模型
model, rmse, training_columns = load_model(target_var, city)
if not model:
return None
# 7. 预测指定日期的温度
result = predict_temperature(model, predict_date, rmse, training_columns)
return model, rmse, training_columns, result, target_var
四、系统特色与创新点
-
多模型对比预测:同时采用线性回归和随机森林模型进行温度预测,可对比预测效果
-
动态可视化大屏:基于ECharts实现可交互的动态数据可视化展示
-
权限精细化管理:支持管理员与普通用户不同权限级别的功能访问
-
自动化数据采集:内置天气数据爬取功能,保证数据持续更新
五、系统展示
5.1 登录界面
5.2 数据可视化大屏
5.3 数据爬取展示
5.4 预测结果展示
六、总结与展望
本文实现的天气数据分析与预测系统整合了Python Web开发与机器学习技术,提供了从数据采集、存储、分析到预测的全流程解决方案。未来可以考虑:
-
增加更多预测指标(如降水量、风速等)
-
引入深度学习模型提升预测精度