IoT-For-Beginners 生长度日(GDD)可视化实战:基于 Jupyter Notebook 的温度数据分析
【免费下载链接】IoT-For-Beginners12 Weeks, 24 Lessons, IoT for All!项目地址: https://gitcode.com/GitHub_Trending/io/IoT-For-Beginners
本文围绕 IoT-For-Beginners 课程农场模块第一课《Predict plant growth with IoT》的课后作业展开,完整讲解如何将 IoT 温度传感器采集的数据,通过 Jupyter Notebook 完成温度曲线可视化与生长度日(Growing Degree Days, GDD)计算。读完本文,你将掌握从 MQTT 服务器落盘
temperature.csv、搭建 Jupyter 分析环境、到按天聚合温度并计算 GDD 的完整实操链路。
作业背景:为什么要用 Notebook 分析 GDD
在前序课程中,你已经通过 IoT 设备(Wio Terminal、Raspberry Pi 或虚拟设备)配合温度传感器采集环境温度,并通过 MQTT 将遥测数据发布到test.mosquitto.org这类公共代理。服务器端代码订阅遥测主题后,将每条消息追加写入 CSV 文件。这一流程的完整代码位于 2-farm/lessons/1-predict-plant-growth/code-server/temperature-sensor-server/app.py。
GDD 的计算需要至少一整天的最高温和最低温,因此可靠的数据必须连续采集数天。而 Jupyter Notebook 将说明文字与可执行代码组织在称为cell(单元格)的区块中,非常适合逐步完成「读取 CSV → 绘制温度曲线 → 按天聚合 → 计算 GDD」的分析过程。本作业提供的 notebook 位于 2-farm/lessons/1-predict-plant-growth/code-notebook/gdd.ipynb,你可以逐格运行,也可以直接修改代码——例如调整用于你目标作物的基准温度base_temperature。
前置条件:确保服务器持续运行
要获得连续的 GDD 数据,必须保证服务器代码在 IoT 设备活跃的整个时间段内持续运行。有两条途径:
- 修改电源管理设置:让运行服务器代码的电脑不会在空闲时休眠,例如禁用系统自动睡眠;
- 运行保活脚本:使用如
keep-system-active之类的 Python 保活脚本,周期性模拟输入以阻止系统进入睡眠。
在数据采集阶段需要注意:若使用虚拟 IoT 设备,建议在 CounterFit 应用中勾选温度传感器的Random复选框并设置合理范围(Min/Max),避免每次读取都返回相同数值、导致最高温与最低温失真。相关设置说明可参见 2-farm/lessons/1-predict-plant-growth/virtual-device-temp.md。
服务器代码如何生成 temperature.csv
理解 Notebook 分析的数据来源很有必要。服务器端temperature-sensor-server/app.py的关键逻辑如下:
from os import path import csv from datetime import datetime temperature_file_name = 'temperature.csv' fieldnames = ['date', 'temperature'] if not path.exists(temperature_file_name): with open(temperature_file_name, mode='w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() def handle_telemetry(client, userdata, message): payload = json.loads(message.payload.decode()) with open(temperature_file_name, mode='a') as temperature_file: temperature_writer = csv.DictWriter(temperature_file, fieldnames=fieldnames) temperature_writer.writerow({'date' : datetime.now().astimezone().replace(microsecond=0).isoformat(), 'temperature' : payload['temperature']})这段代码完成了三件事:
- 初始化 CSV 结构:定义文件名
temperature.csv与列头date,temperature;若文件不存在则创建并写入表头; - 订阅遥测主题:
mqtt_client.subscribe(client_telemetry_topic),其中主题名为id + '/telemetry'; - 追加写入数据:
handle_telemetry回调中,将当前时间(ISO 8601 格式、带时区、不含微秒)与消息中的temperature作为一行追加到文件末尾。
最终的 CSV 内容形如:
date,temperature 2021-04-19T17:21:36-07:00,25 2021-04-19T17:31:36-07:00,24 2021-04-19T17:41:36-07:00,25该文件包含两列:date(服务器收到消息的时刻)与temperature(来自遥测消息的温度值)。temperature.csv就是 Notebook 分析的输入数据,也是本作业后续所有步骤的基础。
环境搭建:创建 gdd-calculation 项目
按照作业要求,按以下步骤准备分析环境:
1. 创建项目文件夹
mkdir gdd-calculation2. 获取 Notebook 与数据
- 将 2-farm/lessons/1-predict-plant-growth/code-notebook/gdd.ipynb 下载并复制到
gdd-calculation文件夹; - 将 MQTT 服务器生成的
temperature.csv复制到同一文件夹——Notebook 使用相对路径读取该文件,二者必须同目录。
3. 创建 Python 虚拟环境
python -m venv .venv4. 安装依赖包
pip install --upgrade pip pip install pandas pip install matplotlib pip install jupyter各依赖的作用:
| 包名 | 用途 |
|---|---|
pandas | 读取 CSV、将时间字符串解析为日期、按天分组聚合 |
matplotlib | 绘制温度随时间变化的曲线图 |
jupyter | 提供 Notebook 运行环境,在浏览器中交互式执行 |
5. 启动 Notebook
jupyter notebook gdd.ipynbJupyter 启动后会打开默认浏览器并加载gdd.ipynb。作业配套的运行效果截图如下:
Notebook 逐步解析:从 CSV 到 GDD
gdd.ipynb(nbformat 4,Python 3 内核)由若干 markdown 说明格与 Python 代码格组成。下面按执行顺序拆解每个代码格的作用。
1. 设置基准温度
Notebook 首先要求设置作物的基准温度(base temperature),即该作物开始生长的最低日平均温度:
base_temperature = 10修改这个值即可适配不同作物。课程 README 中给出了一个标准示例:玉米的基准温度为 10°C,不同品种需要 800~2700 个 GDD 才能成熟(见 2-farm/lessons/1-predict-plant-growth/README.md)。
2. 加载 CSV 数据
import pandas as pd import matplotlib.pyplot as plt # Read the temperature CSV file df = pd.read_csv('temperature.csv')pd.read_csv将temperature.csv读入 DataFrame。此时date仍是字符串,temperature为数值。
3. 绘制温度曲线
plt.figure(figsize=(20, 10)) plt.plot(df['date'], df['temperature']) plt.xticks(rotation='vertical');这段代码以日期为横轴、温度为纵轴绘制完整时间序列曲线;figsize=(20, 10)放大画布、rotation='vertical'让日期刻度竖直排列,避免密集时间戳互相重叠。可视化能让你直观检查数据是否连续、是否有异常值。
4. 按天聚合最高温与最低温
GDD 计算需要的是每天的 T_max 与 T_min,因此要将逐条记录按日期分组:
# Convert datetimes to pure dates so we can group by the date df['date'] = pd.to_datetime(df['date']).dt.date # Group the data by date so it can be analyzed by date data_by_date = df.groupby('date') # Get the minimum and maximum temperatures for each date min_by_date = data_by_date.min() max_by_date = data_by_date.max() # Join the min and max temperatures into one dataframe and flatten it min_max_by_date = min_by_date.join(max_by_date, on='date', lsuffix='_min', rsuffix='_max') min_max_by_date = min_max_by_date.reset_index()关键点在于pd.to_datetime(df['date']).dt.date:先把带时分秒的时间戳截断为纯日期,才能正确按天groupby。随后分别对每天取min()与max(),再通过join合并成一张同时含temperature_min与temperature_max的表。
5. 计算 GDD
GDD 使用课程中给出的简化公式:
GDD = (T_max + T_min) / 2 − T_base
即「当日平均温度减去作物基准温度」。Notebook 中通过函数逐行计算:
def calculate_gdd(row): return ((row['temperature_max'] + row['temperature_min']) / 2) - base_temperature # Calculate the GDD for each row min_max_by_date['gdd'] = min_max_by_date.apply(lambda row: calculate_gdd(row), axis=1) # Print the results print(min_max_by_date[['date', 'gdd']].to_string(index=False))apply(..., axis=1)按行调用calculate_gdd,把计算结果写入新列gdd,最后打印每日date与gdd的对照表。
一个手算核对示例
课程 README 给出了草莓的手算示例,可用于核对 Notebook 输出是否正确(草莓基准温度 10°C):
- 当日最高温 25°C,最低温 12°C;
- 25 + 12 = 37,37 / 2 = 18.5,18.5 − 10 =8.5 GDD。
草莓约需 250 个 GDD 才能结果,因此 8.5 GDD 表明距离成熟仍有相当距离。用同样数据手工验证 Notebook 的结果,是确认分析正确性的好习惯。
数据采集的质量要求与评分标准
本作业的评估围绕两个维度展开,数据质量直接决定 GDD 计算的可靠程度:
| 标准 | 优秀 | 合格 | 待改进 |
|---|---|---|---|
| 数据采集 | 至少 2 个完整天的数据 | 至少 1 个完整天的数据 | 只采集到部分数据 |
| GDD 计算 | 成功运行 Notebook 并计算出 GDD | 成功运行 Notebook | 无法运行 Notebook |
要点提醒:
- 完整天意味着服务器从当天第一次温度记录一直运行到次日同一时刻,期间不能中断、电脑不能休眠;
- 只有覆盖了日间与夜间完整温度波动(最高温、最低温都出现)的数据,
min()与max()才有意义; - 如果只采集了几个小时的片段,计算出的「日最高/最低温」会严重偏低,GDD 也会失真。
进一步探索
- 服务器端完整实现:2-farm/lessons/1-predict-plant-growth/code-server/temperature-sensor-server/app.py
- Notebook 源码(含全部 markdown 说明格):2-farm/lessons/1-predict-plant-growth/code-notebook/gdd.ipynb
- 温度发布端示例(虚拟设备,每 10 分钟发布一条遥测):2-farm/lessons/1-predict-plant-growth/code-publish-temperature/virtual-device/temperature-sensor/app.py
- 课程完整背景(数字农业、温度与作物生长、GDD 定义与公式):2-farm/lessons/1-predict-plant-growth/README.md
- MQTT 遥测接收的通用步骤可回看 1-getting-started/lessons/4-connect-internet/README.md
挑战延伸:作物生长除了热量还需要水、光照、养分等条件,思考这些因素分别可以用什么传感器测量、用什么执行器控制,以及如何组合一个或多个 IoT 设备来优化植物生长——这正是数字农业中「测量—分析—响应」闭环的实践方向。
【免费下载链接】IoT-For-Beginners12 Weeks, 24 Lessons, IoT for All!项目地址: https://gitcode.com/GitHub_Trending/io/IoT-For-Beginners
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考