Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -24,6 +24,11 @@ class HousePricePredictor:
|
|
| 24 |
self.is_trained = False
|
| 25 |
self.selected_features = None
|
| 26 |
self._data_loaded = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def load_data(self):
|
| 29 |
"""Carrega dados do arquivo kc_house_data.csv"""
|
|
@@ -37,6 +42,13 @@ class HousePricePredictor:
|
|
| 37 |
# Limpeza básica dos dados
|
| 38 |
self._clean_data()
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
self._data_loaded = True
|
| 41 |
print(f"✅ Dados carregados: {self.df.shape[0]} imóveis × {self.df.shape[1]} características")
|
| 42 |
return f"✅ Dados carregados: {self.df.shape[0]} imóveis × {self.df.shape[1]} características"
|
|
@@ -75,6 +87,21 @@ class HousePricePredictor:
|
|
| 75 |
numeric_features.remove('price')
|
| 76 |
return numeric_features
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def train_model(self, selected_features):
|
| 79 |
"""Treina o modelo com as features selecionadas"""
|
| 80 |
try:
|
|
@@ -170,6 +197,7 @@ predictor = HousePricePredictor()
|
|
| 170 |
print("🚀 Iniciando aplicação...")
|
| 171 |
initial_message = predictor.load_data()
|
| 172 |
initial_features = predictor.get_numeric_features()
|
|
|
|
| 173 |
print(f"📊 Features disponíveis: {initial_features}")
|
| 174 |
|
| 175 |
# Funções para a interface Gradio
|
|
@@ -441,6 +469,17 @@ def predict_price_action(*feature_values):
|
|
| 441 |
except Exception as e:
|
| 442 |
return f"❌ Erro na previsão: {str(e)}", None
|
| 443 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
# Interface Gradio
|
| 445 |
with gr.Blocks(title="🏠 Análise e Previsão - King County Dataset Real") as demo:
|
| 446 |
gr.Markdown(
|
|
@@ -456,17 +495,14 @@ with gr.Blocks(title="🏠 Análise e Previsão - King County Dataset Real") as
|
|
| 456 |
|
| 457 |
# Status inicial
|
| 458 |
initial_status = gr.Markdown(f"**Status:** {initial_message}")
|
|
|
|
| 459 |
|
| 460 |
with gr.Tab("🚀 Iniciar"):
|
| 461 |
gr.Markdown("### Bem-vindo ao Analisador de Dados Reais do King County!")
|
| 462 |
|
| 463 |
-
gr.Markdown(
|
| 464 |
-
**📊 Dataset Carregado:**
|
| 465 |
-
- **Arquivo**: kc_house_data.csv
|
| 466 |
-
- **Imóveis**: {predictor.df.shape[0] if predictor.df else 'Carregando...'}
|
| 467 |
-
- **Características**: {predictor.df.shape[1] if predictor.df else 'Carregando...'}
|
| 468 |
-
- **Preço Médio**: ${predictor.df['price'].mean():,.2f' if predictor.df else 'Carregando...'}
|
| 469 |
|
|
|
|
| 470 |
**🎯 Funcionalidades:**
|
| 471 |
1. **📊 Análise Exploratória** - Gráficos com dados reais
|
| 472 |
2. **🤖 Treinar Modelo** - Machine Learning com features selecionadas
|
|
@@ -479,7 +515,35 @@ with gr.Blocks(title="🏠 Análise e Previsão - King County Dataset Real") as
|
|
| 479 |
feature_selection = gr.Column()
|
| 480 |
train_btn = gr.Button("🚀 Treinar Modelo", variant="primary", visible=False)
|
| 481 |
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
|
| 484 |
with gr.Tab("📊 Análise Exploratória"):
|
| 485 |
gr.Markdown("### Explore os Dados Reais do King County")
|
|
|
|
| 24 |
self.is_trained = False
|
| 25 |
self.selected_features = None
|
| 26 |
self._data_loaded = False
|
| 27 |
+
self.stats = {
|
| 28 |
+
'n_imoveis': 0,
|
| 29 |
+
'n_caracteristicas': 0,
|
| 30 |
+
'preco_medio': 0
|
| 31 |
+
}
|
| 32 |
|
| 33 |
def load_data(self):
|
| 34 |
"""Carrega dados do arquivo kc_house_data.csv"""
|
|
|
|
| 42 |
# Limpeza básica dos dados
|
| 43 |
self._clean_data()
|
| 44 |
|
| 45 |
+
# Atualizar estatísticas
|
| 46 |
+
self.stats = {
|
| 47 |
+
'n_imoveis': self.df.shape[0],
|
| 48 |
+
'n_caracteristicas': self.df.shape[1],
|
| 49 |
+
'preco_medio': self.df['price'].mean()
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
self._data_loaded = True
|
| 53 |
print(f"✅ Dados carregados: {self.df.shape[0]} imóveis × {self.df.shape[1]} características")
|
| 54 |
return f"✅ Dados carregados: {self.df.shape[0]} imóveis × {self.df.shape[1]} características"
|
|
|
|
| 87 |
numeric_features.remove('price')
|
| 88 |
return numeric_features
|
| 89 |
|
| 90 |
+
def get_dataset_stats(self):
|
| 91 |
+
"""Retorna estatísticas do dataset para display seguro"""
|
| 92 |
+
if self.df is not None:
|
| 93 |
+
return {
|
| 94 |
+
'n_imoveis': self.df.shape[0],
|
| 95 |
+
'n_caracteristicas': self.df.shape[1],
|
| 96 |
+
'preco_medio': self.df['price'].mean()
|
| 97 |
+
}
|
| 98 |
+
else:
|
| 99 |
+
return {
|
| 100 |
+
'n_imoveis': 0,
|
| 101 |
+
'n_caracteristicas': 0,
|
| 102 |
+
'preco_medio': 0
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
def train_model(self, selected_features):
|
| 106 |
"""Treina o modelo com as features selecionadas"""
|
| 107 |
try:
|
|
|
|
| 197 |
print("🚀 Iniciando aplicação...")
|
| 198 |
initial_message = predictor.load_data()
|
| 199 |
initial_features = predictor.get_numeric_features()
|
| 200 |
+
dataset_stats = predictor.get_dataset_stats()
|
| 201 |
print(f"📊 Features disponíveis: {initial_features}")
|
| 202 |
|
| 203 |
# Funções para a interface Gradio
|
|
|
|
| 469 |
except Exception as e:
|
| 470 |
return f"❌ Erro na previsão: {str(e)}", None
|
| 471 |
|
| 472 |
+
def get_dataset_info():
|
| 473 |
+
"""Retorna informações do dataset para display seguro"""
|
| 474 |
+
stats = predictor.get_dataset_stats()
|
| 475 |
+
return f"""
|
| 476 |
+
**📊 Dataset Carregado:**
|
| 477 |
+
- **Arquivo**: kc_house_data.csv
|
| 478 |
+
- **Imóveis**: {stats['n_imoveis']:,}
|
| 479 |
+
- **Características**: {stats['n_caracteristicas']}
|
| 480 |
+
- **Preço Médio**: ${stats['preco_medio']:,.2f}
|
| 481 |
+
"""
|
| 482 |
+
|
| 483 |
# Interface Gradio
|
| 484 |
with gr.Blocks(title="🏠 Análise e Previsão - King County Dataset Real") as demo:
|
| 485 |
gr.Markdown(
|
|
|
|
| 495 |
|
| 496 |
# Status inicial
|
| 497 |
initial_status = gr.Markdown(f"**Status:** {initial_message}")
|
| 498 |
+
dataset_info = gr.Markdown(get_dataset_info())
|
| 499 |
|
| 500 |
with gr.Tab("🚀 Iniciar"):
|
| 501 |
gr.Markdown("### Bem-vindo ao Analisador de Dados Reais do King County!")
|
| 502 |
|
| 503 |
+
gr.Markdown(get_dataset_info())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
|
| 505 |
+
gr.Markdown("""
|
| 506 |
**🎯 Funcionalidades:**
|
| 507 |
1. **📊 Análise Exploratória** - Gráficos com dados reais
|
| 508 |
2. **🤖 Treinar Modelo** - Machine Learning com features selecionadas
|
|
|
|
| 515 |
feature_selection = gr.Column()
|
| 516 |
train_btn = gr.Button("🚀 Treinar Modelo", variant="primary", visible=False)
|
| 517 |
|
| 518 |
+
def update_after_load():
|
| 519 |
+
message = predictor.load_data()
|
| 520 |
+
info = get_dataset_info()
|
| 521 |
+
features = predictor.get_numeric_features()
|
| 522 |
+
|
| 523 |
+
# Criar checkboxes
|
| 524 |
+
feature_checkboxes = []
|
| 525 |
+
if features and predictor.df is not None:
|
| 526 |
+
correlations = predictor.df.corr()['price'].abs().sort_values(ascending=False)
|
| 527 |
+
top_features = []
|
| 528 |
+
for feature in correlations.index:
|
| 529 |
+
if feature != 'price' and len(top_features) < 6:
|
| 530 |
+
top_features.append(feature)
|
| 531 |
+
|
| 532 |
+
for feature in features:
|
| 533 |
+
corr_value = correlations.get(feature, 0)
|
| 534 |
+
feature_checkboxes.append(
|
| 535 |
+
gr.Checkbox(
|
| 536 |
+
label=f"{feature} (corr: {corr_value:.3f})",
|
| 537 |
+
value=feature in top_features
|
| 538 |
+
)
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
return message, info, gr.Column(feature_checkboxes), gr.update(visible=True)
|
| 542 |
+
|
| 543 |
+
load_btn.click(
|
| 544 |
+
update_after_load,
|
| 545 |
+
outputs=[load_status, dataset_info, feature_selection, train_btn]
|
| 546 |
+
)
|
| 547 |
|
| 548 |
with gr.Tab("📊 Análise Exploratória"):
|
| 549 |
gr.Markdown("### Explore os Dados Reais do King County")
|