1. 新增趨勢分析欄位
先到 PostgreSQL 裡,新增一個欄位來存「趨勢方向」:
ALTER TABLE cancer_patients
ADD COLUMN afp_trend VARCHAR(10),
ADD COLUMN alt_trend VARCHAR(10);
2. 用 Python 計算變化率與趨勢
我們可以在之前的 predict_and_insert.py 裡增加一段邏輯,
每次更新時順便判斷最近兩筆資料的變化:
import psycopg2
import pandas as pd
conn = psycopg2.connect(
host="localhost",
database="cancer_db",
user="admin",
password="admin123",
port=5432
)
cursor = conn.cursor()
# 取出最新兩筆資料
cursor.execute("""
SELECT record_date, afp, alt
FROM cancer_patients
WHERE patient_id = '001'
ORDER BY record_date DESC
LIMIT 2;
""")
rows = cursor.fetchall()
latest, previous = rows[0], rows[1]
afp_change = (latest[1] - previous[1]) / previous[1] * 100
alt_change = (latest[2] - previous[2]) / previous[2] * 100
# 根據變化率分類趨勢
def get_trend(change):
if change > 10:
return '上升中'
elif change < -10:
return '下降中'
else:
return '穩定'
afp_trend = get_trend(afp_change)
alt_trend = get_trend(alt_change)
cursor.execute("""
UPDATE cancer_patients
SET afp_trend = %s, alt_trend = %s
WHERE record_date = %s AND patient_id = '001';
""", (afp_trend, alt_trend, latest[0]))
conn.commit()
cursor.close()
conn.close()
print(f"AFP 變化率: {afp_change:.2f}% → {afp_trend}")
print(f"ALT 變化率: {alt_change:.2f}% → {alt_trend}")
這樣每次資料更新時,就會自動標註趨勢方向。
3. 在 Grafana 顯示「健康摘要卡」
(1) 新增一個 Stat Panel
查詢語法:
SELECT afp_trend FROM cancer_patients
WHERE patient_id = '$patient_id'
ORDER BY record_date DESC
LIMIT 1;
顯示「AFP 趨勢」文字結果:上升中 / 穩定 / 下降中
(2) 顏色設定
趨勢狀態 | 顏色 | 說明 |
---|---|---|
上升中 | 🔴 紅色 | 指標惡化,需注意 |
穩定 | 🟡 黃色 | 無明顯變化 |
下降中 | 🟢 綠色 | 情況改善 |
你可以在 Grafana 的 Value mappings 裡設定:
● 上升中 → red
● 穩定 → yellow
● 下降中 → green
4. 顯示趨勢曲線(變化率圖)
新增一個 Bar Chart Panel,查詢:
SELECT
record_date AS "time",
(afp - LAG(afp) OVER (ORDER BY record_date)) / NULLIF(LAG(afp) OVER (ORDER BY record_date), 0) * 100 AS "AFP Change (%)"
FROM cancer_patients
WHERE patient_id = '$patient_id'
ORDER BY record_date;
這樣可以看到每次檢查 AFP 的漲跌百分比,形成清晰的變化趨勢。
5. 加入「AI 預測 vs 實際變化」比較
要讓 Dashboard 更智能,可以再畫一張圖:
顯示「AI 預測變化」與「實際變化」差距。
SELECT
record_date AS "time",
(afp_pred - afp) AS "AFP Prediction Gap"
FROM cancer_patients
WHERE patient_id = '$patient_id'
ORDER BY record_date;
圖上紅色代表預測過高、藍色代表預測偏低。
這能幫助分析模型準確度。
6. 成果
完成後,Dashboard 將有三層資訊:
(1) 病人切換(patient_id 下拉選單)
(2) 健康摘要卡
● AFP 趨勢:上升中
● ALT 趨勢:穩定
(3) 數值變化
● AFP / ALT 實際值 + AI 預測曲線
● AFP 變化率百分比圖
這樣一眼就能看出病人是「改善中」還是「惡化中」。