Applicazioni pratiche di machine learning/Previsione di reati: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
Nuova pagina: {{Applicazioni pratiche di machine learning}} ==Caricamento librerie== <syntaxhighlight lang="rsplus"> library(dplyr) library(ggplot2) library(caret) library(h2o) </syntaxhighlight>...
 
Nessun oggetto della modifica
Riga 94:
==Parte 4: Modellizzazione==
 
<syntaxhighlight lang="rsplus">
```{r}
crime$UCR_PART <- as.character(crime$UCR_PART)
crime<- crime[-which(crime$UCR_PART==""),]
crime<- crime[-which(crime$UCR_PART=="Other"),]
crime$UCR_PART <- as.factor(crime$UCR_PART)
</syntaxhighlight>
```
 
Si dividono i dati in un training set costituito dal 70% dei records su cui si costruisce il modello e in un testing set costituito dal rimanente 30% su cui si testa il modello:
 
 
<syntaxhighlight lang="rsplus">
```{r}
trainIndex <- createDataPartition(crime$UCR_PART,p=0.7, list = FALSE)
training <- crime[trainIndex,]
testing <- crime[-trainIndex,]
</syntaxhighlight>
```
 
<syntaxhighlight lang="rsplus">
```{r}
h2o.init()
</syntaxhighlight>
```
 
H2O is not running yet, starting it now...
 
 
openjdk version "11.0.8" 2020-07-14
OpenJDK Runtime Environment (build 11.0.8+10-post-Ubuntu-0ubuntu120.04)
OpenJDK 64-Bit Server VM (build 11.0.8+10-post-Ubuntu-0ubuntu120.04, mixed mode, sharing)
 
Starting H2O JVM and connecting: ..... Connection successful!
 
Line 141 ⟶ 138:
H2O API Extensions: Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4
R Version: R version 3.6.3 (2020-02-29)
 
<syntaxhighlight lang="rsplus">
training_hf <- as.h2o(training)
y <- "UCR_PART"
x <- c("Lat","Long", "YEAR" ,"MONTH" , "HOUR" , "DAY_OF_WEEK")
 
aml <- h2o.automl(x = x, y = y,
training_frame = training_hf ,max_runtime_secs = 600)
</syntaxhighlight>
 
I primi 6 modelli trovati sono i seguenti :
 
<syntaxhighlight lang="rsplus">
lb <- aml@leaderboard
lb
</syntaxhighlight>
 
model_id mean_per_class_error
1 XGBoost_2_AutoML_20201007_033612 0.6050108
2 DRF_1_AutoML_20201007_033612 0.6127668
3 XGBoost_grid__1_AutoML_20201007_033612_model_1 0.6195701
4 XRT_1_AutoML_20201007_033612 0.6196397
5 GBM_5_AutoML_20201007_033612 0.6269082
6 StackedEnsemble_BestOfFamily_AutoML_20201007_033612 0.6303185
 
Si calcola l'Accuracy dei primi 5 modelli :
 
<syntaxhighlight lang="rsplus">
test <- as.h2o(testing)
for (i in 1:nrow(lb)) {
m<-h2o.getModel(lb[i,1])
p1 = h2o.predict(m, newdata=test)
df2 <- as.data.frame(p1$predict)
print(mean(df2$predict==testing$UCR_PART))
}
</syntaxhighlight>