Spaces:
Runtime error
Runtime error
# app.py | |
import flet as ft | |
import pandas as pd | |
import numpy as np | |
from sklearn.model_selection import train_test_split | |
from sklearn.ensemble import RandomForestRegressor | |
from sklearn.metrics import mean_squared_error, r2_score | |
import asyncio | |
async def main(page: ft.Page): | |
page.title = "C14_1 預測器" | |
page.theme_mode = "light" | |
page.padding = 50 | |
page.scroll = "adaptive" | |
# 載入數據 | |
def load_data(): | |
data = pd.DataFrame({ | |
'C14_1': np.random.rand(100), | |
'blood': np.random.rand(100), | |
'c7': np.random.rand(100), | |
'c17': np.random.rand(100), | |
'c22': np.random.rand(100), | |
'c17_d': np.random.rand(100), | |
'c22_d': np.random.rand(100), | |
'Skinprick': np.random.rand(100), | |
'MAST': np.random.rand(100), | |
'sex': np.random.randint(0, 2, 100), | |
'c12': np.random.rand(100), | |
'c14': np.random.rand(100), | |
'c18': np.random.rand(100), | |
'c20': np.random.rand(100), | |
'f27_1': np.random.rand(100), | |
'h12': np.random.rand(100) | |
}) | |
return data | |
data = load_data() | |
# 準備特徵和目標變量 | |
target_column = 'C14_1' | |
X = data.drop([target_column], axis=1) | |
y = data[target_column] | |
# 分割數據 | |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) | |
# 訓練模型 | |
model = RandomForestRegressor(n_estimators=100, random_state=42) | |
model.fit(X_train, y_train) | |
# 創建輸入控件 | |
input_controls = {} | |
for column in X.columns: | |
input_controls[column] = ft.Slider( | |
min=float(X[column].min()), | |
max=float(X[column].max()), | |
value=float(X[column].mean()), | |
label=f"{column}", | |
divisions=100, | |
) | |
# 預測結果文本 | |
prediction_text = ft.Text(size=20) | |
# 模型性能文本 | |
mse_text = ft.Text(size=16) | |
r2_text = ft.Text(size=16) | |
# 特徵重要性文本 | |
feature_importance_text = ft.Text(size=16) | |
def predict(e): | |
input_data = {col: control.value for col, control in input_controls.items()} | |
input_df = pd.DataFrame([input_data]) | |
prediction = model.predict(input_df)[0] | |
prediction_text.value = f"預測的 C14_1 值為: {prediction:.2f}" | |
page.update() | |
def show_model_performance(e): | |
y_pred = model.predict(X_test) | |
mse = mean_squared_error(y_test, y_pred) | |
r2 = r2_score(y_test, y_pred) | |
mse_text.value = f"均方誤差 (MSE): {mse:.2f}" | |
r2_text.value = f"決定係數 (R²): {r2:.2f}" | |
page.update() | |
def show_feature_importance(e): | |
feature_importance = pd.DataFrame({ | |
'feature': X.columns, | |
'importance': model.feature_importances_ | |
}).sort_values('importance', ascending=False) | |
importance_str = "\n".join([f"{row['feature']}: {row['importance']:.4f}" for _, row in feature_importance.iterrows()]) | |
feature_importance_text.value = f"特徵重要性:\n{importance_str}" | |
page.update() | |
# 創建頁面佈局 | |
await page.add_async( | |
ft.Text("C14_1 預測器", size=30, weight="bold"), | |
ft.Column([control for control in input_controls.values()]), | |
ft.ElevatedButton("預測", on_click=predict), | |
prediction_text, | |
ft.ElevatedButton("顯示模型性能", on_click=show_model_performance), | |
mse_text, | |
r2_text, | |
ft.ElevatedButton("顯示特徵重要性", on_click=show_feature_importance), | |
feature_importance_text, | |
) | |
# 運行應用 | |
async def run_app(): | |
await ft.app_async(target=main, view=ft.WEB_BROWSER) | |
# 在標準Python環境中運行 | |
asyncio.run(run_app()) | |