halil21 commited on
Commit
48949b4
·
verified ·
1 Parent(s): b99f46b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -0
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ with open("app.py", "w") as f:
2
+ f.write("""
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import gradio as gr
7
+ import pickle
8
+ import pandas as pd
9
+
10
+ # TabTransformer Model Tanımı
11
+ class TabTransformer(nn.Module):
12
+ def __init__(self, input_dim, num_classes=2, d_model=64, nhead=4, num_layers=3, dropout=0.1):
13
+ super().__init__()
14
+ self.embedding = nn.Linear(input_dim, d_model)
15
+ encoder_layer = nn.TransformerEncoderLayer(
16
+ d_model=d_model, nhead=nhead, dim_feedforward=d_model * 4, dropout=dropout, activation='gelu'
17
+ )
18
+ self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
19
+ self.fc = nn.Sequential(
20
+ nn.Linear(d_model, d_model // 2),
21
+ nn.ReLU(),
22
+ nn.Dropout(dropout),
23
+ nn.Linear(d_model // 2, num_classes)
24
+ )
25
+
26
+ def forward(self, x):
27
+ x = self.embedding(x)
28
+ x = x.unsqueeze(0) # Add sequence length dimension
29
+ x = self.transformer_encoder(x)
30
+ x = x.squeeze(0) # Remove sequence length dimension
31
+ return self.fc(x)
32
+
33
+ # Kategorik ve sayısal özellikler
34
+ categorical_features = ['Multifocal_PVC', 'Nonsustained_VT', 'gender', 'HTN', 'DM', 'Fullcompansasion']
35
+ numeric_features = ['pvc_percent', 'PVCQRS', 'EF', 'Age', 'PVC_Prematurity_index', 'QRS_ratio',
36
+ 'mean_HR', 'symptom_duration', 'QTc_sinus', 'PVCCI_dispersion',
37
+ 'CI_variability', 'PVC_Peak_QRS_duration', 'PVCCI', 'PVC_Compansatory_interval']
38
+
39
+ # Model ve scaler'ı yükleme
40
+ model_path = "/content/tabtransformer_model.pth"
41
+ scaler_path = "/content/trans_scaler.pkl"
42
+
43
+ # Model tanımı
44
+ input_dim = len(categorical_features) + len(numeric_features) # Toplam giriş boyutu
45
+ model = TabTransformer(input_dim=input_dim)
46
+ model.load_state_dict(torch.load(model_path, weights_only=True)) # Model ağırlıklarını yükle
47
+ model.eval() # Değerlendirme moduna al
48
+
49
+ # Scaler yükleme
50
+ with open(scaler_path, "rb") as f:
51
+ scaler = pickle.load(f)
52
+
53
+ # Prediction fonksiyonu
54
+ def predict(*inputs):
55
+ # Girdileri kategorik ve sayısal olarak ayır
56
+ cat_inputs = inputs[:len(categorical_features)]
57
+ num_inputs = inputs[len(categorical_features):]
58
+
59
+ # Kategorik girdiler (binary olarak 0/1 kodlama: "Yes" -> 1, "No" -> 0)
60
+ cat_data = [1 if val == "Yes" else 0 for val in cat_inputs]
61
+
62
+ # Sayısal girdiler
63
+ num_data = [float(val) for val in num_inputs]
64
+
65
+ # Veriyi birleştir ve ölçeklendir
66
+ data = pd.DataFrame([cat_data + num_data])
67
+ scaled_data = scaler.transform(data)
68
+
69
+ # Modelden tahmin al
70
+ tensor_data = torch.FloatTensor(scaled_data)
71
+ with torch.no_grad():
72
+ logits = model(tensor_data)
73
+ probabilities = F.softmax(logits, dim=1).numpy()
74
+
75
+ return {"Response Probability": probabilities[0][0], "Non-response Probability": probabilities[0][1]}
76
+
77
+ # Gradio arayüzü
78
+ inputs = (
79
+ [gr.Dropdown(choices=['Yes', 'No'], label=feature) for feature in categorical_features] +
80
+ [gr.Number(label=feature) for feature in numeric_features]
81
+ )
82
+ outputs = gr.Label(label="Prediction")
83
+ interface = gr.Interface(fn=predict, inputs=inputs, outputs=outputs, title="TabTransformer Prediction")
84
+
85
+ # Public URL ile başlat
86
+ interface.launch(share=True)
87
+
88
+ """)