---
title: "Analýza dát pre diplomovú prácu"
author: "Patrícia Danová"
date: "`r Sys.Date()`"
output: 
  html_document:
    toc: true
    df_print: paged
  word_document:
    toc: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r}
library(Metrics)
library(caret)
library(corrplot)
library(dplyr)
library(ggplot2)
library(kableExtra)
library(knitr)
library(partykit)
library(patchwork)
library(randomForest)
library(readr)
library(rpart)
library(rpart.plot)
library(scales)
library(tibble)
# Načítanie datasetu z CSV súboru
data <- read_csv2("dataset_nehnutelnosti.csv", locale = locale(encoding = "UTF-8"))

# Exploratívna analýza

# Ukážka všetkých 15 stĺpcov a prvých 10 riadkov
kable(head(data[, 1:15], n=10), caption = "Ukážka všetkých 15 stĺpcov (prvých 10 riadkov)")

str(data)

# Základné štatistiky pre celý dataset
kable(summary(data), caption = "Základné štatistiky pre všetky premenné") %>%
  kable_styling(full_width = FALSE)


# Frekvenčné tabuľky
# Tabuľka kraj
tabulka <- table(data$kraj)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – kraj") %>%
  kable_styling(full_width = FALSE)

# Tabuľka mesto
tabulka <- table(data$mesto)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – mesto") %>%
  kable_styling(full_width = FALSE)

# Tabuľka obec
tabulka <- table(data$obec)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – obec") %>%
  kable_styling(full_width = FALSE)

# Tabuľka kategoria
tabulka <- table(data$kategoria)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – kategoria") %>%
  kable_styling(full_width = FALSE)

# Tabuľka balkon_loggia
tabulka <- table(data$balkon_loggia)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – balkon_loggia") %>%
  kable_styling(full_width = FALSE)

# Tabuľka parkovanie
tabulka <- table(data$parkovanie)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – parkovanie") %>%
  kable_styling(full_width = FALSE)

# Tabuľka zahrada
tabulka <- table(data$zahrada)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – zahrada") %>%
  kable_styling(full_width = FALSE)

# Tabuľka vytah
tabulka <- table(data$vytah)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – vytah") %>%
  kable_styling(full_width = FALSE)

# Tabuľka stav
tabulka <- table(data$stav)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – stav") %>%
  kable_styling(full_width = FALSE)

# Tabuľka pivnica
tabulka <- table(data$pivnica)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – pivnica") %>%
  kable_styling(full_width = FALSE)

# Tabuľka energeticky_certifikat
tabulka <- table(data$energeticky_certifikat)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

kable(tabulka_df, caption = "Frekvenčná tabuľka – energeticky_certifikat") %>%
  kable_styling(full_width = FALSE)

# Nájdenie chýbajúcich hodnôť
colSums(is.na(data))

# Upravenie hodnôt v stĺpci energeticky_certifikat
data$energeticky_certifikat <- ifelse(
  data$energeticky_certifikat %in% c("A", "B", "C", "G", "Áno"),
  "Áno",
  "Nie"
)

# Prevod na dátový rámec a premenovanie stĺpcov
tabulka <- table(data$energeticky_certifikat)
tabulka_df <- as.data.frame(tabulka)
colnames(tabulka_df) <- c("Hodnota", "Frekvencia")

# Zobrazenie frekvenčnej tabuľky
kable(tabulka_df, caption = "Frekvenčná tabuľka – energeticky_certifikat") %>%
  kable_styling(full_width = FALSE)

# Výber číselných premenných
numeric_data <- data[, c("cena", "vymera", "pocet_izieb", "podlazie")]

# Výpočet korelačnej matice
cor_matrix <- cor(numeric_data)

# Výpis korelačnej tabuľky
cor_matrix

# Vizualizácia korelačnej matice
corrplot(
  cor_matrix,
  method = "color",
  addCoef.col = "black",       # číselné hodnoty v poliach
  tl.col = "black",            # farba názvov premenných
  tl.cex = 1.1,                # veľkosť názvov
  number.cex = 1.1,            # veľkosť čísel
  tl.srt = 0,
  col = colorRampPalette(c("white", "lightblue", "steelblue"))(100)
)


# Transformácia premenných na faktorové 
data$kraj <- as.factor(data$kraj)
data$mesto <- as.factor(data$mesto)
data$obec <- as.factor(data$obec)
data$kategoria <- as.factor(data$kategoria)
data$balkon_loggia <- as.factor(data$balkon_loggia)
data$parkovanie <- as.factor(data$parkovanie)
data$zahrada <- as.factor(data$zahrada)
data$vytah <- as.factor(data$vytah)
data$stav <- as.factor(data$stav)
data$energeticky_certifikat <- as.factor(data$energeticky_certifikat)
data$pivnica <- as.factor(data$pivnica)
data$podlazie <- as.factor(data$podlazie)
data$pocet_izieb <- as.factor(data$pocet_izieb)


# Áno/Nie ako faktor
data$energeticky_certifikat <- factor(data$energeticky_certifikat, levels = c("Nie", "Áno"))

# Kontrola
str(data)

# Kontinčenčné tabuľky
# Tabuľka – parkovanie podľa kategórie
table_parkovanie_kategoria <- table(data$parkovanie, data$kategoria)

# Zobrazíme tabuľku
kable(table_parkovanie_kategoria, caption = "Kontingenčná tabuľka – Parkovanie × Kategória") %>%
  kable_styling(full_width = FALSE)

# Tabuľka – energetický certifikát podľa stavu nehnuteľnosti
table_certifikat_stav <- table(data$energeticky_certifikat, data$stav)

# Zobrazíme tabuľku
kable(table_certifikat_stav, caption = "Kontingenčná tabuľka – Energetický certifikát × Stav") %>%
  kable_styling(full_width = FALSE)

# Boxploty
# Boxplot kategoria a cena, stav a cena, kraj a cena, pocet_izieb a cena 
ggplot(data, aes(x = kategoria, y = cena)) +
  geom_boxplot(fill = "lightblue") +
  labs(title = "Cena podľa kategórie nehnuteľnosti", x = "Kategória", y = "Cena") +
  scale_y_continuous(labels = label_comma(big.mark = " ", suffix = " €")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggplot(data, aes(x = stav, y = cena)) +
  geom_boxplot(fill = "lightgreen") +
  labs(title = "Cena podľa stavu nehnuteľnosti", x = "Stav", y = "Cena") +
  scale_y_continuous(labels = scales::label_comma(big.mark = " ", suffix = " €")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggplot(data, aes(x = kraj, y = cena)) +
  geom_boxplot(fill = "lightpink") +
  labs(title = "Cena podľa kraja", x = "Kraj", y = "Cena") +
  scale_y_continuous(labels = scales::label_comma(big.mark = " ", suffix = " €")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggplot(data, aes(x = as.factor(pocet_izieb), y = cena)) +
  geom_boxplot(fill = "orange") +
  labs(title = "Cena podľa počtu izieb", x = "Počet izieb", y = "Cena") +
  scale_y_continuous(labels = scales::label_comma(big.mark = " ", suffix = " €")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5))
# Boxplot kraj, cena a kategória
ggplot(data, aes(x = kraj, y = cena, fill = kategoria)) +
  geom_boxplot() +
  labs(
    title = "Cena podľa kraja a kategórie nehnuteľnosti",
    x = "Kraj",
    y = "Cena",
    fill = "Kategória"
  ) +
  theme_minimal() +
  scale_y_continuous(labels = scales::label_number(big.mark = " ", suffix = " €")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# Stĺpcové grafy
# Graf 1: podľa kraja
g1 <- ggplot(data, aes(x = kraj, fill = kraj)) +
  geom_bar() +
  labs(title = "Podľa kraja", x = NULL, y = "Počet") +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none", axis.text.x = element_text(angle = 45, hjust = 1))

# Graf 2: podľa kategórie
g2 <- ggplot(data, aes(x = kategoria, fill = kategoria)) +
  geom_bar() +
  labs(title = "Podľa kategórie", x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")

# Graf 3: podľa stavu
g3 <- ggplot(data, aes(x = stav, fill = stav)) +
  geom_bar() +
  labs(title = "Podľa stavu", x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none", axis.text.x = element_text(angle = 45, hjust = 1))

# Graf 4: podľa výťahu
g4 <- ggplot(data, aes(x = vytah, fill = vytah)) +
  geom_bar() +
  labs(title = "Podľa výťahu", x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")

# Graf 5: Balkón / loggia
g5 <- ggplot(data, aes(x = balkon_loggia, fill = balkon_loggia)) +
  geom_bar() +
  labs(title = "Podľa balkóna/loggie", x = NULL, y = "Počet") +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")

# Graf 6: Parkovanie
g6 <- ggplot(data, aes(x = parkovanie, fill = parkovanie)) +
  geom_bar() +
  labs(title = "Podľa parkovania", x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")

# Graf 7: Pivnica
g7 <- ggplot(data, aes(x = pivnica, fill = pivnica)) +
  geom_bar() +
  labs(title = "Podľa pivnice", x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")

# Graf 8: Energetický certifikát
g8 <- ggplot(data, aes(x = energeticky_certifikat, fill = energeticky_certifikat)) +
  geom_bar() +
  labs(title = "Podľa energetického certifikátu", x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")

g9 <- ggplot(data, aes(x = pocet_izieb, fill = pocet_izieb)) +
  geom_bar() +
  labs(title = "Podľa počtu izieb", x = "Počet izieb", y = "Počet") +
  theme_minimal(base_size = 10) +
  theme(legend.position = "none")


# Spojenie grafov do jedného výstupu
(g1 | g2 | g3 ) / ( g4 | g5 |g6 ) / (g7 | g8 | g9)

# Modelovanie
# Vytvorenie novej premennej 'podlazie_typ'
data$podlazie_typ <- ifelse(data$kategoria == "Dom", "Dom",
                            ifelse(as.numeric(as.character(data$podlazie)) <= 2, "Nízke", "Vyššie"))
data$podlazie_typ <- as.factor(data$podlazie_typ)

# 2. Výber prediktorov
model_data <- data[, c("kraj", "kategoria", "stav", "pocet_izieb", "vymera", 
                       "parkovanie", "balkon_loggia", "energeticky_certifikat", "podlazie_typ", "cena")]

# 3. Rozdelenie dát na tréningové a testovacie
set.seed(123)
train_index <- createDataPartition(model_data$cena, p = 0.8, list = FALSE)
train_data <- model_data[train_index, ]
test_data <- model_data[-train_index, ]

# ID3 model
# Tréning ID3 modelu (rpart bez pruning-u)
id3_simul <- rpart(cena ~ ., 
                   data = train_data,
                   method = "anova",      
                   control = rpart.control(cp = 0, minsplit = 2))

# 1. Predikcia
id3_pred <- predict(id3_simul, newdata = test_data)

# 2. Zhrnutie uzlov
tree_summary <- as.data.frame(id3_simul$frame)
tree_summary_clean <- tree_summary %>%
  select(var, n, dev, yval) %>%
  rename(
    Premenna = var,
    Pocet_obsahovanych = n,
    Odchylka = dev,
    Priemerna_cena = yval
  )

# 3. Výstup uzlov
knitr::kable(tree_summary_clean, caption = "Zhrnutie uzlov v rozhodovacom strome ID3")

# 4. Vizualizácia stromu
rpart.plot(id3_simul,
           type = 4,
           extra = 101,
           fallen.leaves = TRUE,
           box.palette = "Blues",
           shadow.col = "gray")

names(id3_simul$variable.importance)

rpart.plot(id3_simul)

# 5. Porovnanie skutočnej a predikovanej ceny
comparison_table <- tibble(
  Skutočná_cena = test_data$cena,
  Predikovaná_cena = round(id3_pred),
  Rozdiel = round(id3_pred - test_data$cena),
  Percentuálna_odchýlka = round(((id3_pred - test_data$cena) / test_data$cena) * 100, 2)
)

knitr::kable(head(comparison_table, 10),
             caption = "Porovnanie skutočných a predikovaných cien")

# 6. Histogram chýb
ggplot(comparison_table, aes(x = abs(Rozdiel))) +
  geom_histogram(fill = "#0072B2", bins = 30, color = "white") +
  scale_x_continuous(labels = label_comma(big.mark = " ", suffix = " €")) +
  labs(
    title = "Rozloženie absolútnych chýb pri predikcii ceny (ID3)",
    x = "Absolútna chyba",
    y = "Počet nehnuteľností"
  ) +
  theme_minimal(base_size = 13)

# 7. Dôležitosť premenných
importance_df <- data.frame(
  Premenna = names(id3_simul$variable.importance),
  Dolezitost = as.numeric(id3_simul$variable.importance)
)

importance_df$Percentualna_dolezitost <- round(100 * importance_df$Dolezitost / sum(importance_df$Dolezitost), 2)

ggplot(importance_df, aes(x = reorder(Premenna, Percentualna_dolezitost), y = Percentualna_dolezitost)) +
  geom_col(fill = "#0072B2") +
  coord_flip() +
  labs(
    title = "Percentuálna dôležitosť premenných v modeli (ID3)",
    x = "Premenná",
    y = "Dôležitosť (%)"
  ) +
  theme_minimal()

# 8. Vyhodnotenie modelu
mae_id3 <- mean(abs(id3_pred - test_data$cena))
rmse_id3 <- sqrt(mean((id3_pred - test_data$cena)^2))

SSE <- sum((id3_pred - test_data$cena)^2)
SST <- sum((mean(test_data$cena) - test_data$cena)^2)
r2_id3 <- 1 - (SSE/SST)

mape_id3 <- mean(abs((id3_pred - test_data$cena) / test_data$cena)) * 100
tolerancia_10 <- mean(abs((id3_pred - test_data$cena) / test_data$cena) <= 0.10) * 100

# 9. Výpis
mae_id3
rmse_id3
r2_id3
mape_id3
tolerancia_10


# Vylepšenie modelu ID3
# 1. Zachovanie pôvodných dát
data_orig <- data

# 2. Výber prediktorov
model_data_2 <- data_orig[, c("kraj", "kategoria", "stav", "pocet_izieb", "vymera",
                              "parkovanie", "balkon_loggia", "energeticky_certifikat", "podlazie_typ", "cena")]

# 3. Rozdelenie dát
set.seed(123)
train_index <- createDataPartition(model_data_2$cena, p = 0.8, list = FALSE)

train_data_raw <- model_data_2[train_index, ]
test_data_fixed <- model_data_2[-train_index, ]

# 4. Výpočet IQR
Q1 <- quantile(model_data_2$cena, 0.25)
Q3 <- quantile(model_data_2$cena, 0.75)
IQR <- Q3 - Q1
lower_bound <- Q1 - 1.5 * IQR
upper_bound <- Q3 + 1.5 * IQR

# 5. Odstránenie odľahlých hodnôt
train_data_clean <- train_data_raw[train_data_raw$cena >= lower_bound & train_data_raw$cena <= upper_bound, ]
test_data_fixed <- test_data_fixed[test_data_fixed$cena >= lower_bound & test_data_fixed$cena <= upper_bound, ]


# 5. Tréning vylepšeného ID3 modelu
id3_model_clean <- rpart(cena ~ ., 
                         data = train_data_clean,
                         method = "anova",
                         control = rpart.control(cp = 0, minsplit = 2))

# 6. Predikcia
pred_id3_clean <- predict(id3_model_clean, newdata = test_data_fixed)


# Vytvorenie vizualizácie prerezaného stromu
pruned_model <- prune(id3_model_clean, cp = 0.01)
node_labels <- format(round(pruned_model$frame$yval / 1000), nsmall = 0)
node_n <- pruned_model$frame$n
node_text <- paste0(node_labels, "\nn=", node_n)

# Uloženie do pdf
pdf("vizualizacia_id3_tisice.pdf", width = 11, height = 8.5)
rpart.plot(pruned_model,
           type = 4,
           extra = 0,
           box.palette = "Blues",
           shadow.col = "gray",
           fallen.leaves = TRUE,
           cex = 0.4,
           main = "Zjednodušený strom ID3 – predikcie v tisícoch €",
           node.fun = function(x, labs, digits, varlen)
             node_text[as.numeric(row.names(x$frame))])
dev.off()

# Vytvorenie vizualizácie pôvodného stromu
node_labels <- format(round(id3_model_clean$frame$yval / 1000), nsmall = 0)
node_n <- id3_model_clean$frame$n
node_text <- paste0(node_labels, "\nn=", node_n)

# Uloženie do pdf
pdf("id3_plny_strom_tisice.pdf", width = 11, height = 8.5)
rpart.plot(id3_model_clean,
           type = 4,
           extra = 0,
           box.palette = "Blues",
           shadow.col = "gray",
           fallen.leaves = TRUE,
           cex = 0.3,
           main = "Plná verzia ID3 modelu – predikcie v tisícoch €",
           node.fun = function(x, labs, digits, varlen)
             node_text[as.numeric(row.names(x$frame))])
dev.off()


# 7. Vyhodnotenie modelu 
mae_id3_clean <- mae(test_data_fixed$cena, pred_id3_clean)
rmse_id3_clean <- rmse(test_data_fixed$cena, pred_id3_clean)
r2_id3_clean <- R2(pred_id3_clean, test_data_fixed$cena)
mape_id3_clean <- mape(test_data_fixed$cena, pred_id3_clean) * 100
tolerancia_10_clean <- mean(abs(pred_id3_clean - test_data_fixed$cena) <= 0.1 * test_data_fixed$cena) * 100

# 8. Výpis výsledkov
cat("MAE (čistený):", round(mae_id3_clean, 2), "€\n")
cat("RMSE (čistený):", round(rmse_id3_clean, 2), "€\n")
cat("R² (čistený):", round(r2_id3_clean, 4), "\n")
cat("MAPE (čistený):", round(mape_id3_clean, 2), "%\n")
cat("Podiel predikcií v tolerancii ±10 %:", round(tolerancia_10_clean, 2), "%\n")


# model CART
# 1.Tréning modelu CART
cart_model <- rpart(cena ~ ., 
                    data = train_data,
                    method = "anova")

# 2. Predikcia
cart_pred <- predict(cart_model, newdata = test_data)

# 3. Vykreslenie
rpart.plot(cart_model, 
           type = 4,
           extra = 101,
           box.palette = "Purples",
           fallen.leaves = TRUE)

rpart.plot(cart_model)

# 4. Porovnanie predikovanej a skutočnej ceny
comparison_cart <- tibble(
 Skutočná_cena = test_data$cena,
  Predikovaná_cena = round(cart_pred),
  Rozdiel = round(cart_pred - test_data$cena),
  Percentuálna_odchýlka = round(((cart_pred - test_data$cena) / test_data$cena) * 100, 2)
)

# 5. Zobrazenie prvých 10 riadkov
knitr::kable(head(comparison_cart, 10), caption = "Porovnanie skutočných a predikovaných cien (CART)")

# 6.Vytvorenie dát pre absolútnu chybu
abs_chyby_cart <- abs(cart_pred - test_data$cena)

# 7. Histogram absolútnych chýb
ggplot(comparison_cart, aes(x = abs(Rozdiel))) +
 geom_histogram(fill = "#FF6F61", bins = 30, color = "white") +
  scale_x_continuous(labels = label_comma(big.mark = " ", suffix = " €")) +
  labs(
    title = "Rozloženie absolútnych chýb pri predikcii ceny (CART)",
    x = "Absolútna chyba",
    y = "Počet nehnuteľností"
  ) +
  theme_minimal(base_size = 13)


# 8. Získanie dôležitosti premenných 
importance_cart <- data.frame(
 Premenna = names(cart_model$variable.importance),
Dolezitost = as.numeric(cart_model$variable.importance)
)

# 9. Výpočet percentuálneho podielu
importance_cart$Percentualna_dolezitost <- round(
  100 * importance_cart$Dolezitost / sum(importance_cart$Dolezitost), 2
)


# 10. Grafické zobrazenie
library(ggplot2)
ggplot(importance_cart, aes(x = reorder(Premenna, Percentualna_dolezitost), y = Percentualna_dolezitost)) +
  geom_col(fill = "#D55E00") +
  coord_flip() +
  labs(
   title = "Percentuálna dôležitosť premenných v modeli CART",
    x = "Premenná",
    y = "Dôležitosť (%)"
  ) +
  theme_minimal()


# 11.Vyhodnotenie modelu 
# MAE
mae_cart <- mean(abs(cart_pred - test_data$cena))

# RMSE
rmse_cart <- sqrt(mean((cart_pred - test_data$cena)^2))

# R-squared
SSE_cart <- sum((cart_pred - test_data$cena)^2)
SST_cart <- sum((mean(test_data$cena) - test_data$cena)^2)
r2_cart <- 1 - (SSE_cart / SST_cart)

# MAPE
mape_cart <- mean(abs((cart_pred - test_data$cena) / test_data$cena)) * 100

# Tolerancia ±10 %
tolerancia_cart <- mean(abs((cart_pred - test_data$cena) / test_data$cena) <= 0.10) * 100

mae_cart
rmse_cart
r2_cart
mape_cart
tolerancia_cart


# Vylepšenie modelu CART
# 1. Tréning CART modelu
cart_model_clean <- rpart(cena ~ ., 
                          data = train_data_clean,
                          method = "anova")

# 2. Predikcia 
cart_pred_clean <- predict(cart_model_clean, newdata = test_data_fixed)

# 3. Vyhodnotenie modelu
mae_cart_clean <- mean(abs(test_data_fixed$cena - cart_pred_clean))

rmse_cart_clean <- sqrt(mean((test_data_fixed$cena - cart_pred_clean)^2))

r2_cart_clean <- 1 - sum((test_data_fixed$cena - cart_pred_clean)^2) /
                    sum((test_data_fixed$cena - mean(test_data_fixed$cena))^2)

mape_cart_clean <- mean(abs((test_data_fixed$cena - cart_pred_clean) / test_data_fixed$cena)) * 100

tolerancia_10_cart <- mean(abs(test_data_fixed$cena - cart_pred_clean) <= 0.1 * test_data_fixed$cena) * 100

rpart.plot(cart_model_clean)

# 3. Výpis
cat("MAE:", round(mae_cart_clean, 2), "€\n")
cat("RMSE:", round(rmse_cart_clean, 2), "€\n")
cat("R²:", round(r2_cart_clean, 4), "\n")
cat("MAPE:", round(mape_cart_clean, 2), "%\n")
cat("Podiel predikcií v tolerancii ±10 %:", round(tolerancia_10_cart, 2), "%\n")


# 4. Vizualizácia stromu
rpart.plot(cart_model_clean, type = 4, extra = 101, box.palette = "Purples", fallen.leaves = TRUE)

node_labels <- format(round(cart_model_clean$frame$yval / 1000), nsmall = 0)
node_n <- cart_model_clean$frame$n
node_pct <- round(100 * node_n / sum(node_n))
node_text <- paste0(node_labels, "k\n", "n=", node_n, " (", node_pct, "%)")

# Uloženie do PDF
pdf("cart_model_prehladny.pdf", width = 11, height = 8.5)
rpart.plot(cart_model_clean,
           type = 4,
           extra = 0,
           box.palette = "Blues",
           shadow.col = "gray",
           fallen.leaves = TRUE,
           cex = 0.5,
           main = "Rozhodovací strom CART – predikcie v tisícoch €",
           node.fun = function(x, labs, digits, varlen)
             node_text[as.numeric(row.names(x$frame))])
dev.off()


# 5. Rozloženie absolútnych chýb
abs_diff <- abs(cart_pred_clean - test_data_fixed$cena)

ggplot(data.frame(Chyba = abs_diff), aes(x = Chyba)) +
  geom_histogram(fill = "#AF7AC5", bins = 30, color = "white") +
  scale_x_continuous(labels = scales::label_comma(suffix = " €")) +
  labs(
    title = "Rozloženie absolútnych chýb pri predikcii ceny (log-CART)",
    x = "Absolútna chyba",
    y = "Počet nehnuteľností"
  ) +
  theme_minimal()



# Model CTree
# 1. Tréning CTree modelu
ctree_model <- ctree(cena ~ ., data = train_data,
                     control = ctree_control(mincriterion = 0.75))


# 2. Konverzia pocet_izieb premennej na integer
train_data$pocet_izieb <- as.integer(as.character(train_data$pocet_izieb))
test_data$pocet_izieb <- as.integer(as.character(test_data$pocet_izieb))

# 3. Vizualizácia stromu
plot(ctree_model, main = "Rozhodovací strom CTree")


# 4. Predikcia
ctree_pred <- predict(ctree_model, newdata = test_data)

# 5. Porovnanie skutočnej a predikovanej ceny
comparison_ctree <- tibble(
 Skutočná_cena = test_data$cena,
  Predikovaná_cena = round(ctree_pred),
  Rozdiel = round(ctree_pred - test_data$cena),
  Percentuálna_odchýlka = round(((ctree_pred - test_data$cena) / test_data$cena) * 100, 2)
)

# 6. Výpis prvých 10 riadkov porovnania
kable(head(comparison_ctree, 10), caption = "Porovnanie skutočných a predikovaných cien (CTree)")

# 7. Histogram
ggplot(comparison_ctree, aes(x = abs(Rozdiel))) +
 geom_histogram(fill = "#009E73", bins = 30, color = "white") +
  scale_x_continuous(labels = label_comma(big.mark = " ", suffix = " €")) +
  labs(
   title = "Rozloženie absolútnych chýb pri predikcii ceny (CTree)",
    x = "Absolútna chyba",
    y = "Počet nehnuteľností"
  ) +
  theme_minimal(base_size = 13)

# 8. Výpočet dôležitosti
importance_df <- as.data.frame(varimp(ctree_model))

# 9. Premenujeme stĺpce
importance_df$Premenna <- rownames(importance_df)
colnames(importance_df)[1] <- "Dolezitost"
rownames(importance_df) <- NULL

# 10.Prepočet na percentá
importance_df$Percentualna_dolezitost <- round(100 * importance_df$Dolezitost / sum(importance_df$Dolezitost), 2)

# 11. Zoradenie
importance_df <- importance_df[order(-importance_df$Percentualna_dolezitost), ]
library(ggplot2)

ggplot(importance_df, aes(x = reorder(Premenna, Percentualna_dolezitost), y = Percentualna_dolezitost)) +
  geom_col(fill = "#009E73") +
  coord_flip() +
  labs(
   title = "Percentuálna dôležitosť premenných v modeli CTree",
    x = "Premenná",
    y = "Dôležitosť (%)"
  ) +
  theme_minimal()

# 12. Vyhodnotenie modelu
mae_ctree <- mean(abs(ctree_pred - test_data$cena))
rmse_ctree <- sqrt(mean((ctree_pred - test_data$cena)^2))
SSE_ctree <- sum((ctree_pred - test_data$cena)^2)
SST_ctree <- sum((mean(test_data$cena) - test_data$cena)^2)
r2_ctree <- 1 - (SSE_ctree / SST_ctree)
mape_ctree <- mean(abs((ctree_pred - test_data$cena) / test_data$cena)) * 100
tolerancia_ctree <- mean(abs((ctree_pred - test_data$cena) / test_data$cena) <= 0.10) * 100

# 13. Výpis 
cat("MAE:", round(mae_ctree, 2), "€\n")
cat("RMSE:", round(rmse_ctree, 2), "€\n")
cat("R-squared:", round(r2_ctree, 4), "\n")
cat("MAPE:", round(mape_ctree, 2), "%\n")
cat("Tolerancia ±10%:", round(tolerancia_ctree, 2), "%\n")


# Vylepšenie modelu CTree
# 1. 
train_data_ctree <- train_data_clean      
test_data_ctree <- test_data_fixed        

# 2. Konverzia faktorovej premennej na integer ak treba
train_data_ctree$pocet_izieb <- as.integer(as.character(train_data_ctree$pocet_izieb))
test_data_ctree$pocet_izieb <- as.integer(as.character(test_data_ctree$pocet_izieb))

# 3. Tréning vylepšeného modelu CTree
ctree_model_clean <- ctree(
  cena ~ .,
  data = train_data_ctree,
  control = ctree_control(mincriterion = 0.75)
)

# 4. Predikcia na testovacej množine
ctree_pred_clean <- predict(ctree_model_clean, newdata = test_data_ctree)

# 5. Vyhodnotenie výkonu
mae_ctree_clean <- mean(abs(test_data_ctree$cena - ctree_pred_clean))
rmse_ctree_clean <- sqrt(mean((test_data_ctree$cena - ctree_pred_clean)^2))
r2_ctree_clean <- cor(test_data_ctree$cena, ctree_pred_clean)^2
mape_ctree_clean <- mean(abs((test_data_ctree$cena - ctree_pred_clean) / test_data_ctree$cena)) * 100
tolerancia_ctree_clean <- mean(abs(test_data_ctree$cena - ctree_pred_clean) / test_data_ctree$cena <= 0.10) * 100

# 6. Výpis výsledkov
cat("MAE (vylepšený CTree):", round(mae_ctree_clean, 2), "€\n")
cat("RMSE:", round(rmse_ctree_clean, 2), "€\n")
cat("R²:", round(r2_ctree_clean, 4), "\n")
cat("MAPE:", round(mape_ctree_clean, 2), "%\n")
cat("Tolerancia ±10 %:", round(tolerancia_ctree_clean, 2), "%\n")

# 7. Vizualizácia vylepšeného stromu CTree
plot(ctree_model_clean, main = "Rozhodovací strom CTree (vylepšený)")

# Uloženie do pdf
pdf("ctree_model_clean.pdf", width = 11, height = 8.5)
plot(ctree_model_clean, main = "Rozhodovací strom CTree – predikcie v €")
dev.off()

# 8. Dôležitosť premenných
importance_ctree_clean <- as.data.frame(varimp(ctree_model_clean))
importance_ctree_clean$Premenna <- rownames(importance_ctree_clean)
colnames(importance_ctree_clean)[1] <- "Dolezitost"
importance_ctree_clean$Percentualna_dolezitost <- round(100 * importance_ctree_clean$Dolezitost / sum(importance_ctree_clean$Dolezitost), 2)

# 9. Graf
ggplot(importance_ctree_clean, aes(x = reorder(Premenna, Percentualna_dolezitost), y = Percentualna_dolezitost)) +
  geom_col(fill = "#009E73") +
  coord_flip() +
  labs(
    title = "Percentuálna dôležitosť premenných v modeli CTree (vylepšený)",
    x = "Premenná",
    y = "Dôležitosť (%)"
  ) +
  theme_minimal()

# 10. Histogram chýb
ggplot(data.frame(Chyba = abs(ctree_pred_clean - test_data_ctree$cena)), aes(x = Chyba)) +
  geom_histogram(fill = "#66C2A5", bins = 30, color = "white") +
  labs(
    title = "Rozloženie absolútnych chýb – vylepšený CTree",
    x = "Absolútna chyba (€)",
    y = "Počet nehnuteľností"
  ) +
  theme_minimal()


#Model Náhodný les
# 1. Tréning modelu Náhodný les
rf_model <- randomForest(cena ~ ., data = train_data, ntree = 100)

# 2. Predikcia na testovacích dátach
rf_pred <- predict(rf_model, newdata = test_data)

# 3. Porovnanie skutočnej a predikovanej ceny
comparison_df <- data.frame(
  Skutocna_cena = test_data$cena,
  Predikovana_cena = rf_pred
)


# 4. Výpočet percentuálnej odchýlky
comparison_df$Percentualna_odchylka <- round(((comparison_df$Predikovana_cena - comparison_df$Skutocna_cena) / comparison_df$Skutocna_cena) * 100, 2)

# 5. Zobrazenie prvých 10 riadkov tabuľky
head(comparison_df, 10)

# 6. Vytvorenie stĺpca s absolútnymi chybami
comparison_df$Absolutna_chyba <- abs(comparison_df$Skutocna_cena - comparison_df$Predikovana_cena)

# 7. Vytvorenie histogramu pre absolútne chyby
ggplot(comparison_df, aes(x = Absolutna_chyba)) +
  geom_histogram(fill = "#0072B2", bins = 30, color = "white") +
  scale_x_continuous(labels = scales::label_comma(big.mark = " ", suffix = " €")) +
  labs(
    title = "Rozloženie absolútnych chýb pri predikcii ceny",
    x = "Absolútna chyba",
    y = "Počet nehnuteľností"
  ) +
  theme_minimal(base_size = 13)

# 8. Získanie dôležitosti premenných
importance_rf <- importance(rf_model)

# 9. Prevod dôležitosti na dátový rámec
importance_df_rf <- data.frame(
  Premenna = rownames(importance_rf), 
  Dolezitost = importance_rf[, 1] 
)

# 10. Normalizovanie dôležitosti na percentá
importance_df_rf$Percentualna_dolezitost <- round(100 * importance_df_rf$Dolezitost / sum(importance_df_rf$Dolezitost), 2)

# 11. Zoradenie podľa dôležitosti
importance_df_rf <- importance_df_rf[order(-importance_df_rf$Dolezitost), ]

# 12. Vizualizácia dôležitosti premenných

ggplot(importance_df_rf, aes(x = reorder(Premenna, Percentualna_dolezitost), y = Percentualna_dolezitost)) +
  geom_col(fill = "#0072B2") +
  coord_flip() +
  labs(
    title = "Percentuálna dôležitosť premenných v modeli Náhodný les",
    x = "Premenná",
    y = "Dôležitosť (%)"
  ) +
  theme_minimal(base_size = 13)
# Výpočet MAE
mae_rf <- mean(abs(rf_pred - test_data$cena))

# Výpočet RMSE
rmse_rf <- sqrt(mean((rf_pred - test_data$cena)^2))

# Výpočet R-squared
SSE_rf <- sum((rf_pred - test_data$cena)^2)
SST_rf <- sum((mean(test_data$cena) - test_data$cena)^2)
r2_rf <- 1 - (SSE_rf / SST_rf)

# Výpočet MAPE
mape_rf <- mean(abs((rf_pred - test_data$cena) / test_data$cena)) * 100

# Tolerancia ±10 %
tolerancia_rf <- mean(abs((rf_pred - test_data$cena) / test_data$cena) <= 0.10) * 100

# Výpis metrik
cat("MAE:", round(mae_rf, 2), "€\n")
cat("RMSE:", round(rmse_rf, 2), "€\n")
cat("R-squared:", round(r2_rf, 4), "\n")
cat("MAPE:", round(mape_rf, 2), "%\n")
cat("Tolerancia ±10%:", round(tolerancia_rf, 2), "%\n")


# Vylepšenie modelu Náhodný les
# 1. Tréning 
rf_model_clean <- randomForest(cena ~ ., data = train_data_clean, ntree = 500)

# 2. Predikcia 
pred_rf_clean <- predict(rf_model_clean, newdata = test_data_fixed)

# 3. Vyhodnotenie výkonu
mae_rf_clean <- mean(abs(pred_rf_clean - test_data_fixed$cena))
rmse_rf_clean <- sqrt(mean((pred_rf_clean - test_data_fixed$cena)^2))
r2_rf_clean <- 1 - sum((test_data_fixed$cena - pred_rf_clean)^2) / sum((test_data_fixed$cena - mean(test_data_fixed$cena))^2)
mape_rf_clean <- mean(abs((test_data_fixed$cena - pred_rf_clean) / test_data_fixed$cena)) * 100
tolerancia_rf_clean <- mean(abs((test_data_fixed$cena - pred_rf_clean) / test_data_fixed$cena) <= 0.10) * 100


# 4. Výpis výsledkov
cat("MAE:", round(mae_rf_clean, 2), "€\n")
cat("RMSE:", round(rmse_rf_clean, 2), "€\n")
cat("R²:", round(r2_rf_clean, 4), "\n")
cat("MAPE:", round(mape_rf_clean, 2), "%\n")
cat("Tolerancia ±10 %:", round(tolerancia_rf_clean, 2), "%\n")
