Spaces:
Runtime error
Runtime error
| with open("app.py", "w") as f: | |
| f.write(""" | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import gradio as gr | |
| import pickle | |
| import pandas as pd | |
| # TabTransformer Model Tanımı | |
| class TabTransformer(nn.Module): | |
| def __init__(self, input_dim, num_classes=2, d_model=64, nhead=4, num_layers=3, dropout=0.1): | |
| super().__init__() | |
| self.embedding = nn.Linear(input_dim, d_model) | |
| encoder_layer = nn.TransformerEncoderLayer( | |
| d_model=d_model, nhead=nhead, dim_feedforward=d_model * 4, dropout=dropout, activation='gelu' | |
| ) | |
| self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) | |
| self.fc = nn.Sequential( | |
| nn.Linear(d_model, d_model // 2), | |
| nn.ReLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model // 2, num_classes) | |
| ) | |
| def forward(self, x): | |
| x = self.embedding(x) | |
| x = x.unsqueeze(0) # Add sequence length dimension | |
| x = self.transformer_encoder(x) | |
| x = x.squeeze(0) # Remove sequence length dimension | |
| return self.fc(x) | |
| # Kategorik ve sayısal özellikler | |
| categorical_features = ['Multifocal_PVC', 'Nonsustained_VT', 'gender', 'HTN', 'DM', 'Fullcompansasion'] | |
| numeric_features = ['pvc_percent', 'PVCQRS', 'EF', 'Age', 'PVC_Prematurity_index', 'QRS_ratio', | |
| 'mean_HR', 'symptom_duration', 'QTc_sinus', 'PVCCI_dispersion', | |
| 'CI_variability', 'PVC_Peak_QRS_duration', 'PVCCI', 'PVC_Compansatory_interval'] | |
| # Model ve scaler'ı yükleme | |
| model_path = "/content/tabtransformer_model.pth" | |
| scaler_path = "/content/trans_scaler.pkl" | |
| # Model tanımı | |
| input_dim = len(categorical_features) + len(numeric_features) # Toplam giriş boyutu | |
| model = TabTransformer(input_dim=input_dim) | |
| model.load_state_dict(torch.load(model_path, weights_only=True)) # Model ağırlıklarını yükle | |
| model.eval() # Değerlendirme moduna al | |
| # Scaler yükleme | |
| with open(scaler_path, "rb") as f: | |
| scaler = pickle.load(f) | |
| # Prediction fonksiyonu | |
| def predict(*inputs): | |
| # Girdileri kategorik ve sayısal olarak ayır | |
| cat_inputs = inputs[:len(categorical_features)] | |
| num_inputs = inputs[len(categorical_features):] | |
| # Kategorik girdiler (binary olarak 0/1 kodlama: "Yes" -> 1, "No" -> 0) | |
| cat_data = [1 if val == "Yes" else 0 for val in cat_inputs] | |
| # Sayısal girdiler | |
| num_data = [float(val) for val in num_inputs] | |
| # Veriyi birleştir ve ölçeklendir | |
| data = pd.DataFrame([cat_data + num_data]) | |
| scaled_data = scaler.transform(data) | |
| # Modelden tahmin al | |
| tensor_data = torch.FloatTensor(scaled_data) | |
| with torch.no_grad(): | |
| logits = model(tensor_data) | |
| probabilities = F.softmax(logits, dim=1).numpy() | |
| return {"Response Probability": probabilities[0][0], "Non-response Probability": probabilities[0][1]} | |
| # Gradio arayüzü | |
| inputs = ( | |
| [gr.Dropdown(choices=['Yes', 'No'], label=feature) for feature in categorical_features] + | |
| [gr.Number(label=feature) for feature in numeric_features] | |
| ) | |
| outputs = gr.Label(label="Prediction") | |
| interface = gr.Interface(fn=predict, inputs=inputs, outputs=outputs, title="TabTransformer Prediction") | |
| # Public URL ile başlat | |
| interface.launch(share=True) | |
| """) | |