File size: 3,792 Bytes
afcfa0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# 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())