Upload README.md with huggingface_hub
Browse files
README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## `.pkl` 文件是什么?
|
| 2 |
+
|
| 3 |
+
PKL = Pickle,是 Python 的一种序列化格式。
|
| 4 |
+
|
| 5 |
+
简单理解:就是把一个 Python 对象(比如训练好的模型)**"冷冻"保存**到硬盘上,
|
| 6 |
+
需要的时候再**"解冻"**加载回来,完全不需要重新训练。
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
## 两个文件分别存了什么?
|
| 11 |
+
|
| 12 |
+
### `bike_availability_model.pkl`
|
| 13 |
+
- 存储了训练好的 Random Forest 模型
|
| 14 |
+
- 包含所有学习到的决策树、权重等信息
|
| 15 |
+
- 加载后可以直接调用 `.predict()` 进行预测
|
| 16 |
+
|
| 17 |
+
### `model_features.pkl`
|
| 18 |
+
- 存储了特征列表:`['station_id', 'capacity', 'lat', 'lon', 'hour', 'day', 'day_of_week', 'is_weekend', 'avg_temperature', 'avg_humidity', 'avg_pressure']`
|
| 19 |
+
- 确保预测时特征的**顺序和名称**与训练时完全一致
|
| 20 |
+
- 顺序错了预测结果就会出错
|
| 21 |
+
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
## 如何在 Flask 中使用?
|
| 25 |
+
```python
|
| 26 |
+
import pickle
|
| 27 |
+
import pandas as pd
|
| 28 |
+
|
| 29 |
+
# 1. 加载模型和特征列表(Flask启动时执行一次)
|
| 30 |
+
with open('bike_availability_model.pkl', 'rb') as f:
|
| 31 |
+
model = pickle.load(f)
|
| 32 |
+
|
| 33 |
+
with open('model_features.pkl', 'rb') as f:
|
| 34 |
+
features = pickle.load(f)
|
| 35 |
+
|
| 36 |
+
# 2. 预测时使用
|
| 37 |
+
def predict_bikes(station_id, capacity, lat, lon,
|
| 38 |
+
hour, day, day_of_week, is_weekend,
|
| 39 |
+
avg_temperature, avg_humidity, avg_pressure):
|
| 40 |
+
|
| 41 |
+
# 构造输入数据,顺序必须与features一致
|
| 42 |
+
input_data = pd.DataFrame([{
|
| 43 |
+
'station_id': station_id,
|
| 44 |
+
'capacity': capacity,
|
| 45 |
+
'lat': lat,
|
| 46 |
+
'lon': lon,
|
| 47 |
+
'hour': hour,
|
| 48 |
+
'day': day,
|
| 49 |
+
'day_of_week': day_of_week,
|
| 50 |
+
'is_weekend': is_weekend,
|
| 51 |
+
'avg_temperature': avg_temperature,
|
| 52 |
+
'avg_humidity': avg_humidity,
|
| 53 |
+
'avg_pressure': avg_pressure
|
| 54 |
+
}])[features] # 用features确保列顺序正确
|
| 55 |
+
|
| 56 |
+
prediction = model.predict(input_data)
|
| 57 |
+
return int(round(prediction[0]))
|
| 58 |
+
```
|