Projet Apprentissage statistique

Fontaine Aymeric

Tavian Matteo

Bertholon Kilian

Etape 1 : Explication sur les données traitées.

Nous avons choisi de travailler sur des données de football. Ne trouvant pas de jeu de données intéresant. Nous avons donc choisi décidé de web-scrapper des données issus d’un site Internet. Nous avons décidé de travailer sur le site : https://redscores.com/fr/football-stats.

A l’aide d’un code Javascript construit pour cela nous avons pu récupérer les données issues de 42000 joueurs sur plus de 5 saisons (sur les 10 plus grands championnats mondiaux ainsi que 5 championnats de 2ème division.

Le code Javascript est disponible dans le dossier code Javascript.

Pour chacun des joueurs on dispose d’informations sur ses performances au court de l’année :

  • Son nom

  • Son poste

  • Son club

  • Son Age

  • Le nombre de Minutes jouées dans l’années

  • Le nombre d’apparitions (en match)

  • Le nombre de but(s) qu’il a inscrit

  • Le nombre de passe(s) décisive(s) qu’il a délivré

  • Sa note moyenne sur l’ensemble de l’année

  • Le nombre de tirs moyen par match

  • Le nombre de dribbles moyen par match

  • Le pourcentage de passes réussis par match

  • La moyenne de passes clés par match

  • Le pourcentage de centres réussis

  • Le nombre de dégagement par match

  • Le nombre d’interception moyens par match

  • Le nombre de tacle moyen par match

  • Le nombre de Tir bloqué moyen par match

  • Le nombre de dribbles subis moyen par match

  • Le nombre de faute moyen par match

  • Le nombre de tacle moyen recu par match

  • Le nombre de Hors-jeu moyen par match

  • L’année de références des stastiques

Etape 2 : Import des données et Pré-traitement

#### Chargement des packages ####

library(jsonlite)
## Warning: le package 'jsonlite' a été compilé avec la version R 4.3.2
library(tidyr)
library(ggplot2)
## Warning: le package 'ggplot2' a été compilé avec la version R 4.3.2
library(dplyr)
## 
## Attachement du package : 'dplyr'
## Les objets suivants sont masqués depuis 'package:stats':
## 
##     filter, lag
## Les objets suivants sont masqués depuis 'package:base':
## 
##     intersect, setdiff, setequal, union
library(corrplot)
## Warning: le package 'corrplot' a été compilé avec la version R 4.3.2
## corrplot 0.92 loaded
library(ggraph)
## Warning: le package 'ggraph' a été compilé avec la version R 4.3.2
library(tidymodels)
## ── Attaching packages ────────────────────────────────────── tidymodels 1.1.1 ──
## ✔ broom        1.0.5     ✔ rsample      1.2.0
## ✔ dials        1.2.0     ✔ tibble       3.2.1
## ✔ infer        1.0.5     ✔ tune         1.1.2
## ✔ modeldata    1.2.0     ✔ workflows    1.1.3
## ✔ parsnip      1.1.1     ✔ workflowsets 1.0.1
## ✔ purrr        1.0.2     ✔ yardstick    1.2.0
## ✔ recipes      1.0.9
## Warning: le package 'scales' a été compilé avec la version R 4.3.2
## Warning: le package 'parsnip' a été compilé avec la version R 4.3.2
## Warning: le package 'recipes' a été compilé avec la version R 4.3.2
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ purrr::discard() masks scales::discard()
## ✖ dplyr::filter()  masks stats::filter()
## ✖ purrr::flatten() masks jsonlite::flatten()
## ✖ dplyr::lag()     masks stats::lag()
## ✖ recipes::step()  masks stats::step()
## • Use suppressPackageStartupMessages() to eliminate package startup messages
library(xgboost)
## Warning: le package 'xgboost' a été compilé avec la version R 4.3.2
## 
## Attachement du package : 'xgboost'
## L'objet suivant est masqué depuis 'package:dplyr':
## 
##     slice
library(doParallel)
## Warning: le package 'doParallel' a été compilé avec la version R 4.3.2
## Le chargement a nécessité le package : foreach
## 
## Attachement du package : 'foreach'
## Les objets suivants sont masqués depuis 'package:purrr':
## 
##     accumulate, when
## Le chargement a nécessité le package : iterators
## Le chargement a nécessité le package : parallel
library(vip)
## Warning: le package 'vip' a été compilé avec la version R 4.3.2
## 
## Attachement du package : 'vip'
## L'objet suivant est masqué depuis 'package:utils':
## 
##     vi
library(plotly)
## Warning: le package 'plotly' a été compilé avec la version R 4.3.2
## 
## Attachement du package : 'plotly'
## L'objet suivant est masqué depuis 'package:xgboost':
## 
##     slice
## L'objet suivant est masqué depuis 'package:ggplot2':
## 
##     last_plot
## L'objet suivant est masqué depuis 'package:stats':
## 
##     filter
## L'objet suivant est masqué depuis 'package:graphics':
## 
##     layout
library(yardstick)

Dans cette partie, nous effectuerons les modifications nécessaires pour créer le dataframe que l’on utilisera à partir des JSON crée précédamment par le scrapping

#Indiquer les années disponibles
year_available <- 2019:2023

#Boucle de création du dataframe à partir des nom de fichiers
for (annee in year_available) {
  fichier_data <- paste0("resultat_football_", annee, ".json")
  data <- fromJSON(fichier_data)
  
  top10 <- data$Top10_championnat
  hors_top10 <- data$Autres
  
  data <- rbind(top10, hors_top10)
  data = data[-1]
  
  data <- separate(data, info, into = c("Poste", "Club", "Age"), sep = ",\\s*")
  
  data$Age <- sub("yrs", "", data$Age)
  data$Passes_perc <- (as.numeric(sub("%", "", data$Passes_perc)))
  
  data <- data %>% rename(Apparences = CartonJaune)
  
  cols_to_convert <- c("Age", "minJ", "Apparences", "But", "PasseDecisive", "Note", "Tirs",
                       "Dribbles", "moy_passes", "centre_perc", "degagement", "interception",
                       "tacle", "tirsBloques", "driblesSubis", "fautes", "TaclesRecu", "HorsJeu")
  
  data[, cols_to_convert] <- lapply(data[, cols_to_convert], function(x) as.numeric(gsub("'", "", x)))
  
  data$Annee <- as.character(annee)
  
  assign(paste0("data_", annee), data)
}
## Warning: Expected 3 pieces. Missing pieces filled with `NA` in 40 rows [1940, 2178,
## 2581, 2811, 3559, 3879, 4026, 4144, 4173, 4891, 5530, 5707, 5810, 5812, 5831,
## 5864, 6240, 6287, 6532, 6683, ...].
## Warning: Expected 3 pieces. Missing pieces filled with `NA` in 141 rows [404, 604, 921,
## 1265, 1368, 1553, 1904, 2566, 2804, 2914, 3072, 3337, 3402, 3415, 3574, 3683,
## 3877, 3948, 4194, 4212, ...].
## Warning: Expected 3 pieces. Missing pieces filled with `NA` in 226 rows [37, 151, 194,
## 302, 372, 652, 681, 837, 986, 1247, 1312, 1472, 1555, 1598, 1714, 1920, 1974,
## 2089, 2153, 2259, ...].
## Warning: Expected 3 pieces. Missing pieces filled with `NA` in 245 rows [93, 127, 229,
## 671, 1006, 1358, 1553, 1627, 1667, 1706, 1735, 1743, 1765, 1959, 1962, 1986,
## 2058, 2067, 2069, 2287, ...].
## Warning: Expected 3 pieces. Missing pieces filled with `NA` in 307 rows [110, 371, 519,
## 566, 669, 691, 735, 779, 884, 909, 988, 1028, 1129, 1176, 1207, 1261, 1320,
## 1336, 1357, 1390, ...].
all_data <- rbind(data_2023, data_2022, data_2021, data_2020, data_2019)

summary(all_data)
##      nom               Poste               Club                Age      
##  Length:41600       Length:41600       Length:41600       Min.   :16.0  
##  Class :character   Class :character   Class :character   1st Qu.:24.0  
##  Mode  :character   Mode  :character   Mode  :character   Median :27.0  
##                                                           Mean   :27.5  
##                                                           3rd Qu.:31.0  
##                                                           Max.   :46.0  
##                                                           NA's   :959   
##       minJ          Apparences         But         PasseDecisive   
##  Min.   :   0.0   Min.   : 1.00   Min.   : 0.000   Min.   : 0.000  
##  1st Qu.: 324.0   1st Qu.: 8.00   1st Qu.: 0.000   1st Qu.: 0.000  
##  Median : 971.5   Median :16.00   Median : 0.000   Median : 0.000  
##  Mean   :1154.6   Mean   :17.38   Mean   : 1.529   Mean   : 1.043  
##  3rd Qu.:1821.0   3rd Qu.:27.00   3rd Qu.: 2.000   3rd Qu.: 1.000  
##  Max.   :4410.0   Max.   :49.00   Max.   :43.000   Max.   :21.000  
##                                                                    
##       Note            Tirs           Dribbles       Passes_perc    
##  Min.   :1.700   Min.   :0.0000   Min.   :0.0000   Min.   :  0.00  
##  1st Qu.:6.600   1st Qu.:0.1000   1st Qu.:0.2000   1st Qu.:  0.00  
##  Median :6.800   Median :0.4000   Median :0.6000   Median : 73.00  
##  Mean   :6.779   Mean   :0.5466   Mean   :0.8665   Mean   : 55.23  
##  3rd Qu.:7.000   3rd Qu.:0.8000   3rd Qu.:1.3000   3rd Qu.: 80.00  
##  Max.   :9.300   Max.   :6.3000   Max.   :9.3000   Max.   :100.00  
##  NA's   :2044                                                      
##    moy_passes      centre_perc      degagement  interception   
##  Min.   :0.0000   Min.   :  0.0   Min.   :0    Min.   :0.0000  
##  1st Qu.:0.1000   1st Qu.:  0.0   1st Qu.:0    1st Qu.:0.1000  
##  Median :0.4000   Median : 14.3   Median :0    Median :0.5000  
##  Mean   :0.5007   Mean   : 16.5   Mean   :0    Mean   :0.6055  
##  3rd Qu.:0.8000   3rd Qu.: 26.2   3rd Qu.:0    3rd Qu.:1.0000  
##  Max.   :6.0000   Max.   :100.0   Max.   :0    Max.   :6.0000  
##                                                                
##      tacle         tirsBloques      driblesSubis        fautes    
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.00  
##  1st Qu.:0.3000   1st Qu.:0.0000   1st Qu.:0.2000   1st Qu.:0.40  
##  Median :0.8000   Median :0.1000   Median :0.4000   Median :0.70  
##  Mean   :0.9125   Mean   :0.1613   Mean   :0.4713   Mean   :0.75  
##  3rd Qu.:1.4000   3rd Qu.:0.2000   3rd Qu.:0.7000   3rd Qu.:1.10  
##  Max.   :8.0000   Max.   :5.0000   Max.   :6.0000   Max.   :5.00  
##                                                                   
##    TaclesRecu        HorsJeu     Annee          
##  Min.   :0.0000   Min.   :0   Length:41600      
##  1st Qu.:0.3000   1st Qu.:0   Class :character  
##  Median :0.6000   Median :0   Mode  :character  
##  Mean   :0.6836   Mean   :0                     
##  3rd Qu.:1.0000   3rd Qu.:0                     
##  Max.   :6.0000   Max.   :0                     
## 

Etape 3 : Première analyses visuelles sur les données

Analyse des distributions variables par variables

a) Répartition par postes

#Les postes étaient avant des postes précis (milieu offensif droit par exemple. Par soucis de compréhension nous remplacons ces postes par 4 modalités (Gardien, défenseur, milieu et attaquant))
all_data <- all_data %>%
  mutate(Poste_global = case_when(
    Poste %in% c("AM", "CF", "LW", "RW") ~ "Attaquant",
    Poste %in% c("CB", "DF", "LB", "RB") ~ "Défenseur",
    Poste %in% c("CM", "DM", "LM", "MF", "RM") ~ "Milieu",
    Poste == "GK" ~ "Gardien",
    Poste == '' ~ NA,
    TRUE ~ "Autre"
  ))
ggplot(all_data, aes(x = Poste_global)) +
  geom_bar(fill = "skyblue", color = "black") +
  labs(title = "Distribution des postes des joueurs de foot",
       x = "Poste",
       y = "Nombre de joueurs")

b) Age

# Créez un histogramme de l'âge
ggplot(all_data, aes(x = Age)) +
  geom_histogram(binwidth = 1, fill = "cyan", color = "black", alpha = 0.7) +
  labs(title = "Distribution de l'âge des joueurs", x = "Âge", y = "Fréquence")
## Warning: Removed 959 rows containing non-finite values (`stat_bin()`).

c) But

all_data$Poste_global <- factor(all_data$Poste_global, levels = c("Gardien", "Défenseur", "Milieu", "Attaquant", "NA"))

ggplot(all_data, aes(x = Poste_global, y = But)) +
  geom_boxplot(fill = "skyblue", color = "black") +  
  labs(title = "Distribution des buts par poste global",
       x = "Poste Global",
       y = "Buts")

d) Passes décisives

# Créez un boxplot pour la distribution des passes décisives en fonction du poste global
ggplot(all_data, aes(x = Poste_global, y = PasseDecisive, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des passes décisives en fonction du poste global", x = "Poste global", y = "Passe décisives") +
  scale_fill_brewer(palette = "Set3")  # Vous pouvez changer la palette de couleurs selon vos préférences

e) Minutes jouées

Min_joue_poste<- ggplot(all_data, aes(x = Poste_global, y = minJ, fill = Poste_global)) +
  geom_boxplot() +  # Utiliser un boxplot pour la distribution
  labs(title = "Distribution des Minutes jouées par poste ",
       x = "Poste ",
       y = "Minutes jouées")

# Afficher le graphique
print(Min_joue_poste)

f) Apparitions

# Créez un boxplot pour la distribution des passes décisives en fonction du poste global
ggplot(all_data, aes(x = Poste_global, y = Apparences, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des apparitions des joueurs en fonction du poste global", x = "Poste global", y = "Apparitions") +
  scale_fill_brewer(palette = "Set3")  # Vous pouvez changer la palette de couleurs selon vos préférences

g) Note

# Créez un boxplot pour la distribution des Notes fonction du poste global
ggplot(all_data, aes(x = Poste_global, y = Note, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des notes des joueurs en fonction du poste global", x = "Poste global", y = "Note") +
  scale_fill_brewer(palette = "Set3")  # Vous pouvez changer la palette de couleurs selon vos préférences
## Warning: Removed 2044 rows containing non-finite values (`stat_boxplot()`).

h) Tirs

ggplot(all_data, aes(x = Poste_global, y = Tirs, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des tirs des joueurs en fonction du poste global", x = "Poste global", y = "Tirs") +
  scale_fill_brewer(palette = "Set3") 

i) Dribbles

ggplot(all_data, aes(x = Poste_global, y = Dribbles , fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des dribbles des joueurs en fonction du poste global", x = "Poste global", y = "Dribbles") +
  scale_fill_brewer(palette = "Set3")

j) Passes Pourcentages

ggplot(all_data, aes(x = Poste_global, y = Passes_perc , fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des pourcentages de passes réussies des joueurs en fonction du poste global", x = "Poste global", y = "Pourcentage de passes réussies") +
  scale_fill_brewer(palette = "Set3") 

k) Moyenne passe clé

ggplot(all_data, aes(x = Poste_global, y = moy_passes , fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des moyennes des passes clées des joueurs en fonction du poste global", x = "Poste global", y = "Moyenne de passes clées par match") +
  scale_fill_brewer(palette = "Set3")  

l) Centre pourcentage

ggplot(all_data, aes(x = Poste_global, y = centre_perc , fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des pourcentages de centres réussies des joueurs en fonction du poste global", x = "Poste global", y = "Pourcentage de centres réussis") +
  scale_fill_brewer(palette = "Set3") 

m) Dégagement

ggplot(all_data, aes(x = Poste_global, y = degagement , fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des dégagements des joueurs en fonction du poste global", x = "Poste global", y = "Dégagements") +
  scale_fill_brewer(palette = "Set3") 

On voit que tout les boxplots quelque soit le poste sont situées à 0. Cela signifie que toute la colonne “degagement” du jeu de données est constituée de 0. Cette variable n’est donc pas nécessaire, on peut la supprimer.

all_data <- subset(all_data, select = -degagement)

n) Interception

ggplot(all_data, aes(x = Poste_global, y = interception , fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Distribution des interceptions des joueurs en fonction du poste global", x = "Poste global", y = "interception") +
  scale_fill_brewer(palette = "Set3")

o) Tacles recus

ggplot(all_data, aes(x = Poste_global, y = TaclesRecu, fill = Poste_global)) +
  geom_boxplot() +  
  labs(title = "Tacles recus par postes",
       x = "Postes ",
       y = "Tacles recus")

p) Tirs bloques

ggplot(all_data, aes(x = Poste_global, y = tirsBloques, fill = Poste_global)) +
  geom_boxplot() + 
  labs(title = "Tirs bloqués par par postes",
       x = "Postes ",
       y = "Tirs bloqués")

q) Dribles subis

ggplot(all_data, aes(x = Poste_global, y = driblesSubis, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Dribles subis par par postes",
       x = "Postes ",
       y = "Dribles Subis")

r) Fautes commises moyennes par match

ggplot(all_data, aes(x = Poste_global, y = fautes, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Fautes par postes",
       x = "Postes",
       y = "Fautes moyenne par match")

s) Tacles recu

ggplot(all_data, aes(x = Poste_global, y = TaclesRecu, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Tacles recu par postes",
       x = "Poste ",
       y = "Tacles recu")

t) Hors jeu

ggplot(all_data, aes(x = Poste_global, y = HorsJeu, fill = Poste_global)) +
  geom_boxplot() +
  labs(title = "Hors jeu par postes",
       x = "Poste ",
       y = "Hors jeu")

On voit ici que les Hors jeu sont nul pour chacunes des modalités. On peut donc substituer cette colonne dans le cas ou nos données ne seront pas completées par de nouvelles données comportant des hors-jeu

all_data <- subset(all_data, select = -HorsJeu)

u) Annee

table_annee <- data.frame(table(all_data$Annee))

ggplot(table_annee, aes(x = Var1, y = Freq)) +
  geom_bar(stat = "identity", fill = "skyblue", color = "black") +
  labs(title = "Observation par années",
       x = "Année",
       y = "Observations")

Analyse des corrélations globales

On peut penser que certaines variables peuvent être corrélées. Selon le modèle que l’on utilise ca pourrait éventuellement nous poser problèmes. On va donc étudier cela.

Nous avons seulement des variables quantitatives –> corrélations de Pearson

# Sélectionner seulement les colonnes avec des variables quantitatives
variables_quantitatives <- all_data %>%
  select_if(is.numeric)

variables_quantitatives <- na.omit(variables_quantitatives)

# Calculer la matrice de corrélation
matrice_correlation <- cor(variables_quantitatives, use = "complete.obs")

# Afficher une heatmap avec corrplot
corrplot(matrice_correlation, method = "color", type = "lower", diag = FALSE, col = COL2('RdYlBu', 10))

Quelques variables paraissent un peu corrélées :

  • Minutes jouées avec le nombre d’apparitions ( ce qui parait logique )

  • Le nombre de but avec le nombre de tirs

  • Le nombre de passe clés avec le nombre de passes décisives

  • Le pourcentage de passes avec le nombre d’apparritions

  • Le nombre d’interception avec le nombre de tacles

Etape 4 : Identification des probématiques potentielles :

Dans le cadre du footbal, plusieurs problématiques peuvent se poser devant nous avec les données dont nous disposons :

  1. Essayer de calculer la note des joueurs à partir de leurs statistiques

  2. Essayer d’identifier des performances futures à partir des performances passées

  3. Essayer de confirmer des choix de l’entraineurs (visualisables à partir de apparitions et des minutes jouées)

  4. Essayer d’identifier des critères de performances pour chacuns des postes

1) Note des joueurs

Le site sur lesquel nous avons recolté nos données permet d’obtenir les notes de chaque joueurs. Nous aimerions pouvoir recalculer les notes de chacun des joueurs à partir de leurs statistiques.

Cependant, nos connaissances de la disciplines nous indiquent que les notes des joueurs à partir des statistiques seront dépendantes du postes (un attaquant qui effectue plus de tirs sera avantagé car c’est ce qu’on lui demande)

L’ensemble de nos variables sont quantitatives : Nous allons donc pouvoir essayer plusieurs modèles différents afin d’estimer aux plus justes les notes des joueurs.

Dans un premier temps, il va donc falloir préparer nos données pour rassembler les joueurs par postes.

Notre démarche s’effectuera de tel sorte :

  1. Préparer nos donnnées

  2. Comparer les différents modèles vus en cours sur l’ensemble de nos données ( reg LASSO, reg RIDGE, reg Linéaire, XGboost, Foret aléatoires).

  1. Sélectionner le modèle qui semble le plus efficace

  2. Essayer d’obtimiser les différentes variables pour augmenter la prédiction finale

Pré-traitement des données

Rassembler les joueurs par postes

Gardien <- all_data |> filter(Poste_global == "Gardien")
Defenseur <- all_data |> filter(Poste_global == "Défenseur")
Milieu <- all_data |> filter(Poste_global == "Milieu")
Attaquant <- all_data |> filter(Poste_global == "Attaquant")

Etudier la distribution des notes par postes

density <- ggplot(all_data, aes(Note, color = Poste_global)) + geom_density()
density
## Warning: Removed 2044 rows containing non-finite values (`stat_density()`).

On semble plutot suivre une loin normale sur chacun des notes des différents postes

Utilisation des différents algorithmes

a) XGBoost

Attaquant

all_data_attaquant <- subset(Attaquant, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_attaquant <- na.omit(all_data_attaquant, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split_att <- initial_split(all_data_attaquant, prop = 0.75, strata = Note)
data_train_att <- training(data_split_att)
data_test_att <- testing(data_split_att)

#Préparation des données 
variable_a_tester_xg <- c("Age","minJ","Apparences","But","PasseDecisive","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")
recipe_xg_att <- recipe(Note ~ ., data = data_train_att) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_predictors())

xgb_model_att <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf_att <- workflow() |>
  add_recipe(recipe_xg_att) |>
  add_model(xgb_model_att)

play_samples_cv_att <- vfold_cv(data_train_att,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold_att <- xgb_wf_att |>
  tune_grid(resamples=play_samples_cv_att,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold_att |> autoplot()

best_par_att <- xgb_3fold_att |>
  select_best()

final_xgb_att <- xgb_wf_att |> 
  finalize_workflow(best_par_att) |>
  fit(data = data_train_att)

pred_att <- final_xgb_att |>
  predict(new_data=data_test_att)


data_test_att_fin <- data_test_att |> select(Note)
data_test_att_fin_2 <- cbind(pred_att, data_test_att_fin)

data_test_att_fin_2$Difference <- data_test_att_fin_2$Note - data_test_att_fin_2$.pred
data_test_att_fin_2$DifferenceAbs <- abs(data_test_att_fin_2$Note - data_test_att_fin_2$.pred)


# Calculer la médiane et les intervalles de confiance
median_diff_att <- median(data_test_att_fin_2$Difference)
ci_low_att <- quantile(data_test_att_fin_2$Difference, 0.025)
ci_high_att <- quantile(data_test_att_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot_att <- ggplot(data_test_att_fin_2, aes(x = rownames(data_test_att_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff_att, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low_att, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high_att, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur Attaquant",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
gg_plot_att

R2_att_xg <- 1 - sum((data_test_att_fin_2$Note - data_test_att_fin_2$.pred)^2) / sum((data_test_att_fin_2$Note - mean(data_test_att_fin_2$Note))^2)
RMSE_att_xg <- sqrt(mean((data_test_att_fin_2$Note - data_test_att_fin_2$.pred)^2))
erreur_moy_abs_att_xg <- mean(data_test_att_fin_2$DifferenceAbs)

Milieu

all_data_milieu <- subset(Milieu, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_milieu <- na.omit(all_data_milieu, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split_mil <- initial_split(all_data_milieu, prop = 0.75, strata = Note)
data_train_mil <- training(data_split_mil)
data_test_mil <- testing(data_split_mil)

#Préparation des données 
variable_a_tester_xg <- c("Age","minJ","Apparences","But","PasseDecisive","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")
recipe_xg_mil <- recipe(Note ~ ., data = data_train_mil) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_predictors())

xgb_model_mil <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf_mil <- workflow() |>
  add_recipe(recipe_xg_mil) |>
  add_model(xgb_model_mil)

play_samples_cv_mil <- vfold_cv(data_train_mil,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold_mil <- xgb_wf_mil |>
  tune_grid(resamples=play_samples_cv_mil,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold_mil |> autoplot()

best_par_mil <- xgb_3fold_mil |>
  select_best()

final_xgb_mil <- xgb_wf_mil |> 
  finalize_workflow(best_par_mil) |>
  fit(data = data_train_mil)

pred_mil <- final_xgb_mil |>
  predict(new_data=data_test_mil)


data_test_mil_fin <- data_test_mil |> select(Note)
data_test_mil_fin_2 <- cbind(pred_mil, data_test_mil_fin)

data_test_mil_fin_2$Difference <- data_test_mil_fin_2$Note - data_test_mil_fin_2$.pred
data_test_mil_fin_2$DifferenceAbs <- abs(data_test_mil_fin_2$Note - data_test_mil_fin_2$.pred)


# Calculer la médiane et les intervalles de confiance
median_diff_mil <- median(data_test_mil_fin_2$Difference)
ci_low_mil <- quantile(data_test_mil_fin_2$Difference, 0.025)
ci_high_mil <- quantile(data_test_mil_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot_mil <- ggplot(data_test_mil_fin_2, aes(x = rownames(data_test_mil_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff_mil, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low_mil, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high_mil, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur Milieu",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot_mil

R2_mil_xg <- 1 - sum((data_test_mil_fin_2$Note - data_test_mil_fin_2$.pred)^2) / sum((data_test_mil_fin_2$Note - mean(data_test_mil_fin_2$Note))^2)
RMSE_mil_xg <- sqrt(mean((data_test_mil_fin_2$Note - data_test_mil_fin_2$.pred)^2))
erreur_moy_abs_mil_xg <- mean(data_test_mil_fin_2$DifferenceAbs)

Défenseur

all_data_defenseur <- subset(Defenseur, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_defenseur <- na.omit(all_data_defenseur, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split_def <- initial_split(all_data_defenseur, prop = 0.75, strata = Note)
data_train_def <- training(data_split_def)
data_test_def <- testing(data_split_def)

#Préparation des données 
variable_a_tester_xg <- c("Age","minJ","Apparences","But","PasseDecisive","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")
recipe_xg_def <- recipe(Note ~ ., data = data_train_def) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_predictors())

xgb_model_def <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf_def <- workflow() |>
  add_recipe(recipe_xg_def) |>
  add_model(xgb_model_def)

play_samples_cv_def <- vfold_cv(data_train_def,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold_def <- xgb_wf_def |>
  tune_grid(resamples=play_samples_cv_def,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold_def |> autoplot()

best_par_def <- xgb_3fold_def |>
  select_best()

final_xgb_def <- xgb_wf_def |> 
  finalize_workflow(best_par_def) |>
  fit(data = data_train_def)

pred_def <- final_xgb_def |>
  predict(new_data=data_test_def)


data_test_def_fin <- data_test_def |> select(Note)
data_test_def_fin_2 <- cbind(pred_def, data_test_def_fin)

data_test_def_fin_2$Difference <- data_test_def_fin_2$Note - data_test_def_fin_2$.pred
data_test_def_fin_2$DifferenceAbs <- abs(data_test_def_fin_2$Note - data_test_def_fin_2$.pred)


# Calculer la médiane et les intervalles de confiance
median_diff_def <- median(data_test_def_fin_2$Difference)
ci_low_def <- quantile(data_test_def_fin_2$Difference, 0.025)
ci_high_def <- quantile(data_test_def_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot_def <- ggplot(data_test_def_fin_2, aes(x = rownames(data_test_def_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff_def, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low_def, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high_def, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur Défenseur",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot_def

R2_def_xg <- 1 - sum((data_test_def_fin_2$Note - data_test_def_fin_2$.pred)^2) / sum((data_test_def_fin_2$Note - mean(data_test_def_fin_2$Note))^2)
RMSE_def_xg <- sqrt(mean((data_test_def_fin_2$Note - data_test_def_fin_2$.pred)^2))
erreur_moy_abs_def_xg <- mean(data_test_def_fin_2$DifferenceAbs)

Gardien

all_data_gardien <- subset(Gardien, select = -c(nom, Poste, Club, Annee, Poste_global, tirsBloques))
all_data_gardien <- na.omit(all_data_gardien, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split_gar <- initial_split(all_data_gardien, prop = 0.75, strata = Note)
data_train_gar <- training(data_split_gar)
data_test_gar <- testing(data_split_gar)

#Préparation des données 
variable_a_tester_xg <- c("Age","minJ","Apparences","But","PasseDecisive","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","driblesSubis","fautes","TaclesRecu")
recipe_xg_gar <- recipe(Note ~ ., data = data_train_gar) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_predictors())

xgb_model_gar <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf_gar <- workflow() |>
  add_recipe(recipe_xg_gar) |>
  add_model(xgb_model_gar)

play_samples_cv_gar <- vfold_cv(data_train_gar,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold_gar <- xgb_wf_gar |>
  tune_grid(resamples=play_samples_cv_gar,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold_gar |> autoplot()

best_par_gar <- xgb_3fold_gar |>
  select_best()

final_xgb_gar <- xgb_wf_gar |> 
  finalize_workflow(best_par_gar) |>
  fit(data = data_train_gar)

pred_gar <- final_xgb_gar |>
  predict(new_data=data_test_gar)


data_test_gar_fin <- data_test_gar |> select(Note)
data_test_gar_fin_2 <- cbind(pred_gar, data_test_gar_fin)

data_test_gar_fin_2$Difference <- data_test_gar_fin_2$Note - data_test_gar_fin_2$.pred
data_test_gar_fin_2$DifferenceAbs <- abs(data_test_gar_fin_2$Note - data_test_gar_fin_2$.pred)


# Calculer la médiane et les intervalles de confiance
median_diff_gar <- median(data_test_gar_fin_2$Difference)
ci_low_gar <- quantile(data_test_gar_fin_2$Difference, 0.025)
ci_high_gar <- quantile(data_test_gar_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot_gar <- ggplot(data_test_gar_fin_2, aes(x = rownames(data_test_gar_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff_gar, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low_gar, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high_gar, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur Gardien",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot_gar

R2_gar_xg <- 1 - sum((data_test_gar_fin_2$Note - data_test_gar_fin_2$.pred)^2) / sum((data_test_gar_fin_2$Note - mean(data_test_gar_fin_2$Note))^2)
RMSE_gar_xg <- sqrt(mean((data_test_gar_fin_2$Note - data_test_gar_fin_2$.pred)^2))
erreur_moy_abs_gar_xg <- mean(data_test_gar_fin_2$DifferenceAbs)

Total

all_data_xg <- subset(all_data, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_xg <- na.omit(all_data_xg, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split <- initial_split(all_data_xg, prop = 0.65, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

#Préparation des données 
variable_a_tester_xg <- c("Age","minJ","Apparences","But","PasseDecisive","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")
recipe_xg <- recipe(Note ~ ., data = data_train) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_predictors())

xgb_model <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf <- workflow() |>
  add_recipe(recipe_xg) |>
  add_model(xgb_model)

play_samples_cv <- vfold_cv(data_train,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold <- xgb_wf |>
  tune_grid(resamples=play_samples_cv,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold |> autoplot()

best_par <- xgb_3fold |>
  select_best()

final_xgb <- xgb_wf |> 
  finalize_workflow(best_par) |>
  fit(data = data_train)

pred <- final_xgb |>
  predict(new_data=data_test)


data_test_fin <- data_test |> select(Note)
data_test_fin_2 <- cbind(pred, data_test_fin)

data_test_fin_2$Difference <- data_test_fin_2$Note - data_test_fin_2$.pred
data_test_fin_2$DifferenceAbs <- abs(data_test_fin_2$Note - data_test_fin_2$.pred)



# Calculer la médiane et les intervalles de confiance
median_diff <- median(data_test_fin_2$Difference)
ci_low <- quantile(data_test_fin_2$Difference, 0.025)
ci_high <- quantile(data_test_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot <- ggplot(data_test_fin_2, aes(x = rownames(data_test_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot

R2_tot_xg <- 1 - sum((data_test_fin_2$Note - data_test_fin_2$.pred)^2) / sum((data_test_fin_2$Note - mean(data_test_fin_2$Note))^2)
RMSE_tot_xg <- sqrt(mean((data_test_fin_2$Note - data_test_fin_2$.pred)^2))
erreur_moy_abs_tot_xg <- mean(data_test_fin_2$DifferenceAbs)

Nous avons tester pour chaque postes et pour la population totale XGboost on va venir faire un tableau recap prenant :

  • Le R2 par model

  • Le RMSE

  • La différence absolu moyenne = Moyenne ( | Note - note.pred| )

b) Random Forest

Total

library(ranger)
## Warning: le package 'ranger' a été compilé avec la version R 4.3.2
library(caret)
## Le chargement a nécessité le package : lattice
## 
## Attachement du package : 'caret'
## Les objets suivants sont masqués depuis 'package:yardstick':
## 
##     precision, recall, sensitivity, specificity
## L'objet suivant est masqué depuis 'package:purrr':
## 
##     lift
library(tidymodels)
library(ggplot2)

# Définir la graine pour la reproductibilité
set.seed(123)

# Séparation des données en ensemble d'entraînement et ensemble de test
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

# Supprimer les colonnes non pertinentes
data_train <- subset(data_train, select = -c(nom, Poste, Club, Annee, Poste_global))
data_train <- na.omit(data_train, cols = "Note")

data_test <- subset(data_test, select = -c(nom, Poste, Club, Annee, Poste_global))
data_test <- na.omit(data_test, cols = "Note")

# Recherche du meilleur mtry par validation croisée
pargrid_regression <- expand.grid(mtry = 1:16,
                                  splitrule = "variance",
                                  min.node.size = 1)

# Définir le schéma de validation croisée
ctrl <- trainControl(method = "cv", number = 5)

# Entraîner le modèle avec validation croisée
rf_model <- train(Note ~ ., 
                  data = data_train, 
                  method = "ranger", 
                  trControl = ctrl, 
                  tuneGrid = pargrid_regression)

# Afficher les résultats de la validation croisée
print(rf_model)
## Random Forest 
## 
## 30893 samples
##    16 predictor
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold) 
## Summary of sample sizes: 24713, 24714, 24716, 24714, 24715 
## Resampling results across tuning parameters:
## 
##   mtry  RMSE       Rsquared   MAE      
##    1    0.2898311  0.3639588  0.1591514
##    2    0.2812521  0.3872400  0.1542763
##    3    0.2800405  0.3893315  0.1542354
##    4    0.2803632  0.3869277  0.1547424
##    5    0.2805950  0.3857341  0.1551736
##    6    0.2814707  0.3820567  0.1556716
##    7    0.2818369  0.3806745  0.1562016
##    8    0.2828080  0.3769252  0.1568625
##    9    0.2831305  0.3758347  0.1571625
##   10    0.2840594  0.3723600  0.1578052
##   11    0.2846480  0.3703208  0.1582382
##   12    0.2852635  0.3681882  0.1586375
##   13    0.2857505  0.3664686  0.1589823
##   14    0.2862665  0.3647728  0.1593214
##   15    0.2867487  0.3629821  0.1597621
##   16    0.2873331  0.3610972  0.1601367
## 
## Tuning parameter 'splitrule' was held constant at a value of variance
## 
## Tuning parameter 'min.node.size' was held constant at a value of 1
## RMSE was used to select the optimal model using the smallest value.
## The final values used for the model were mtry = 3, splitrule = variance
##  and min.node.size = 1.
# Tracer la performance en fonction de mtry
ggplot(rf_model$results) +
  geom_line(aes(x = mtry, y = RMSE, color = "RMSE"), linetype = "solid") +
  geom_line(aes(x = mtry, y = Rsquared, color = "Rsquared"), linetype = "dashed") +
  labs(title = "Performance du Random Forest en fonction de mtry",
       x = "mtry",
       y = "Métrique") +
  scale_color_manual(values = c("blue", "red"),
                     labels = c("RMSE", "Rsquared"))

# Sélectionner le modèle optimal
best_mtry <- rf_model$bestTune$mtry

# Entraîner le modèle final avec le meilleur mtry
final_rf_model <- ranger(Note ~ ., 
                         data = data_train, 
                         mtry = best_mtry)

# Prédiction sur l'ensemble de test
predictions <- predict(final_rf_model, data = data_test)$predictions


# Calculer d'autres métriques d'évaluation
RMSE_tot_rf <- sqrt(mean((data_test$Note - predictions)^2))
R2_tot_rf <- 1 - sum((data_test$Note - predictions)^2) / sum((data_test$Note - mean(data_test$Note))^2)
erreur_moy_abs_tot_rf <- mean(abs(data_test$Note - predictions))

# Créer le dataframe de comparaison
comparison_rf <- data.frame(
  Actual = data_test$Note,
  Predicted = predictions,
  Residuals = data_test$Note - predictions,
  DifferenceAbs = abs(data_test$Note - predictions)
  
)



# Calculer la médiane et les intervalles de confiance
median_diff <- median(comparison_rf$Residuals)
ci_low <- quantile(comparison_rf$Residuals, 0.025)
ci_high <- quantile(comparison_rf$Residuals, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
ggplot(comparison_rf, aes(x = rownames(comparison_rf), y = Residuals, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5) + 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5) +   labs(title = "Prédiction Random Forest sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

c) Régression linéaire

Total

#Division en jeu d'entraienement 

# Division en jeu d'entraînement
set.seed(123)
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

# Préparation des données
data_train <- subset(data_train, select = -c(nom, Poste, Club, Annee, Poste_global))
data_train <- na.omit(data_train, cols = "Note")

data_test <- subset(data_test, select = -c(nom, Poste, Club, Annee, Poste_global))
data_test <- na.omit(data_test, cols = "Note")

# Entraînement du modèle de régression linéaire
lm_fit <- lm(Note ~ ., data = data_train)

# Prédictions sur l'ensemble de test
predictions_lin <- predict(lm_fit, newdata = data_test)
actual_values <- data_test$Note  

# Création du dataframe de comparaison
comparison_lin <- data.frame(
  Actual = actual_values,
  Predicted = predictions_lin,
  Residuals = actual_values - predictions_lin
)

# Calcul des statistiques d'évaluation
median_diff <- median(comparison_lin$Actual - comparison_lin$Predicted)
ci_low <- quantile(comparison_lin$Actual - comparison_lin$Predicted, 0.025)
ci_high <- quantile(comparison_lin$Actual - comparison_lin$Predicted, 0.975)

# Création du plot ggplot2
ggplot(comparison_lin, aes(x = rownames(comparison_lin), y = Residuals, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction Régression Linéaire sur la population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

# Calcul des métriques d'évaluation
RMSE_reg_tot <- sqrt(mean(comparison_lin$Residuals^2))
R2_reg_tot <- 1 - sum((comparison_lin$Actual - comparison_lin$Predicted)^2) / sum((comparison_lin$Actual - mean(comparison_lin$Predicted))^2)
erreur_moy_abs_tot_reg <- mean(abs(comparison_lin$Actual - comparison_lin$Predicted))

Attaquant

# Division en jeu d'entraînement
set.seed(123)
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

# Filtrage pour les attaquants
all_data_poste_train <- data_train |> filter(Poste_global == "Attaquant")
all_data_poste_train <- subset(all_data_poste_train, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_poste_train <- na.omit(all_data_poste_train, cols = "Note")

all_data_poste_test <- data_test |> filter(Poste_global == "Attaquant")
all_data_poste_test <- subset(all_data_poste_test, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_poste_test <- na.omit(all_data_poste_test, cols = "Note")

# Entraînement du modèle de régression linéaire
lm_fit_att <- lm(Note ~ ., data = all_data_poste_train)

# Prédictions sur l'ensemble de test
predictions_poste_lin_att <- predict(lm_fit_att, newdata = all_data_poste_test)
actual_values <- all_data_poste_test$Note  

# Création du dataframe de comparaison
comparison_poste_lin_att <- data.frame(
  Actual = actual_values,
  Predicted = predictions_poste_lin_att,
  Residuals = actual_values - predictions_poste_lin_att
)

# Calcul des statistiques d'évaluation
median_diff <- median(comparison_poste_lin_att$Actual - comparison_poste_lin_att$Predicted)
ci_low <- quantile(comparison_poste_lin_att$Actual - comparison_poste_lin_att$Predicted, 0.025)
ci_high <- quantile(comparison_poste_lin_att$Actual - comparison_poste_lin_att$Predicted, 0.975)

# Création du plot ggplot2
ggplot(comparison_poste_lin_att, aes(x = rownames(comparison_poste_lin_att), y = Residuals, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction Régression Linéaire sur la population des attaquants",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

# Calcul des métriques d'évaluation
RMSE_reg_att <- sqrt(mean(comparison_poste_lin_att$Residuals^2))
R2_reg_att <- 1 - sum((comparison_poste_lin_att$Actual - comparison_poste_lin_att$Predicted)^2) / sum((comparison_poste_lin_att$Actual - mean(comparison_poste_lin_att$Predicted))^2)
erreur_moy_abs_att_reg <- mean(abs(comparison_poste_lin_att$Actual - comparison_poste_lin_att$Predicted))

d) Régression Lasso

Total

# Définition du modèle LASSO
# Division en jeu d'entraînement
set.seed(123)
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train_2 <- training(data_split)
data_test_2 <- testing(data_split)

# Préparation des données
data_train_3 <- subset(data_train_2, select = -c(nom, Poste, Club, Annee, Poste_global))
data_train <- na.omit(data_train_3, cols = "Note")

data_test_3 <- subset(data_test_2, select = -c(nom, Poste, Club, Annee, Poste_global))
data_test <- na.omit(data_test_3, cols = "Note")

lasso_model <- linear_reg() |>
  set_engine("glmnet") |>
  set_mode("regression") |>
  set_args(penalty = tune(), mixture = 1)

# Création du workflow pour le LASSO
lasso_wf <- workflow() |> 
  add_model(lasso_model) |> 
  add_formula(Note ~ .)

# Création des folds pour la validation croisée
folds <- vfold_cv(data_train, v = 3, strata = "Note")

# Définition de la grille de recherche du paramètre lambda
lambda_grid <- grid_regular(penalty(range = c(-5, 2)), levels = 100)

# Validation croisée pour le LASSO
lasso_cv <- lasso_wf |> 
  tune_grid(resamples = folds, grid = lambda_grid, metrics = metric_set(rsq))
## Warning: le package 'glmnet' a été compilé avec la version R 4.3.2
## → A | warning: A correlation computation is required, but `estimate` is constant and has 0 standard deviation, resulting in a divide by 0 error. `NA` will be returned.
## 
There were issues with some computations   A: x1

There were issues with some computations   A: x2

There were issues with some computations   A: x3

There were issues with some computations   A: x3
# Collecte des métriques
res <- lasso_cv |> collect_metrics()



lasso_cv |> 
  collect_metrics() |> 
  ggplot(aes(penalty, mean, color = .metric)) +
  geom_errorbar(aes(
    ymin = mean - std_err,
    ymax = mean + std_err
  ),
  alpha = 0.5
  ) +
  geom_line(size = 1.5) +
  facet_wrap(~.metric, scales = "free", nrow = 2) +
  scale_x_log10() +
  theme(legend.position = "none")
## Warning: Removed 41 rows containing missing values (`geom_line()`).

# Sélection du meilleur lambda
best_rsq <- lasso_cv |> select_best(metric = "rsq")
best_rsq$penalty
## [1] 1e-05
# Finalisation du workflow avec le meilleur lambda
final_wf <- finalize_workflow(lasso_wf, best_rsq)
print(final_wf)
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Formula
## Model: linear_reg()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## Note ~ .
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Linear Regression Model Specification (regression)
## 
## Main Arguments:
##   penalty = 1e-05
##   mixture = 1
## 
## Computational engine: glmnet
# Entraînement du modèle LASSO avec le meilleur lambda sur l'ensemble des données d'entraînement
final_lasso <- final_wf |> fit(data_train)

# Tidy sur le modèle LASSO
final_lasso |> tidy()
## # A tibble: 17 × 3
##    term           estimate penalty
##    <chr>             <dbl>   <dbl>
##  1 (Intercept)    6.57     0.00001
##  2 Age           -0.000530 0.00001
##  3 minJ           0.000215 0.00001
##  4 Apparences    -0.0162   0.00001
##  5 But            0.0141   0.00001
##  6 PasseDecisive  0.00709  0.00001
##  7 Tirs           0.0783   0.00001
##  8 Dribbles      -0.0328   0.00001
##  9 Passes_perc    0.00199  0.00001
## 10 moy_passes     0.184    0.00001
## 11 centre_perc    0        0.00001
## 12 interception   0.0328   0.00001
## 13 tacle          0.0921   0.00001
## 14 tirsBloques    0.0675   0.00001
## 15 driblesSubis  -0.153    0.00001
## 16 fautes        -0.0961   0.00001
## 17 TaclesRecu     0.0448   0.00001
# Prédictions avec le modèle LASSO sur l'ensemble de test
predictions_lasso <- predict(final_lasso, new_data = data_test)
comparison_lasso <- data.frame(Actual = data_test$Note, Predicted = predictions_lasso)
residuals_lasso <- actual_values - predictions_lasso

comparison_lasso <- data.frame(
  Actual = data_test$Note,
  Predicted = predictions_lasso,
  Residuals = residuals_lasso
)
colnames(comparison_lasso) <- c("Actual", "Predicted", "Residuals")

# Calcul des différences et des erreurs absolues
comparison_lasso$Difference <- comparison_lasso$Actual - comparison_lasso$Predicted
comparison_lasso$DifferenceAbs <- abs(comparison_lasso$Actual - comparison_lasso$Predicted)

# Calcul de la médiane et des intervalles de confiance
median_diff <- median(comparison_lasso$Difference)
ci_low <- quantile(comparison_lasso$Difference, 0.025)
ci_high <- quantile(comparison_lasso$Difference, 0.975)

# Création du plot ggplot2
ggplot(comparison_lasso, aes(x = rownames(comparison_lasso), y = Residuals, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction Régression LASSO sur la population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

# Calcul des métriques d'évaluation
RMSE_regLASSO_tot <- sqrt(mean(comparison_lasso$Residuals^2))
R2_regLASSO_tot <- 1 - sum((comparison_lasso$Actual - comparison_lasso$Predicted)^2) / sum((comparison_lasso$Actual - mean(comparison_lasso$Predicted))^2)
erreur_moy_abs_tot_regLASSO <- mean(comparison_lasso$DifferenceAbs)

Attaquant

set.seed(123)
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

# Filtrage pour les attaquants
all_data_poste_train <- data_train |> filter(Poste_global == "Attaquant")
all_data_poste_train <- subset(all_data_poste_train, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_poste_train <- na.omit(all_data_poste_train, cols = "Note")

all_data_poste_test <- data_test |> filter(Poste_global == "Attaquant")
all_data_poste_test <- subset(all_data_poste_test, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_poste_test <- na.omit(all_data_poste_test, cols = "Note")


lasso_att_model <- linear_reg() |>
  set_engine("glmnet") |>
  set_mode("regression") |>
  set_args(penalty = tune(), mixture = 1)

lasso_att_wf <- workflow() |> 
  add_model(lasso_att_model) |> 
  add_formula(Note ~ .)

folds <- vfold_cv(all_data_poste_train, v=5, strata = "Note")

lambda_grid <- grid_regular(penalty(range = c(-5, 2)), levels = 100)
lambda_grid$penalty
##   [1] 1.000000e-05 1.176812e-05 1.384886e-05 1.629751e-05 1.917910e-05
##   [6] 2.257020e-05 2.656088e-05 3.125716e-05 3.678380e-05 4.328761e-05
##  [11] 5.094138e-05 5.994843e-05 7.054802e-05 8.302176e-05 9.770100e-05
##  [16] 1.149757e-04 1.353048e-04 1.592283e-04 1.873817e-04 2.205131e-04
##  [21] 2.595024e-04 3.053856e-04 3.593814e-04 4.229243e-04 4.977024e-04
##  [26] 5.857021e-04 6.892612e-04 8.111308e-04 9.545485e-04 1.123324e-03
##  [31] 1.321941e-03 1.555676e-03 1.830738e-03 2.154435e-03 2.535364e-03
##  [36] 2.983647e-03 3.511192e-03 4.132012e-03 4.862602e-03 5.722368e-03
##  [41] 6.734151e-03 7.924829e-03 9.326033e-03 1.097499e-02 1.291550e-02
##  [46] 1.519911e-02 1.788650e-02 2.104904e-02 2.477076e-02 2.915053e-02
##  [51] 3.430469e-02 4.037017e-02 4.750810e-02 5.590810e-02 6.579332e-02
##  [56] 7.742637e-02 9.111628e-02 1.072267e-01 1.261857e-01 1.484968e-01
##  [61] 1.747528e-01 2.056512e-01 2.420128e-01 2.848036e-01 3.351603e-01
##  [66] 3.944206e-01 4.641589e-01 5.462277e-01 6.428073e-01 7.564633e-01
##  [71] 8.902151e-01 1.047616e+00 1.232847e+00 1.450829e+00 1.707353e+00
##  [76] 2.009233e+00 2.364489e+00 2.782559e+00 3.274549e+00 3.853529e+00
##  [81] 4.534879e+00 5.336699e+00 6.280291e+00 7.390722e+00 8.697490e+00
##  [86] 1.023531e+01 1.204504e+01 1.417474e+01 1.668101e+01 1.963041e+01
##  [91] 2.310130e+01 2.718588e+01 3.199267e+01 3.764936e+01 4.430621e+01
##  [96] 5.214008e+01 6.135907e+01 7.220809e+01 8.497534e+01 1.000000e+02
lasso_att_cv <- lasso_att_wf |> 
  tune_grid(resamples = folds, grid = lambda_grid, metrics = metric_set(rsq))
## → A | warning: A correlation computation is required, but `estimate` is constant and has 0 standard deviation, resulting in a divide by 0 error. `NA` will be returned.
## 
There were issues with some computations   A: x1

There were issues with some computations   A: x2

There were issues with some computations   A: x3

There were issues with some computations   A: x4

There were issues with some computations   A: x5

There were issues with some computations   A: x5
res <- lasso_att_cv |>
  collect_metrics()


res$mean
##   [1] 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992
##   [8] 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992
##  [15] 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992 0.4813992
##  [22] 0.4813992 0.4813997 0.4813735 0.4813497 0.4813138 0.4812656 0.4811917
##  [29] 0.4811141 0.4810125 0.4808627 0.4806598 0.4803844 0.4800082 0.4794950
##  [36] 0.4788856 0.4781218 0.4770626 0.4756292 0.4738504 0.4716967 0.4688205
##  [43] 0.4651215 0.4602613 0.4544962 0.4513691 0.4496098 0.4488263 0.4477623
##  [50] 0.4462043 0.4441430 0.4423652 0.4413772 0.4408349 0.4399883 0.4384955
##  [57] 0.4356712 0.4297337 0.4170844 0.3976582 0.3443552 0.3526982       NaN
##  [64]       NaN       NaN       NaN       NaN       NaN       NaN       NaN
##  [71]       NaN       NaN       NaN       NaN       NaN       NaN       NaN
##  [78]       NaN       NaN       NaN       NaN       NaN       NaN       NaN
##  [85]       NaN       NaN       NaN       NaN       NaN       NaN       NaN
##  [92]       NaN       NaN       NaN       NaN       NaN       NaN       NaN
##  [99]       NaN       NaN
lasso_att_cv |>
  collect_metrics() |>
  ggplot(aes(penalty, mean, color = .metric)) +
  geom_errorbar(aes(
    ymin = mean - std_err,
    ymax = mean + std_err
  ),
  alpha = 0.5
  ) +
  geom_line(size = 1.5) +
  facet_wrap(~.metric, scales = "free", nrow = 2) +
  scale_x_log10() +
  theme(legend.position = "none")
## Warning: Removed 38 rows containing missing values (`geom_line()`).

# On sélectionne le lambda qui minimise le risque estimé par VC

best_rsq <- lasso_att_cv |>
  select_best(metric="rsq")
best_rsq$penalty
## [1] 0.0003593814
# On relance (entraine) la régression lasso_att avec ce "meilleur" lambda sur l'ensemble du jeu de données pour obtenir le "meilleur" prédicteur lasso_att

final_wf <- finalize_workflow(lasso_att_wf,best_rsq)
print(final_wf)
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Formula
## Model: linear_reg()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## Note ~ .
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Linear Regression Model Specification (regression)
## 
## Main Arguments:
##   penalty = 0.000359381366380463
##   mixture = 1
## 
## Computational engine: glmnet
final_lasso_att <- final_wf |>
  fit(all_data_poste_train)

final_lasso_att |> tidy()
## # A tibble: 17 × 3
##    term            estimate  penalty
##    <chr>              <dbl>    <dbl>
##  1 (Intercept)    6.43      0.000359
##  2 Age           -0.00104   0.000359
##  3 minJ          -0.0000546 0.000359
##  4 Apparences    -0.00318   0.000359
##  5 But            0.0224    0.000359
##  6 PasseDecisive  0.0144    0.000359
##  7 Tirs           0.102     0.000359
##  8 Dribbles      -0.00911   0.000359
##  9 Passes_perc    0.00131   0.000359
## 10 moy_passes     0.236     0.000359
## 11 centre_perc    0.000444  0.000359
## 12 interception   0.0710    0.000359
## 13 tacle          0.0990    0.000359
## 14 tirsBloques    0.175     0.000359
## 15 driblesSubis  -0.116     0.000359
## 16 fautes        -0.0320    0.000359
## 17 TaclesRecu     0.0565    0.000359
predictions_poste_lasso_att <- predict(final_lasso_att, new_data = all_data_poste_test)
comparison_poste_lasso_att <- data.frame(Actual = all_data_poste_test$Note, Predicted = predictions_poste_lasso_att)
residuals_lasso_att <- actual_values - predictions_poste_lasso_att

comparison_poste_lasso_att <- data.frame(
  Actual = actual_values,
  Predicted = predictions_poste_lasso_att,
  Residuals = residuals_lasso_att
)
colnames(comparison_poste_lasso_att) <- c("Actual", "Predicted", "Residuals")

comparison_poste_lasso_att$Difference <- comparison_poste_lasso_att$Actual - comparison_poste_lasso_att$Predicted
comparison_poste_lasso_att$DifferenceAbs <- abs(comparison_poste_lasso_att$Actual - comparison_poste_lasso_att$Predicted)




# Calculer la médiane et les intervalles de confiance
median_diff <- median(comparison_poste_lasso_att$Difference)
ci_low <- quantile(comparison_poste_lasso_att$Difference, 0.025)
ci_high <- quantile(comparison_poste_lasso_att$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
ggplot(comparison_poste_lasso_att, aes(x = rownames(comparison_poste_lasso_att), y = Difference, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction Regréssion LASSO sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

RMSE_regLASSO_att <- sqrt(mean(comparison_poste_lasso_att$Residuals^2))
R2_regLASSO_att <- 1 - sum((comparison_poste_lasso_att$Actual - comparison_poste_lasso_att$Predicted)^2) / sum((comparison_poste_lasso_att$Actual - mean(comparison_poste_lasso_att$Predicted))^2)
erreur_moy_abs_att_regLASSO <- mean(comparison_poste_lasso_att$DifferenceAbs)

e) Régression Ridge

Total

# Régression RIDGE avec validation croisée
set.seed(123)
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train_2 <- training(data_split)
data_test_2 <- testing(data_split)

# Préparation des données
data_train_3 <- subset(data_train_2, select = -c(nom, Poste, Club, Annee, Poste_global))
data_train <- na.omit(data_train_3, cols = "Note")

data_test_3 <- subset(data_test_2, select = -c(nom, Poste, Club, Annee, Poste_global))
data_test <- na.omit(data_test_3, cols = "Note")

ridge_model <- linear_reg() |>
  set_engine("glmnet") |>
  set_mode("regression") |>
  set_args(penalty = tune(), mixture = 0)

ridge_wf <- workflow() |> 
  add_model(ridge_model) |> 
  add_formula(Note ~ .)


ridge_cv <- ridge_wf |> 
  tune_grid(resamples = folds, grid = lambda_grid, metrics = metric_set(rsq))


res <- ridge_cv |>
  collect_metrics()


res$mean
##   [1] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##   [8] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [15] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [22] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [29] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [36] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [43] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801518 0.4797687
##  [50] 0.4792747 0.4786499 0.4778652 0.4768917 0.4756768 0.4741915 0.4724133
##  [57] 0.4703052 0.4678368 0.4649698 0.4616944 0.4580379 0.4540111 0.4496171
##  [64] 0.4449151 0.4400067 0.4349495 0.4297750 0.4245896 0.4195182 0.4146108
##  [71] 0.4098730 0.4053847 0.4012316 0.3974108 0.3938827 0.3906772 0.3878275
##  [78] 0.3852964 0.3830308 0.3810230 0.3792840 0.3777725 0.3764430 0.3752836
##  [85] 0.3742941 0.3734459 0.3727069 0.3720683 0.3715285 0.3710684 0.3706695
##  [92] 0.3703266 0.3700381 0.3697931 0.3695814 0.3693998 0.3692481 0.3691188
##  [99] 0.3690071 0.3689116
ridge_cv |>
  collect_metrics() |>
  ggplot(aes(penalty, mean, color = .metric)) +
  geom_errorbar(aes(
    ymin = mean - std_err,
    ymax = mean + std_err
  ),
  alpha = 0.5
  ) +
  geom_line(size = 1.5) +
  facet_wrap(~.metric, scales = "free", nrow = 2) +
  scale_x_log10() +
  theme(legend.position = "none")

# On sélectionne le lambda qui minimise le risque estimé par VC

best_rsq <- ridge_cv |>
  select_best(metric="rsq")
best_rsq$penalty
## [1] 1e-05
# On relance (entraine) la régression ridge avec ce "meilleur" lambda sur l'ensemble du jeu de données pour obtenir le "meilleur" prédicteur ridge

final_wf <- finalize_workflow(ridge_wf,best_rsq)
print(final_wf)
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Formula
## Model: linear_reg()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## Note ~ .
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Linear Regression Model Specification (regression)
## 
## Main Arguments:
##   penalty = 1e-05
##   mixture = 0
## 
## Computational engine: glmnet
final_ridge <- final_wf |>
  fit(data_train)

final_ridge |> tidy()
## # A tibble: 17 × 3
##    term           estimate penalty
##    <chr>             <dbl>   <dbl>
##  1 (Intercept)    6.55     0.00001
##  2 Age           -0.000220 0.00001
##  3 minJ           0.000142 0.00001
##  4 Apparences    -0.00944  0.00001
##  5 But            0.0132   0.00001
##  6 PasseDecisive  0.00771  0.00001
##  7 Tirs           0.0750   0.00001
##  8 Dribbles      -0.0293   0.00001
##  9 Passes_perc    0.00160  0.00001
## 10 moy_passes     0.179    0.00001
## 11 centre_perc   -0.000123 0.00001
## 12 interception   0.0432   0.00001
## 13 tacle          0.0862   0.00001
## 14 tirsBloques    0.0921   0.00001
## 15 driblesSubis  -0.142    0.00001
## 16 fautes        -0.0922   0.00001
## 17 TaclesRecu     0.0445   0.00001
predictions_ridge <- predict(final_ridge, new_data = data_test)
residuals_ridge <- actual_values - predictions_ridge

comparison_ridge <- data.frame(
  Actual = data_test$Note,
  Predicted = predictions_ridge,
  Residuals = residuals_ridge
)
colnames(comparison_ridge) <- c("Actual", "Predicted", "Residuals")

comparison_ridge$Difference <- comparison_ridge$Actual - comparison_ridge$Predicted
comparison_ridge$DifferenceAbs <- abs(comparison_ridge$Actual - comparison_ridge$Predicted)




# Calculer la médiane et les intervalles de confiance
median_diff <- median(comparison_ridge$Difference)
ci_low <- quantile(comparison_ridge$Difference, 0.025)
ci_high <- quantile(comparison_ridge$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
ggplot(comparison_ridge, aes(x = rownames(comparison_ridge), y = Residuals, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction Regréssion RIDGE sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

RMSE_regRIDGE_tot <- sqrt(mean(comparison_ridge$Residuals^2))
R2_regRIDGE_tot <- 1 - sum((comparison_ridge$Actual - comparison_ridge$Predicted)^2) / sum((comparison_ridge$Actual - mean(comparison_ridge$Predicted))^2)
erreur_moy_abs_tot_regRIDGE <- mean(comparison_ridge$DifferenceAbs)

Attaquant

set.seed(123)
data_split <- initial_split(all_data, prop = 0.8, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

# Filtrage pour les attaquants
all_data_poste_train <- data_train |> filter(Poste_global == "Attaquant")
all_data_poste_train <- subset(all_data_poste_train, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_poste_train <- na.omit(all_data_poste_train, cols = "Note")

all_data_poste_test <- data_test |> filter(Poste_global == "Attaquant")
all_data_poste_test <- subset(all_data_poste_test, select = -c(nom, Poste, Club, Annee, Poste_global))
all_data_poste_test <- na.omit(all_data_poste_test, cols = "Note")

ridge_att_model <- linear_reg() |>
  set_engine("glmnet") |>
  set_mode("regression") |>
  set_args(penalty = tune(), mixture = 0)

ridge_att_wf <- workflow() |> 
  add_model(ridge_att_model) |> 
  add_formula(Note ~ .)


ridge_att_cv <- ridge_att_wf |> 
  tune_grid(resamples = folds, grid = lambda_grid, metrics = metric_set(rsq))


res <- ridge_att_cv |>
  collect_metrics()


res$mean
##   [1] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##   [8] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [15] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [22] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [29] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [36] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563
##  [43] 0.4801563 0.4801563 0.4801563 0.4801563 0.4801563 0.4801518 0.4797687
##  [50] 0.4792747 0.4786499 0.4778652 0.4768917 0.4756768 0.4741915 0.4724133
##  [57] 0.4703052 0.4678368 0.4649698 0.4616944 0.4580379 0.4540111 0.4496171
##  [64] 0.4449151 0.4400067 0.4349495 0.4297750 0.4245896 0.4195182 0.4146108
##  [71] 0.4098730 0.4053847 0.4012316 0.3974108 0.3938827 0.3906772 0.3878275
##  [78] 0.3852964 0.3830308 0.3810230 0.3792840 0.3777725 0.3764430 0.3752836
##  [85] 0.3742941 0.3734459 0.3727069 0.3720683 0.3715285 0.3710684 0.3706695
##  [92] 0.3703266 0.3700381 0.3697931 0.3695814 0.3693998 0.3692481 0.3691188
##  [99] 0.3690071 0.3689116
ridge_att_cv |>
  collect_metrics() |>
  ggplot(aes(penalty, mean, color = .metric)) +
  geom_errorbar(aes(
    ymin = mean - std_err,
    ymax = mean + std_err
  ),
  alpha = 0.5
  ) +
  geom_line(size = 1.5) +
  facet_wrap(~.metric, scales = "free", nrow = 2) +
  scale_x_log10() +
  theme(legend.position = "none")

# On sélectionne le lambda qui minimise le risque estimé par VC

best_rsq <- ridge_att_cv |>
  select_best(metric="rsq")
best_rsq$penalty
## [1] 1e-05
# On relance (entraine) la régression ridge_att avec ce "meilleur" lambda sur l'ensemble du jeu de données pour obtenir le "meilleur" prédicteur ridge_att

final_wf <- finalize_workflow(ridge_att_wf,best_rsq)
print(final_wf)
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Formula
## Model: linear_reg()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## Note ~ .
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Linear Regression Model Specification (regression)
## 
## Main Arguments:
##   penalty = 1e-05
##   mixture = 0
## 
## Computational engine: glmnet
final_ridge_att <- final_wf |>
  fit(all_data_poste_train)

final_ridge_att |> tidy()
## # A tibble: 17 × 3
##    term            estimate penalty
##    <chr>              <dbl>   <dbl>
##  1 (Intercept)    6.44      0.00001
##  2 Age           -0.000897  0.00001
##  3 minJ          -0.0000317 0.00001
##  4 Apparences    -0.00342   0.00001
##  5 But            0.0191    0.00001
##  6 PasseDecisive  0.0152    0.00001
##  7 Tirs           0.103     0.00001
##  8 Dribbles      -0.00537   0.00001
##  9 Passes_perc    0.00123   0.00001
## 10 moy_passes     0.214     0.00001
## 11 centre_perc    0.000540  0.00001
## 12 interception   0.0646    0.00001
## 13 tacle          0.0884    0.00001
## 14 tirsBloques    0.171     0.00001
## 15 driblesSubis  -0.105     0.00001
## 16 fautes        -0.0297    0.00001
## 17 TaclesRecu     0.0530    0.00001
predictions_poste_ridge_att <- predict(final_ridge_att, new_data = all_data_poste_test)
comparison_poste_ridge_att <- data.frame(Actual = actual_values, Predicted = predictions_poste_ridge_att)
residuals_ridge_att <- actual_values - predictions_poste_ridge_att

comparison_poste_ridge_att <- data.frame(
  Actual = actual_values,
  Predicted = predictions_poste_ridge_att,
  Residuals = residuals_ridge_att
)
colnames(comparison_poste_ridge_att) <- c("Actual", "Predicted", "Residuals")

comparison_poste_ridge_att$Difference <- comparison_poste_ridge_att$Actual - comparison_poste_ridge_att$Predicted
comparison_poste_ridge_att$DifferenceAbs <- abs(comparison_poste_ridge_att$Actual - comparison_poste_ridge_att$Predicted)




# Calculer la médiane et les intervalles de confiance
median_diff <- median(comparison_poste_ridge_att$Difference)
ci_low <- quantile(comparison_poste_ridge_att$Difference, 0.025)
ci_high <- quantile(comparison_poste_ridge_att$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
ggplot(comparison_poste_ridge_att, aes(x = rownames(comparison_poste_ridge_att), y = Difference, color = Actual)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction Regréssion RIDGE sur Attaquant",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

RMSE_regRIDGE_att <- sqrt(mean(comparison_poste_ridge_att$Residuals^2))
R2_regRIDGE_att <- 1 - sum((comparison_poste_ridge_att$Actual - comparison_poste_ridge_att$Predicted)^2) / sum((comparison_poste_ridge_att$Actual - mean(comparison_poste_ridge_att$Predicted))^2)
erreur_moy_abs_att_regRIDGE <- mean(comparison_poste_ridge_att$DifferenceAbs)

g) Recap

recap <- data.frame(
  Model = c("XG_att", "XG_mil", "XG_def", "XG_gar", "XG_tot", "Reg_tot","Reg_att", "Reg_LASSO","Reg_LASSO_att", "Reg_RIDGE", "Reg_RIDGE_att", "Rf_tot"),
  R2 = c(R2_att_xg, R2_mil_xg, R2_def_xg, R2_gar_xg, R2_tot_xg, R2_reg_tot,R2_reg_att, R2_regLASSO_tot,R2_regLASSO_att, R2_regRIDGE_tot, R2_regRIDGE_att, R2_tot_rf),
  RMSE = c(RMSE_att_xg, RMSE_mil_xg, RMSE_def_xg, RMSE_gar_xg, RMSE_tot_xg, RMSE_reg_tot,RMSE_reg_att, RMSE_regLASSO_tot,RMSE_regLASSO_att, RMSE_regRIDGE_tot, RMSE_regRIDGE_att, RMSE_tot_rf),
  DifMoyAbs = c(erreur_moy_abs_att_xg, erreur_moy_abs_mil_xg, erreur_moy_abs_def_xg, erreur_moy_abs_gar_xg, erreur_moy_abs_tot_xg, erreur_moy_abs_tot_reg,erreur_moy_abs_att_reg,erreur_moy_abs_att_regLASSO, erreur_moy_abs_tot_regLASSO, erreur_moy_abs_tot_regRIDGE, erreur_moy_abs_att_regRIDGE,erreur_moy_abs_tot_rf)
)

recap <- recap %>%
  mutate_at(vars(RMSE, R2, DifMoyAbs), ~ round(., 4))

print(recap)
##            Model     R2   RMSE DifMoyAbs
## 1         XG_att 0.4680 0.2650    0.1386
## 2         XG_mil 0.4536 0.2600    0.1431
## 3         XG_def 0.3587 0.2543    0.1449
## 4         XG_gar 0.0549 0.3741    0.2524
## 5         XG_tot 0.3894 0.2837    0.1517
## 6        Reg_tot 0.3304 0.2922    0.1643
## 7        Reg_att 0.5126 0.2311    0.1285
## 8      Reg_LASSO 0.3304 0.3788    0.1284
## 9  Reg_LASSO_att 0.5130 0.2310    0.1641
## 10     Reg_RIDGE 0.3256 0.3734    0.1622
## 11 Reg_RIDGE_att 0.5118 0.2312    0.1283
## 12        Rf_tot 0.3882 0.2793    0.1541
## Afin d'éviter de relancer tout les modèles nous placons ici un récap des différent smodèles
recap <- data.frame(
  Model = c("XG_att", "XG_mil", "XG_def", "XG_gar", "XG_tot", 
            "Reg_tot", "Reg_att", "Reg_LASSO_tot", "Reg_LASSO_att", 
            "Reg_RIDGE_tot", "Reg_RIDGE_att", "Rf_tot"),
  R2 = c(0.4680, 0.4536, 0.3587, 0.0549, 0.3894, 0.3304, 
         0.5126, 0.3304, 0.5130, 0.3256, 0.5118, 0.3882),
  RMSE = c(0.2650, 0.2600, 0.2543, 0.3741, 0.2837, 0.2922, 
           0.2311, 0.3788, 0.2310, 0.3734, 0.2312, 0.2793),
  DifMoyAbs = c(0.1386, 0.1431, 0.1449, 0.2524, 0.1517, 0.1643, 
                0.1285, 0.1284, 0.1641, 0.1622, 0.1283, 0.1541)
)

library(ggplot2)
library(patchwork)
## Warning: le package 'patchwork' a été compilé avec la version R 4.3.2
# Filtrer les modèles contenant "tot" dans leur nom
recap_tot <- recap[grep("tot", recap$Model), ]

# Créer trois graphiques linéaires pour chaque variable
# R2
plot_r2 <- ggplot(recap_tot, aes(x = Model, y = R2, group = 1)) +
  geom_line() +
  labs(
       x = "Modèle",
       y = "R2") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# RMSE
plot_rmse <- ggplot(recap_tot, aes(x = Model, y = RMSE, group = 1)) +
  geom_line() +
  labs(
       x = "Modèle",
       y = "RMSE") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# DifMoyAbs
plot_dif <- ggplot(recap_tot, aes(x = Model, y = DifMoyAbs, group = 1)) +
  geom_line() +
  labs(
       x = "Modèle",
       y = "DifMoyAbs") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# Combinaison des trois graphiques
combined_plot <- plot_r2 + plot_rmse + plot_dif

# Affichage de la combinaison
combined_plot

On peut donc ici voir que XGboost produit les meilleurs résultats sur la population globale

Conclusion de sélection de modèle

Pour conclure sur la sélection de modèle, dans notre cas va s’opérer sur la population totale ( c’est à dire l’ensemble des postes de chacun des joeueurs). On veut un modèle qui soit le plus puissant possible pour prédire la note de joeueurs évoluant sur différents postes.

Toutefois nous avons identifier quelques axes d’améliorations que l’on pourrait inclure à notre modèle pour le rendre légérement plus restrictif mais plus puissant :

  • Transformer les variables pour qu’elles représentente toutes la même unités de mesures ( Dans notre jeu de données la quasi-totalités des variables sont exprimés par % sur un match ou par moyenne par matchs à l’exception de trois ( Min Joués, But et passes décisives nous allons donc essyayer de transformer cela afin d’étudier les gains de précisions de ce dernier).
#Modification des variables dans le but de les uniformiser
test_data <- all_data |> mutate(MJ_match = minJ/Apparences,
                                But_match = (But/minJ)*90,
                                PasseDe_match = (PasseDecisive/minJ)*90)


all_data_xg <- subset(test_data, select = -c(nom, Poste, Club, Annee, Poste_global, minJ, But, PasseDecisive))
all_data_xg <- na.omit(all_data_xg, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split <- initial_split(all_data_xg, prop = 0.65, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

#Préparation des données 
variable_a_tester_xg <- c("Age","MJ_match","But_match","PasseDe_match","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")

recipe_xg <- recipe(Note ~ ., data = data_train) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_numeric_predictors())

xgb_model <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf <- workflow() |>
  add_recipe(recipe_xg) |>
  add_model(xgb_model)

play_samples_cv <- vfold_cv(data_train,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold <- xgb_wf |>
  tune_grid(resamples=play_samples_cv,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold |> autoplot()

best_par <- xgb_3fold |>
  select_best()

final_xgb <- xgb_wf |> 
  finalize_workflow(best_par) |>
  fit(data = data_train)

pred <- final_xgb |>
  predict(new_data=data_test)


data_test_fin <- data_test |> select(Note)
data_test_fin_2 <- cbind(pred, data_test_fin)

data_test_fin_2$Difference <- data_test_fin_2$Note - data_test_fin_2$.pred
data_test_fin_2$DifferenceAbs <- abs(data_test_fin_2$Note - data_test_fin_2$.pred)



# Calculer la médiane et les intervalles de confiance
median_diff <- median(data_test_fin_2$Difference)
ci_low <- quantile(data_test_fin_2$Difference, 0.025)
ci_high <- quantile(data_test_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot <- ggplot(data_test_fin_2, aes(x = rownames(data_test_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot

R2_tot_xg_trans1 <- 1 - sum((data_test_fin_2$Note - data_test_fin_2$.pred)^2) / sum((data_test_fin_2$Note - mean(data_test_fin_2$Note))^2)
RMSE_tot_xg_trans1 <- sqrt(mean((data_test_fin_2$Note - data_test_fin_2$.pred)^2))
erreur_moy_abs_tot_xg_trans1 <- mean(data_test_fin_2$DifferenceAbs)
  • Si on se fixe également sur un point de vue sportif. Evaluer des joueurs qui joue très peu dans un match ou sur l’ensemble de la saison ne nous semble pas cohérent (nous décidons donc de laisser uniquement les joueurs jouant plus de 270 min sur la saison et plus de 45 min par apparitions)
#Supprimer les joueurs qui joue peu 
test_data <- all_data |> mutate(MJ_match = minJ/Apparences,
                                But_match = (But/minJ)*90,
                                PasseDe_match = (PasseDecisive/minJ)*90)
all_data_2 <- test_data |> filter(minJ >270)
all_data_2 <- all_data_2 |> filter(MJ_match > 45)

all_data_xg <- subset(all_data_2, select = -c(nom, Poste, Club, Annee, Poste_global, minJ, But, PasseDecisive))
all_data_xg <- na.omit(all_data_xg, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split <- initial_split(all_data_xg, prop = 0.65, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

#Préparation des données 
variable_a_tester_xg <- c("Age","MJ_match","But_match","PasseDe_match","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")

recipe_xg <- recipe(Note ~ ., data = data_train) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_numeric_predictors())

xgb_model <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf <- workflow() |>
  add_recipe(recipe_xg) |>
  add_model(xgb_model)

play_samples_cv <- vfold_cv(data_train,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold <- xgb_wf |>
  tune_grid(resamples=play_samples_cv,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold |> autoplot()

best_par <- xgb_3fold |>
  select_best()

final_xgb <- xgb_wf |> 
  finalize_workflow(best_par) |>
  fit(data = data_train)

pred <- final_xgb |>
  predict(new_data=data_test)


data_test_fin <- data_test |> select(Note)
data_test_fin_2 <- cbind(pred, data_test_fin)

data_test_fin_2$Difference <- data_test_fin_2$Note - data_test_fin_2$.pred
data_test_fin_2$DifferenceAbs <- abs(data_test_fin_2$Note - data_test_fin_2$.pred)



# Calculer la médiane et les intervalles de confiance
median_diff <- median(data_test_fin_2$Difference)
ci_low <- quantile(data_test_fin_2$Difference, 0.025)
ci_high <- quantile(data_test_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot <- ggplot(data_test_fin_2, aes(x = rownames(data_test_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot

R2_tot_xg_trans2 <- 1 - sum((data_test_fin_2$Note - data_test_fin_2$.pred)^2) / sum((data_test_fin_2$Note - mean(data_test_fin_2$Note))^2)
RMSE_tot_xg_trans2 <- sqrt(mean((data_test_fin_2$Note - data_test_fin_2$.pred)^2))
erreur_moy_abs_tot_xg_trans2 <- mean(data_test_fin_2$DifferenceAbs)
  • Enfin, on voit que la grande majorité des joueurs ont des notes compris entre 6 et 8 et on voit sur les graphes associés à chaque modèles que l’on a beaucoup de mal à prédire la performance de joueurs ayant des notes un peu atypiques. On décide donc de conserver uniquement les joeueurs avec une notes comprises entre 6 et 8
#Ajouter un filtre des notes pour garder une grand epartie de la popuation mais exclure les cas les plus extrêmes
test_data <- all_data |> mutate(MJ_match = minJ/Apparences,
                                But_match = (But/minJ)*90,
                                PasseDe_match = (PasseDecisive/minJ)*90)
all_data_2 <- test_data |> filter(minJ >270)
all_data_2 <- all_data_2 |> filter(MJ_match > 45)
all_data_3 <- all_data_2 |> filter(Note >= 6)
all_data_4 <- all_data_3 |> filter(Note <= 8)


all_data_xg <- subset(all_data_2, select = -c(nom, Poste, Club, Annee, Poste_global, minJ, But, PasseDecisive))
all_data_xg <- na.omit(all_data_xg, cols = "Note")

#Diviser en entrainement et test
set.seed(123)
data_split <- initial_split(all_data_xg, prop = 0.65, strata = Note)
data_train <- training(data_split)
data_test <- testing(data_split)

#Préparation des données 
variable_a_tester_xg <- c("Age","MJ_match","But_match","PasseDe_match","Tirs","Dribbles","Passes_perc","moy_passes","centre_perc","interception","tacle","tirsBloques","driblesSubis","fautes","TaclesRecu")

recipe_xg <- recipe(Note ~ ., data = data_train) |>
  update_role(all_of(variable_a_tester_xg), new_role = "predictor") |>
  step_normalize(all_numeric_predictors())

xgb_model <-
  boost_tree(
    trees = 1000,
    stop_iter=20,
    min_n = 1,
    tree_depth = tune(),
    learn_rate = tune()
  ) |>
  set_mode("regression") |>
  set_engine("xgboost")

xgb_wf <- workflow() |>
  add_recipe(recipe_xg) |>
  add_model(xgb_model)

play_samples_cv <- vfold_cv(data_train,v=3,repeats=1,strata="Note")

xgb_grid <- expand.grid(tree_depth=c(1,2,3,4,5),learn_rate=c(0.0205,0.0210, 0.215,0.220))

xgb_3fold <- xgb_wf |>
  tune_grid(resamples=play_samples_cv,grid=xgb_grid,
            metrics=metric_set(mae))

xgb_3fold |> autoplot()

best_par <- xgb_3fold |>
  select_best()

final_xgb <- xgb_wf |> 
  finalize_workflow(best_par) |>
  fit(data = data_train)

pred <- final_xgb |>
  predict(new_data=data_test)


data_test_fin <- data_test |> select(Note)
data_test_fin_2 <- cbind(pred, data_test_fin)

data_test_fin_2$Difference <- data_test_fin_2$Note - data_test_fin_2$.pred
data_test_fin_2$DifferenceAbs <- abs(data_test_fin_2$Note - data_test_fin_2$.pred)



# Calculer la médiane et les intervalles de confiance
median_diff <- median(data_test_fin_2$Difference)
ci_low <- quantile(data_test_fin_2$Difference, 0.025)
ci_high <- quantile(data_test_fin_2$Difference, 0.975)

# Créer le plot ggplot2 avec médiane et intervalles de confiance
gg_plot <- ggplot(data_test_fin_2, aes(x = rownames(data_test_fin_2), y = Difference, color = Note)) +
  geom_point() +
  geom_hline(yintercept = median_diff, linetype = "dashed", color = "black", size = 1) +
  geom_hline(yintercept = ci_low, linetype = "dashed", color = "black", size = 0.5)+ 
  geom_hline(yintercept = ci_high, linetype = "dashed", color = "black", size = 0.5)+ 
  labs(title = "Prédiction XGboost sur population",
       x = "Individu",
       y = "Différence") +
  scale_colour_gradientn(colours = terrain.colors(10)) +
  theme_classic() 

gg_plot

R2_tot_xg_trans3 <- 1 - sum((data_test_fin_2$Note - data_test_fin_2$.pred)^2) / sum((data_test_fin_2$Note - mean(data_test_fin_2$Note))^2)
RMSE_tot_xg_trans3 <- sqrt(mean((data_test_fin_2$Note - data_test_fin_2$.pred)^2))
erreur_moy_abs_tot_xg_trans3 <- mean(data_test_fin_2$DifferenceAbs)
#Amélioration de modèle 
df_recap_xg <- data.frame(
  Model = c("Xg_tot", "Xg_tot_par_match", "Xg_tot_par_match_tpsJeu", "Xg_tot_par_match_tpsJeu_Note6_8"),
  R2 = c(R2_tot_xg, R2_tot_xg_trans1, R2_tot_xg_trans2, R2_tot_xg_trans3),
  RMSE = c(RMSE_tot_xg, RMSE_tot_xg_trans1, RMSE_tot_xg_trans2, RMSE_tot_xg_trans3),
  DiffAbsMoy = c(erreur_moy_abs_tot_xg, erreur_moy_abs_tot_xg_trans1, erreur_moy_abs_tot_xg_trans2, erreur_moy_abs_tot_xg_trans3)
)

plot_r2 <- ggplot(df_recap_xg, aes(x = Model, y = R2, group = 1)) +
  geom_line() +
  labs(
       x = "Modèle",
       y = "R2") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# RMSE
plot_rmse <- ggplot(df_recap_xg, aes(x = Model, y = RMSE, group = 1)) +
  geom_line() +
  labs(
       x = "Modèle",
       y = "RMSE") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# DifMoyAbs
plot_dif <- ggplot(df_recap_xg, aes(x = Model, y = DiffAbsMoy, group = 1)) +
  geom_line() +
  labs(
       x = "Modèle",
       y = "DifMoyAbs") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# Combinaison des trois graphiques
combined_plot <- plot_r2 + plot_rmse + plot_dif

# Affichage de la combinaison
combined_plot

Pour conclure, le fil du rouge de ce projet à été d’utiliser les différents modèles de Machine learning vue en cours dans le but de répondre à une problématique (dans notre cas un problème de régression). En se basant sur 3 indicateurs de performances des modèles de régression (R2, RMSE et et diffAbsMoy, nous avons essayer d’estimer au mieux les notes de joueurs à partir d’un ensemble de variables). L’ensemble des modèles à été FineTuner par validation croisée pour sélectionner les meilleurs paramètres pour chacun des modèles.

Enfin, après sélection du modèle le plus adapté (ici XGboost). Nous avons essayé d’améliorer la prédiction de notre modèle en ajoutant des éléments restrictifs sur nos données (dans la mesure du raisonnables bien sûr).