From bd0a5b9f1285ada6f9c13c444cabf3185abf9d1a Mon Sep 17 00:00:00 2001 From: Marilyne HU <marilyne.hu@student-cs.fr> Date: Tue, 1 Apr 2025 08:40:24 +0200 Subject: [PATCH] add files --- README.md | 92 +---------------- model_xgboost.py | 255 +++++++++++++++++++++++++++++++++++++++++++++++ utils_graph.py | 119 ++++++++++++++++++++++ 3 files changed, 375 insertions(+), 91 deletions(-) create mode 100644 model_xgboost.py create mode 100644 utils_graph.py diff --git a/README.md b/README.md index 993398b..3a4763d 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,3 @@ # Class_python - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab-student.centralesupelec.fr/marilyne.hu/class_python.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab-student.centralesupelec.fr/marilyne.hu/class_python/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +Ce répertoire concentre l'ensemble des fonctions qui me serait utile pour la suite de l'alternance, il est en cours de conception donc des changements peuvent souvent être apporter. \ No newline at end of file diff --git a/model_xgboost.py b/model_xgboost.py new file mode 100644 index 0000000..539db79 --- /dev/null +++ b/model_xgboost.py @@ -0,0 +1,255 @@ +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import seaborn as sns +import xgboost as xgb +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import LabelEncoder +from sklearn.metrics import accuracy_score, classification_report, balanced_accuracy_score, roc_auc_score, precision_recall_curve, auc, confusion_matrix +import json +from sklearn.model_selection import GridSearchCV +from sklearn.preprocessing import StandardScaler +import shap +from tqdm import tqdm + +def shorten_cfa_name(name): + if len(name) > 30: + # Trouver le premier espace au milieu du texte + words = name.split() + mid = len(words) // 2 + return " ".join(words[:mid]) + "\n" + " ".join(words[mid:]) + return name + +class XGBModel: + def __init__(self, X, y, objective, eval_metric, test_size=0.15, random_state=42): + + self.X = X + self.y = y + self.test_size = test_size + self.random_state = random_state + + self.X_train, self.X_test, self.y_train, self.y_test = train_test_split( + X, y, test_size=self.test_size, random_state=self.random_state, stratify=y + ) + + neg, pos = np.bincount(self.y_train) + self.class_ratio = neg / pos + + self.objective = objective + self.eval_metric = eval_metric + + def corr_plot(self) : + + corr_matrix = self.X.corr() + # On garde uniquement la moitié inférieure pour éviter les doublons + mask = np.tril(np.ones(corr_matrix.shape), k=-1).astype(bool) + corr_pairs = corr_matrix.where(mask) + + # On sélectionne uniquement les corrélations égales à 1 (ou très proches de 1 à cause de la précision numérique) + correlated_vars = corr_pairs.stack().reset_index() + correlated_vars.columns = ['Variable_1', 'Variable_2', 'Correlation'] + + # On filtre les corrélations parfaites + perfect_corr = correlated_vars[correlated_vars['Correlation'] == 1.0] + + print(perfect_corr) + + fig , ax = plt.subplots(figsize = (30,20)) + corr_matrix = self.X.corr() + sns.heatmap(corr_matrix, annot=False) + plt.show() + + def grid_search(self, objective = "binary:logistic", eval_metric = 'logloss', cv = 3) : + + param_grid = { + "n_estimators": [100, 500], + "learning_rate": [0.1, 0.05], + "max_depth": [3, 5, 7], + "subsample": [0.8, 1.0], + "colsample_bytree": [0.8, 1.0], + "reg_lambda": [0.5, 1], + "reg_alpha": [0, 0.5] + } + + grid_search = GridSearchCV( + estimator=xgb.XGBClassifier(objective= objective, eval_metric= eval_metric), + param_grid=param_grid, + scoring="accuracy", + cv=cv, # Validation croisée à 3 folds + n_jobs=-1, + verbose=1 + ) + + grid_search.fit(self.X_train, self.y_train) + + self.best_params_ = grid_search.best_params_ + self.best_model_ = grid_search.best_estimator_ + + return self.best_params_ + + def fit(self) : + + if not hasattr(self, "best_params_"): + raise ValueError("grid_search() must be called before fit().") + + else : + self.model = xgb.XGBClassifier( + objective=self.objective, + eval_metric=self.eval_metric, + n_estimators= self.best_params_['n_estimators'], + learning_rate=self.best_params_['learning_rate'], + max_depth=self.best_params_['max_depth'], + colsample_bytree = self.best_params_['colsample_bytree'], + reg_alpha = self.best_params_['reg_alpha'] , + reg_lambda = self.best_params_['reg_lambda'], + subsample = self.best_params_['subsample'], + scale_pos_weight= self.class_ratio) + + return self.model.fit(self.X_train, self.y_train) + + def predict(self, X): + return self.model.predict(X) + + def predict_proba(self, X): + return self.model.predict_proba(X) + + + def scoring(self) : + + # Prédictions sur le jeu de test (probabilités pour ROC-AUC et PR-AUC) + self.y_pred = self.model.predict(self.X_test) + self.y_pred_proba = self.model.predict_proba(self.X_test)[:, 1] # Probabilité d'être classe 1 + + # Accuracy classique + accuracy = accuracy_score(self.y_test, self.y_pred) + balanced_acc = balanced_accuracy_score(self.y_test, self.y_pred) + + # ROC-AUC score + roc_auc = roc_auc_score(self.y_test, self.y_pred_proba) + + # PR-AUC (courbe Precision-Recall) + precision, recall, _ = precision_recall_curve(self.y_test, self.y_pred_proba) + pr_auc = auc(recall, precision) + + # Matrice de confusion + conf_matrix = confusion_matrix(self.y_test, self.y_pred) + + self.accuracy = accuracy + self.balanced_acc = balanced_acc + self.roc_auc = roc_auc + self.pr_auc = pr_auc + self.classification_report = classification_report(self.y_test, self.y_pred) + self.conf_matrix = conf_matrix + + # Affichage des résultats + print(f"Accuracy: {accuracy:.2f}") + print(f"Balanced Accuracy: {balanced_acc:.2f}") + print(f"ROC-AUC Score: {roc_auc:.2f}") + print(f"PR-AUC Score: {pr_auc:.2f}\n") + + print("Classification Report:") + print(self.classification_report) + + print("Confusion Matrix:") + print(conf_matrix) + + # ajouter les fonctions pour les visualisations + + def plot_importance(self) : + + fig, ax = plt.subplots(figsize = (8,10)) + xgb.plot_importance(self.model, ax = ax, height=0.9, grid=False, color = '#FFBF66', max_num_features=20) + plt.show() + + def shap_values(self) : + explainer = shap.TreeExplainer(self.model, approximate=True) + self.shap_values = explainer(self.X_train) + + return self.shap_values + + def get_corr_shap_df(self) : + corr_list = [] + feature_list = self.X_train.columns + df_shap_values = pd.DataFrame(self.shap_values.values, + index = self.X_train.index, + columns = self.X_train.columns) + + # get correlation + for feature in tqdm(feature_list) : + b = np.corrcoef(df_shap_values[feature],self.X_train[feature])[1][0] + corr_list.append(b) + + # correlation by feature + df_corr = pd.concat([pd.Series(feature_list),pd.Series(corr_list)], axis = 1).fillna(0) + df_corr.columns = ['Variable','Corr'] + + # positive correlation in red and negative correlation in blue + df_corr['Color_sign'] = np.where(df_corr['Corr'] > 0,'green','red') + df_corr.loc[df_corr.Corr == 0,'Color_sign'] = 'grey' + + # plot it + shap_abs = np.abs(df_shap_values) + df_shap_abs = pd.DataFrame(shap_abs.mean()).reset_index() + df_shap_abs.columns = ['Variable','SHAP_abs'] + + # mean shap + corr + df_corr_shap = pd.merge(df_shap_abs,df_corr, on = 'Variable') + df_corr_shap['Sign_all'] = np.sign(df_corr_shap['Corr']) # get mean sign of correlation for total + df_corr_shap = df_corr_shap.sort_values(by = 'SHAP_abs', ascending = False) + + self.df_plot = df_corr_shap.iloc[0:12,:].sort_values(by = 'SHAP_abs', ascending = True) + self.df_plot['Variable'] = self.df_plot['Variable'].str.replace('_',' ') + + self.df_plot['SHAP_abs_sign'] = self.df_plot['SHAP_abs'] * self.df_plot['Sign_all'] + + return self.df_plot + + def plot_impact(self) : + #color_map = {'Positif' : '#DE2E4B', 'Négatif' :'#82CEF9'} + + xlabel = 'Coefficient d\'impact' + + colors = [] + + for value in self.df_plot['Corr'] : + if value > 0 : + colors.append('green') + elif value < 0 : + colors.append('red') + + fig, ax = plt.subplots(figsize=(10,8)) + + bars = ax.barh(self.df_plot['Variable'].apply(shorten_cfa_name), self.df_plot['SHAP_abs_sign'], color=colors, height=0.9) + ax.set_xlabel(xlabel) + ax.tick_params(axis='y', labelsize=7) + + #reste_index = self.df_plot[self.df_plot['index'] == f'{len(self.df_plot) - 20} autres variables'].index.values[0] + #bars[reste_index].set_hatch('//') + + for n,bar in enumerate(bars) : + width = round(bar.get_width(),2) + text = str(width) + + if colors[n] == 'green' : + ax.text(width*1.01, bar.get_y() + bar.get_height() / 2, text ,va='center', ha='left', color='green', fontsize=9) + else : + ax.text(width*1.01, bar.get_y() + bar.get_height() / 2, text ,va='center', ha='right', color='red', fontsize=9) + + legend_elements = [ + mpatches.Patch(facecolor='green', label='Positif'), + mpatches.Patch(facecolor='red', label='Négatif'), + ] + + ax.vlines(0,-1, self.df_plot.shape[0], color = 'black') + + ax.set_xlim(min(self.df_plot['SHAP_abs_sign'])*1.2, max(self.df_plot['SHAP_abs_sign'])*1.3) + ax.legend(handles=legend_elements, loc='best', title='Impact sur la prédiction') + plt.title('Impact moyen des variables sur la prédiction (SHAP)', pad = 20, fontsize = 14) + plt.tight_layout() + plt.show() + + + + + \ No newline at end of file diff --git a/utils_graph.py b/utils_graph.py new file mode 100644 index 0000000..588399a --- /dev/null +++ b/utils_graph.py @@ -0,0 +1,119 @@ +import numpy as np +import matplotlib.pyplot as plt +import pandas as pd +from matplotlib.colors import LinearSegmentedColormap, ListedColormap +import matplotlib.patches as mpatches + +# partie sur les légendes à revoir + +c_map = ['#000091', '#AB0345'] +cmap = LinearSegmentedColormap.from_list("custom_cmap", c_map) + +class plot_graph() : + def __init__(self,df, x, y, figsize = (10,6), ax = None, fig = None): + self.df = df + self.x = self.df[x] + self.y = self.df[y] + self.figsize = figsize + self.ax = ax + self.fig = fig + + def barh_subplot(self, title = None, xlabel = None, ylabel = None, + path = None, yticklabels = None, xticklabels = None, colors = None, + legend_list = None, title_legend = None, show = True, force_new_fig= True, + legend_indices=None): + + # couleurs des barres + if colors in self.df.columns and not self.df[colors].empty: + valid_colors = [c for c in self.df[colors] if not pd.isna(c)] + n_color = max(valid_colors) + 1 + self.list_colors = cmap(np.linspace(0,1,n_color)) + colors_bars = ['lightgray' if pd.isna(n) else self.list_colors[n] for n in self.df[colors]] + + hatches = ['//' if pd.isna(n) else None for n in self.df[colors]] + + elif colors is None : + self.list_colors = None + colors_bars = colors + hatches = None + + # Tracer le graphique + if self.ax is None or self.fig is None or force_new_fig: + self.fig, self.ax = plt.subplots(figsize=self.figsize) + + self.bars = self.ax.barh(self.y, self.x, color = colors_bars, hatch = hatches) + + if legend_list and colors is not None: + legend_elements = [] + + # Toujours ajouter la légende pour les valeurs manquantes (None) + if any(pd.isna(c) or c is None for c in self.df[colors]): + legend_elements.append(mpatches.Patch(facecolor='lightgray', hatch='//', label='Indisponible')) + + if legend_indices is None: + legend_indices = list(range(len(legend_list))) # toutes les légendes par défaut + + for idx in legend_indices: + if idx < len(self.list_colors) and idx < len(legend_list): + legend_elements.append(mpatches.Patch(facecolor=self.list_colors[idx], label=legend_list[idx])) + + self.ax.legend(handles=legend_elements, loc='best', title=title_legend) + + if xticklabels is False : + self.ax.set_xticklabels([]) + elif xticklabels is not None : + self.ax.set_xticklabels(xticklabels) + + if yticklabels is False : + self.ax.set_yticklabels([]) + elif yticklabels is not None : + self.ax.set_yticklabels(yticklabels) + + self.ax.set_xlabel(xlabel) + self.ax.set_ylabel(ylabel) + self.ax.set_title(title, pad=30, color='black', fontsize=16) + + self.ax.grid(axis='x', linestyle='-', alpha=0.2) + + plt.tight_layout() + + if show : + plt.show() + + if path: + plt.savefig(path, dpi=500, bbox_inches='tight') + + return self.fig + + # partie à revoir selon les besoins des missions + def annotation(self, pourcentage = None, Nombre = None) : + + if pourcentage and not Nombre : + for n, bar in enumerate(self.bars) : + width = bar.get_width() + text = self.df.loc[n,pourcentage] + self.ax.text(width * 1.01 if not np.isnan(width) else 0 , bar.get_y() + bar.get_height() / 2, + text, va='center', ha='left', color='gray', fontsize=9) + + elif Nombre and not pourcentage : + for n, bar in enumerate(self.bars) : + width = bar.get_width() + text = self.df.loc[n,Nombre] + self.ax.text(width * 1.01 if not np.isnan(width) else 0 , bar.get_y() + bar.get_height() / 2, + text, va='center', ha='left', color='gray', fontsize=9) + + elif Nombre and pourcentage : + for n, bar in enumerate(self.bars) : + width = bar.get_width() + text = f'{self.df.loc[n,Nombre]} ({self.df.loc[n,pourcentage]} %)' + self.ax.text(width * 1.01 if not np.isnan(width) else 0 , bar.get_y() + bar.get_height() / 2, + text, va='center', ha='left', color='gray', fontsize=9) + + + def encadrer(self) : + + """iscod_index = self.df[self.df['denomination_cfa'] == 'ISCOD'].index.values[0] + bars[iscod_index].set_edgecolor('black') # Couleur de la bordure + bars[iscod_index].set_linewidth(2) # Épaisseur de la bordure """ + + pass \ No newline at end of file -- GitLab