homerfu commited on
Commit
f70eb93
·
verified ·
1 Parent(s): 2191065

Upload 18 files

Browse files
.streamlit/config.toml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [server]
2
+ port = 8501
3
+ address = "0.0.0.0"
4
+ headless = true
5
+ enableCORS = true
6
+ enableXsrfProtection = true
7
+ fileWatcherType = "auto" # 自動監控檔案變更(使用 watchdog,如果可用)
8
+ runOnSave = true # 檔案儲存時自動重新執行(此選項可能不存在,但保留無妨)
9
+
10
+ [runner]
11
+ fastReruns = true # 快速重新執行
12
+
13
+ [browser]
14
+ gatherUsageStats = false
15
+ serverAddress = "localhost"
16
+ serverPort = 8501
17
+
18
+ [theme]
19
+ primaryColor = "#3498db"
20
+ backgroundColor = "#ffffff"
21
+ secondaryBackgroundColor = "#f0f2f6"
22
+ textColor = "#262730"
23
+ font = "sans serif"
.streamlit/credential.toml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [general]
2
+ email = ""
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 使用官方 Python 基礎映像
2
+ FROM python:3.10-slim
3
+
4
+ # 設定工作目錄
5
+ WORKDIR /app
6
+
7
+ # 安裝系統依賴(包含 libgomp,用於 LightGBM 等)
8
+ RUN apt-get update && \
9
+ apt-get install -y --no-install-recommends libgomp1 && \
10
+ rm -rf /var/lib/apt/lists/*
11
+
12
+ # 複製需求檔案
13
+ COPY requirements.txt .
14
+
15
+ # 安裝 Python 依賴
16
+ RUN pip install --no-cache-dir -r requirements.txt
17
+
18
+ # 複製應用程式程式碼
19
+ COPY . .
20
+
21
+ # 暴露 Streamlit 端口
22
+ EXPOSE 8501
23
+
24
+ # 啟動 Streamlit(非互動模式,跳過歡迎訊息)
25
+ CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.headless=true", "--browser.gatherUsageStats=false"]
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from modules.pre_processing import pre_processing
5
+ from modules.nested_calibration_cv import nested_cv_calibration
6
+
7
+ # 設定頁面配置
8
+ st.set_page_config(
9
+ page_title="CLL Prediction",
10
+ layout="wide",
11
+ initial_sidebar_state="expanded",
12
+ )
13
+
14
+ # # CSS 客製化 sidebar 寬度
15
+ # st.markdown(
16
+ # """
17
+ # <style>
18
+ # section[data-testid="stSidebar"] {
19
+ # width: 500px !important;
20
+ # }
21
+ # </style>
22
+ # """,
23
+ # unsafe_allow_html=True,
24
+ # )
25
+
26
+ @st.cache_resource
27
+ def get_calibration():
28
+ return nested_cv_calibration()
29
+
30
+ # Initialize session state
31
+ if "predict_clicked" not in st.session_state:
32
+ st.session_state.predict_clicked = False
33
+
34
+ if "input_payload" not in st.session_state:
35
+ st.session_state.input_payload = None
36
+
37
+ st.title("Chronic Lymphocytic Leukemia Prediction")
38
+ st.caption("Please fill in the fields on the left and click \"Predict\".")
39
+ with st.expander("Explanation of HL p-value / Brier Score / AUC"):
40
+ col1, col2, col3 = st.columns(3)
41
+ with col1:
42
+ st.markdown("**HL p-value**: The p-value of the Hosmer-Lemeshow test. A p-value **higher than 0.05** indicates that the model is fit well.")
43
+ with col2:
44
+ st.markdown("**Brier Score**: The Brier score is a measure of the accuracy of probability predictions. A **closer to 0** indicates a better model.")
45
+ with col3:
46
+ st.markdown("**AUC**: The area under the receiver operating characteristic curve. A **higher AUC** indicates a better model.")
47
+ st.sidebar.title(" ⚙️Input")
48
+ with st.sidebar.form("prediction_form"):
49
+
50
+ st.subheader("Lymphocyte count(×10⁹/L)", help="Normal range is around 1.0-4.8 ×10⁹/L.")
51
+ lym_count = st.number_input(
52
+ "",
53
+ min_value=0.0,
54
+ max_value=100.0,
55
+ value=1.0,
56
+ step=0.1
57
+
58
+ )
59
+ st.subheader("Sex")
60
+ sex = st.radio("", ("Male", "Female"))
61
+ st.subheader("Past chemotherapy treatment")
62
+ past_chemo = st.radio("", ("Yes", "No"), key="past_chemo")
63
+ st.subheader("Sleep duration (hours)")
64
+ slp_duration = st.slider("", min_value=0, max_value=24, value=8)
65
+ st.subheader("Enlarged liver and spleen")
66
+ enlarge_liver_spleen = st.radio("", ("Yes", "No"), key="enlarge_liver_spleen")
67
+ st.subheader("Unusual blood test results")
68
+ unusual_blood_test = st.radio("", ("Yes", "No"), key="unusual_blood_test")
69
+ st.subheader("History of smoking")
70
+ smoking_history = st.radio("In the past, how often have you smoked tobacco?", (
71
+ "Smoked on most or all days",
72
+ "Smoked occasionally",
73
+ "Just tried once or twice",
74
+ "I have never smoked",
75
+ ), key="smoking_history")
76
+
77
+ st.subheader("History of major muscle & joint conditions", help="e.g., Rheumatoid Arthritis, Lupus, Chronic Disc Herniation, or past surgeries. Do not include temporary muscle soreness.")
78
+ muscle_joint_conditions = st.radio("", ("Yes", "No"),key="muscle_joint_conditions")
79
+ st.subheader("Metastasis (cancer spread to lungs or digestive system)")
80
+ metastasis = st.radio("", ("Yes", "No"), key="metastasis")
81
+
82
+ submitted = st.form_submit_button("Predict")
83
+ st.sidebar.markdown("The UK Biobank CLL Risk Prediction tool was established based on UK Biobank study cohort. The tool was developed on research purpose and cannot be used as clinical evidence.")
84
+
85
+ if submitted:
86
+ st.session_state.predict_clicked = True
87
+ st.session_state.input_payload = {
88
+ "Lymphocyte count": lym_count,
89
+ "Sex": sex,
90
+ "Past chemotherapy treatment": past_chemo,
91
+ "Sleep duration": slp_duration,
92
+ "Enlarged liver and spleen": enlarge_liver_spleen,
93
+ "Unusual blood test results": unusual_blood_test,
94
+ "Smoking history": smoking_history,
95
+ "History of muscle & joint conditions": muscle_joint_conditions,
96
+ "Metastasis": metastasis,
97
+ }
98
+
99
+ # numeric_columns = ['Lymphocyte count', 'Sleep duration']
100
+ # categorical_columns = ['Sex', 'Past chemotherapy treatment', 'Enlarged liver and spleen', 'Unusual blood test results', 'Smoking history', 'History of muscle & joint conditions', 'Metastasis']
101
+
102
+ if st.session_state.predict_clicked and st.session_state.input_payload is not None:
103
+ msg = st.empty() # 建立一個可被清空的區塊
104
+ msg.success("Data submitted, starting prediction process.")
105
+
106
+ Fix_Param = {
107
+ 'learning_rate': 0.05,
108
+ 'n_estimators': 200,
109
+ 'num_leaves': 6,
110
+ 'boosting_type' : 'gbdt',
111
+ 'objective' : 'binary',
112
+ 'max_bin':225,
113
+ 'random_state' : 500,
114
+ 'colsample_bytree' : 0.64,
115
+ 'subsample' : 0.7,
116
+ 'reg_alpha' : 0.8,
117
+ 'reg_lambda' : 1.8,
118
+ 'is_unbalance': True, # imbalanced data
119
+ }
120
+
121
+
122
+ input_df = pd.DataFrame([st.session_state.input_payload])
123
+ processed_df = pre_processing(input_df) # already scaled and encoded
124
+
125
+
126
+ X_np_5y = np.load("./plot_reference/5y/5y_balanced_X.npy"); y_np_5y = np.load("./plot_reference/5y/5y_balanced_y.npy");
127
+ X_np_10y = np.load("./plot_reference/10y/10y_balanced_X.npy"); y_np_10y = np.load("./plot_reference/10y/10y_balanced_y.npy");
128
+ X_np_all = np.load("./plot_reference/all/all_balanced_X.npy"); y_np_all = np.load("./plot_reference/all/all_balanced_y.npy");
129
+
130
+ # get risk from model (use processed features to match training data)
131
+ fig_5y = nested_cv_calibration(X_np_5y, y_np_5y, Fix_Param, "5-year CLL Risk",
132
+ calibration_method="isotonic",
133
+ input_df=processed_df,
134
+ num_groups=4,
135
+ output_name=None,
136
+ feature_names=None)
137
+
138
+ col_left, col_right = st.columns([5, 1])
139
+ with col_right:
140
+ st.markdown("**5-year model AUC: 0.876**", unsafe_allow_html=True)
141
+ st.pyplot(fig_5y)
142
+
143
+
144
+
145
+ fig_10y = nested_cv_calibration(X_np_10y, y_np_10y, Fix_Param, "10-year CLL Risk",
146
+ calibration_method="isotonic",
147
+ input_df=processed_df,
148
+ num_groups=4,
149
+ output_name=None,
150
+ feature_names=None)
151
+
152
+ col_left, col_right = st.columns([5, 1])
153
+ with col_right:
154
+ st.markdown("**10-year model AUC: 0.873**", unsafe_allow_html=True)
155
+ st.pyplot(fig_10y)
156
+
157
+
158
+ fig_all = nested_cv_calibration(X_np_all, y_np_all, Fix_Param, "All CLL Risk",
159
+ calibration_method="isotonic",
160
+ input_df=processed_df,
161
+ num_groups=4,
162
+ output_name=None,
163
+ feature_names=None)
164
+
165
+ col_left, col_right = st.columns([5, 1])
166
+ with col_right:
167
+ st.markdown("**All model AUC: 0.884**", unsafe_allow_html=True)
168
+ st.pyplot(fig_all)
169
+
170
+ msg.empty() # 清空成功訊息
171
+
best_ml/top9_final_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6718b1d15051c453c14c698f1d3e65f880c46904bcfc980647c459de6e5186e
3
+ size 160251
docker-compose.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ cellpose-app:
5
+ build: .
6
+ container_name: CLL_pred_streamlit
7
+ ports:
8
+ - "8501:8501"
9
+ volumes:
10
+ # 掛載資料目錄以持久化資料
11
+ - ./data:/app/data
12
+ # 掛載配置檔
13
+ - ./.streamlit:/app/.streamlit
14
+ # 掛載程式碼目錄(開發模式:程式碼更改即時生效)
15
+ - ./app.py:/app/app.py
16
+ - ./modules:/app/modules
17
+ # 掛載模型目錄,避免每次重建容器重下載 Cellpose 模型
18
+ - ~/.cellpose:/root/.cellpose
19
+ environment:
20
+ - PYTHONUNBUFFERED=1
21
+ - STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
22
+ - STREAMLIT_SERVER_HEADLESS=true
23
+ # 如果需要 GPU 支援,取消下面的註解
24
+ # deploy:
25
+ # resources:
26
+ # reservations:
27
+ # devices:
28
+ # - driver: nvidia
29
+ # count: 1
30
+ # capabilities: [gpu]
31
+ restart: always
modules/__pycache__/nested_calibration_cv.cpython-310.pyc ADDED
Binary file (6.95 kB). View file
 
modules/__pycache__/pre_processing.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
modules/nested_calibration_cv.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import re
3
+ from sklearn.model_selection import StratifiedKFold, cross_val_predict
4
+ from sklearn.calibration import CalibratedClassifierCV
5
+ from sklearn.metrics import brier_score_loss, log_loss
6
+ from scipy.stats import chi2
7
+ from lightgbm import LGBMClassifier
8
+ import numpy as np
9
+ import pandas as pd
10
+ import matplotlib.pyplot as plt
11
+ from sklearn.metrics import roc_curve, auc, roc_auc_score
12
+ from sklearn.metrics import (
13
+ accuracy_score, precision_score, recall_score, f1_score,
14
+ roc_auc_score, confusion_matrix, log_loss, brier_score_loss, roc_curve
15
+ )
16
+ from sklearn.model_selection import StratifiedKFold, cross_val_predict
17
+ from sklearn.calibration import CalibratedClassifierCV
18
+ from lightgbm import LGBMClassifier
19
+ import numpy as np
20
+
21
+
22
+ def hosmer_lemeshow_test(y_true, y_pred_proba, num_groups=10):
23
+ df = pd.DataFrame({'y_true': y_true, 'y_pred': y_pred_proba})
24
+ df['decile'] = pd.qcut(df['y_pred'], num_groups, labels=False, duplicates='drop')
25
+
26
+ decile_stats = df.groupby('decile').apply(lambda x: pd.Series({
27
+ 'observed': x['y_true'].sum(),
28
+ 'expected': x['y_pred'].sum(),
29
+ })).reset_index()
30
+
31
+ chi_square_stat = np.sum(
32
+ (decile_stats['observed'] - decile_stats['expected']) ** 2 / (decile_stats['expected'] + 1e-8)
33
+ )
34
+ df_chi = df['decile'].nunique() - 2
35
+
36
+ # summary
37
+ summary = df.groupby('decile').apply(
38
+ lambda x: pd.Series({
39
+ 'Sample Size': len(x),
40
+ 'Positive Rate (%)': 100 * x['y_true'].mean(),
41
+ 'Predicted Range': f"{x['y_pred'].min():.3f}–{x['y_pred'].max():.3f}"
42
+ })
43
+ ).reset_index()
44
+
45
+ return 1 - chi2.cdf(chi_square_stat, df_chi), summary
46
+
47
+
48
+ def plot_calibration_with_y_pred(y_true:np.ndarray, y_pred_proba:np.ndarray, pvalue:float, brier_score:float, title:str, y_pred:float=None, num_groups:int=4):
49
+ df = pd.DataFrame({'y_true': y_true, 'y_pred': y_pred_proba})
50
+ df['decile'] = pd.cut(df['y_pred'], bins=np.linspace(0, 1, num_groups+1), labels=False)
51
+
52
+ decile_stats = df.groupby('decile').apply(
53
+ lambda x: pd.Series({
54
+ 'observed': 100 * x['y_true'].mean(),
55
+ 'predicted': 100 * x['y_pred'].mean()
56
+ })
57
+ ).reset_index()
58
+
59
+ fig, ax = plt.subplots(figsize=(8, 4.5))
60
+ x = np.arange(len(decile_stats))
61
+ width = 0.35
62
+
63
+ ax.bar(x - width/2, decile_stats['observed'], width, label='Observed', color='steelblue')
64
+ ax.bar(x + width/2, decile_stats['predicted'], width, label='Predicted', color='orange')
65
+
66
+ if y_pred is not None:
67
+ ax.axhline(
68
+ y=y_pred * 100, # 機率轉百分比
69
+ color="red",
70
+ linestyle="--",
71
+ linewidth=2,
72
+ label=f"CLL Risk: {y_pred*100:.2f}%" # 或改成你要的單位文字
73
+ )
74
+
75
+ for i in range(len(x)):
76
+ ax.text(x[i] - width/2, decile_stats['observed'][i] + 1,
77
+ f"{decile_stats['observed'][i]:.1f}", ha='center', fontsize=8, color='steelblue', fontweight='bold')
78
+ ax.text(x[i] + width/2, decile_stats['predicted'][i] + 1,
79
+ f"{decile_stats['predicted'][i]:.1f}", ha='center', fontsize=8, color='orange', fontweight='bold')
80
+
81
+ top_y = max(decile_stats['observed'].max(), decile_stats['predicted'].max())
82
+ ax.text(len(x)/2-0.5, top_y - 1, title, ha='center', fontsize=14, color='black')
83
+ ax.text(len(x)/2-0.5, top_y - 5,
84
+ f"HL p-value = {pvalue:.2f} Brier Score = {brier_score:.2f}",
85
+ ha='center', fontsize=10, color='black')
86
+
87
+ ax.set_xticks(x)
88
+ ax.set_xticklabels(range(1, len(decile_stats) + 1))
89
+ ax.set_xlabel(f"{num_groups} Quantile Groups")
90
+ ax.set_ylabel("Frequency (%)")
91
+ ax.legend()
92
+ ax.grid(True, linestyle='--', alpha=0.4)
93
+ plt.tight_layout()
94
+ return fig
95
+
96
+
97
+
98
+ def _calibration_output_stem(title, output_name):
99
+ """檔名用:output/calibration_{stem}.xlsx;僅英數與底線較安全。"""
100
+ raw = output_name if output_name is not None else title
101
+ stem = re.sub(r"[^\w\-]+", "_", str(raw).strip()).strip("_")
102
+ return stem or "calibration"
103
+
104
+
105
+ def _ensure_feature_frame(X, feature_names):
106
+ """訓練/預測皆用具欄位名的 DataFrame,避免 ndarray 與欄位名不一致的 sklearn 警告。"""
107
+ if isinstance(X, pd.DataFrame):
108
+ return X.copy()
109
+ X_arr = np.asarray(X)
110
+ if X_arr.ndim != 2:
111
+ raise ValueError("X must be 2-dimensional")
112
+ n_features = X_arr.shape[1]
113
+ if feature_names is not None:
114
+ cols = list(feature_names)
115
+ if len(cols) != n_features:
116
+ raise ValueError(
117
+ f"feature_names length ({len(cols)}) must match X columns ({n_features})"
118
+ )
119
+ else:
120
+ cols = [f"f{i}" for i in range(n_features)]
121
+ return pd.DataFrame(X_arr, columns=cols)
122
+
123
+
124
+ def _to_numeric_matrix(X, feature_names=None):
125
+ """轉為純數值矩陣,��免 LightGBM 對 pandas 類別欄位推斷不一致。"""
126
+ X_df = _ensure_feature_frame(X, feature_names)
127
+ X_num = X_df.apply(pd.to_numeric, errors="coerce")
128
+ if X_num.isnull().values.any():
129
+ raise ValueError("Input features contain non-numeric values after preprocessing.")
130
+ return X_num.to_numpy(dtype=np.float64)
131
+
132
+
133
+ def nested_cv_calibration(
134
+ X,
135
+ y,
136
+ fix_params,
137
+ title,
138
+ calibration_method="isotonic",
139
+ num_groups=10,
140
+ output_name=None,
141
+ feature_names=None,
142
+ input_df=None,
143
+ ):
144
+ lgbm_params = {**fix_params}
145
+ if "verbose" not in lgbm_params:
146
+ lgbm_params["verbose"] = -1 # 關閉 [LightGBM] [Info] 訓練日誌
147
+
148
+ base_model = LGBMClassifier(**lgbm_params)
149
+ cal_model = CalibratedClassifierCV(base_model, method=calibration_method, cv=5)
150
+ X_mat = _to_numeric_matrix(X, feature_names)
151
+ y_arr = np.asarray(y).ravel()
152
+
153
+ # 1) 用 cross_val_predict 取得「校正後機率」做 decile 校正評估
154
+ y_prob = cross_val_predict(cal_model, X_mat, y_arr, method="predict_proba", cv=5)[:, 1]
155
+
156
+ pval, summary = hosmer_lemeshow_test(y_arr, y_prob, num_groups=num_groups)
157
+ brier_score = brier_score_loss(y_arr, y_prob)
158
+
159
+ # 2) 若有提供 input_df:用「校正後模型」在全資料上訓練,再對個案預測機率
160
+ if input_df is not None:
161
+ # 先在全資料上重新訓練校正模型,作為部署用模型
162
+ cal_model.fit(X_mat, y_arr)
163
+
164
+ X_input_mat = _to_numeric_matrix(input_df, feature_names)
165
+ if X_input_mat.shape[1] != X_mat.shape[1]:
166
+ raise ValueError(
167
+ f"input features ({X_input_mat.shape[1]}) do not match training features ({X_mat.shape[1]})."
168
+ )
169
+ y_input_pred_proba = cal_model.predict_proba(X_input_mat)[:, 1]
170
+ input_risk = float(y_input_pred_proba[0])
171
+
172
+ # 使用校正後機率 + 個案風險畫紅色虛線
173
+ fig = plot_calibration_with_y_pred(
174
+ y_true=y_arr,
175
+ y_pred_proba=y_prob,
176
+ pvalue=pval,
177
+ brier_score=brier_score,
178
+ title=title,
179
+ y_pred=input_risk,
180
+ num_groups=num_groups,
181
+ )
182
+
183
+ return fig
184
+ # # save for web app
185
+ # if output_name is None:
186
+ # raise ValueError("output_name must be provided to save web plot reference files.")
187
+
188
+ # plot_ref_root = Path(r"D:\BA cases\ZBA040124_揚波\CLL_prediction_web\plot_reference")
189
+ # plot_ref_dir = plot_ref_root / str(output_name)
190
+ # plot_ref_dir.mkdir(parents=True, exist_ok=True)
191
+
192
+ # np.save(plot_ref_dir / "y_arr.npy", y_arr)
193
+ # np.save(plot_ref_dir / "y_prob.npy", y_prob)
194
+ # np.save(plot_ref_dir / "pval.npy", pval)
195
+ # np.save(plot_ref_dir / "brier_score.npy", brier_score)
196
+
197
+
198
+ # record_df = pd.DataFrame(metrics_list)
199
+
200
+ # stem = _calibration_output_stem(title, output_name)
201
+ # out_dir = Path("output")
202
+ # out_dir.mkdir(parents=True, exist_ok=True)
203
+ # out_path = out_dir / f"calibration_{stem}.xlsx"
204
+ # with pd.ExcelWriter(out_path, engine="openpyxl") as writer:
205
+ # summary.to_excel(writer, sheet_name="summary", index=False)
206
+ # record_df.to_excel(writer, sheet_name="record", index=False)
207
+ # print(f"Calibration tables saved: {out_path.resolve()}")
208
+
209
+ # print(f"Hosmer–Lemeshow p-value: {pval:.4f}")
210
+ # print(f"Brier Score: {brier_score:.4f}")
211
+ # print(f"Log Loss: {log_loss(y_arr, y_prob):.4f}")
212
+
213
+ # return y_prob, cal_model, summary, fold_roc_results, metrics_list
214
+
215
+ def summarize_cv_metrics(metrics_list):
216
+ import pandas as pd
217
+
218
+ df = pd.DataFrame(metrics_list)
219
+ mean_series = df.mean()
220
+ std_series = df.std()
221
+
222
+ summary_df = pd.DataFrame({
223
+ 'Mean': mean_series,
224
+ 'Std': std_series
225
+ }).round(4)
226
+
227
+ print("Cross-Validation Metric Summary:")
228
+ print(summary_df)
229
+
230
+ return summary_df
231
+
232
+
233
+
234
+ def calibration_ROC(fold_roc_results):
235
+
236
+ mean_fpr = np.linspace(0, 1, 100) # 生成統一的 FPR 軸
237
+ tprs = []
238
+ aucs = []
239
+
240
+
241
+ for fpr, tpr, auc_score in fold_roc_results:
242
+ interp_tpr = np.interp(mean_fpr, fpr, tpr) # 插值對齊 TPR
243
+ interp_tpr[0] = 0.0 # 確保起點為 0
244
+ tprs.append(interp_tpr)
245
+ aucs.append(auc_score)
246
+
247
+
248
+
249
+ mean_tpr = np.mean(tprs, axis=0)
250
+ std_tpr = np.std(tprs, axis=0)
251
+ mean_auc = np.mean(aucs)
252
+ std_auc = np.std(aucs)
253
+
254
+
255
+ return mean_fpr, mean_tpr, std_tpr, mean_auc, std_auc
256
+
257
+
258
+
259
+
260
+
261
+
modules/pre_processing.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
3
+
4
+ def pre_processing(input_df):
5
+ scaler = StandardScaler()
6
+ numeric_columns = ['Lymphocyte count', 'Sleep duration'] # UKB code: p30120_i0, p1160_i0
7
+ input_df[numeric_columns] = scaler.fit_transform(input_df[numeric_columns])
8
+ categorical_columns = ['Sex', 'Past chemotherapy treatment', 'Enlarged liver and spleen', 'Unusual blood test results', 'Smoking history', 'History of muscle & joint conditions', 'Metastasis']
9
+ input_df[categorical_columns] = input_df[categorical_columns].astype('category')
10
+
11
+ # 理論上要用當初訓練模型的encoder, 但因為都是yes/no and sex, 直接映射
12
+ input_df['Sex'] = input_df['Sex'].map({'Male': 1, 'Female': 0}) # UKB code: p31
13
+ input_df['Past chemotherapy treatment'] = input_df['Past chemotherapy treatment'].map({'Yes': 1, 'No': 0}) # UKB code: Z926
14
+ input_df['Enlarged liver and spleen'] = input_df['Enlarged liver and spleen'].map({'Yes': 1, 'No': 0}) # UKB code: R16
15
+ input_df['Unusual blood test results'] = input_df['Unusual blood test results'].map({'Yes': 1, 'No': 0}) # UKB code: R79
16
+ input_df['Smoking history'] = input_df['Smoking history'].map({'Smoked on most or all days': 1, 'Smoked occasionally': 2, 'Just tried once or twice': 3, 'I have never smoked': 4}) # UKB code: p1249_i0
17
+ input_df['History of muscle & joint conditions'] = input_df['History of muscle & joint conditions'].map({'Yes': 1, 'No': 0}) # UKB code: Z873
18
+ input_df['Metastasis'] = input_df['Metastasis'].map({'Yes': 1, 'No': 0}) # UKB code: C78
19
+ return input_df
plot_reference/10y/10y_balanced_X.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:511bbf19aea136f441f759ac2cdd48f4dc886e05a1d9bd9600474645dd4f730c
3
+ size 1025048
plot_reference/10y/10y_balanced_y.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28383f7826cbdc3b259859e88ed959351083a4a31eaeee61aa8db0053522f0d0
3
+ size 114008
plot_reference/5y/5y_balanced_X.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c012997a5276e3fba1335a3f001a0e4d0e66e2a29bc3fa5dd5573bd3f991006
3
+ size 1025048
plot_reference/5y/5y_balanced_y.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28383f7826cbdc3b259859e88ed959351083a4a31eaeee61aa8db0053522f0d0
3
+ size 114008
plot_reference/all/all_balanced_X.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adf64e580594bc9ae5525a5645ed7e37152fb224970312cc5177143dab7cb659
3
+ size 1025048
plot_reference/all/all_balanced_y.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28383f7826cbdc3b259859e88ed959351083a4a31eaeee61aa8db0053522f0d0
3
+ size 114008
plot_reference/top9_feature_dict.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "p30120_i0": "Lymphocyte count",
3
+ "p31": "Sex",
4
+ "Z926": "Past chemotherapy treatment",
5
+ "p1160_i0": "Sleep duration",
6
+ "R16": "Enlarged liver and spleen",
7
+ "R79": "Unusual blood test results",
8
+ "p1249_i0": "In the past, how often have you smoked tobacco?",
9
+ "Z873": "History of muscle & joint conditions",
10
+ "C78": "Cancer spread to lungs or digestive system"
11
+ }
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ scipy
3
+ pandas
4
+ scikit-learn
5
+ imblearn
6
+ matplotlib
7
+ openpyxl
8
+ streamlit
9
+ lightgbm