Package: mljar-supervised
MLJAR Automated Machine Learning for HumansDocumentation:https://supervised.mljar.com/Source Code:https://github.com/mljar/mljar-supervisedLooking for commercial support: Please contact us byemailfor detailsTable of ContentsAutomated Machine LearningWhat's good in it?AutoML Web App with GUIAutomatic DocumentationAvailable ModesFairness Aware TrainingExamplesFAQDocumentationInstallationDemoContributingCiteLicenseCommercial supportMLJARAutomated Machine LearningThemljar-supervisedis an Automated Machine Learning Python package that works with tabular data. It is designed to save time for a data scientist. It abstracts the common way to preprocess the data, construct the machine learning models, and perform hyper-parameters tuning to find the best model :trophy:. It is no black box, as you can see exactly how the ML pipeline is constructed (with a detailed Markdown report for each ML model).Themljar-supervisedwill help you with:explaining and understanding your data (Automatic Exploratory Data Analysis),trying many different machine learning models (Algorithm Selection and Hyper-Parameters tuning),creating Markdown reports from analysis with details about all models (Automatic-Documentation),saving, re-running, and loading the analysis and ML models.It has four built-in modes of work:Explainmode, which is ideal for explaining and understanding the data, with many data explanations, like decision trees visualization, linear models coefficients display, permutation importance, and SHAP explanations of data,Performfor building ML pipelines to use in production,Competemode that trains highly-tuned ML models with ensembling and stacking, with the purpose to use in ML competitions.Optunamode can be used to search for highly-tuned ML models should be used when the performance is the most important, and computation time is not limited (it is available from version0.10.0)Of course, you can further customize the details of eachmodeto meet the requirements.What's good in it?It uses many algorithms:Baseline,Linear,Random Forest,Extra Trees,LightGBM,Xgboost,CatBoost,Neural Networks, andNearest Neighbors.It can compute Ensemble based on a greedy algorithm fromCaruana paper.It can stack models to build a level 2 ensemble (available inCompetemode or after setting thestack_modelsparameter).It can do features preprocessing, like missing values imputation and converting categoricals. What is more, it can also handle target values preprocessing.It can do advanced features engineering, likeGolden Features,Features Selection, Text and Time Transformations.It can tune hyper-parameters with anot-so-random-searchalgorithm (random-search over a defined set of values) and hill climbing to fine-tune final models.It can compute theBaselinefor your data so that you will know if you need Machine Learning or not!It has extensive explanations. This package is training simpleDecision Treeswithmax_depth <= 5, so you can easily visualize them with amazingdtreevizto better understand your data.Themljar-superviseduses simple linear regression and includes its coefficients in the summary report, so you can check which features are used the most in the linear model.It cares about the explainability of models: for every algorithm, the feature importance is computed based on permutation. Additionally, for every algorithm, the SHAP explanations are computed: feature importance, dependence plots, and decision plots (explanations can be switched off with theexplain_levelparameter).There is automatic documentation for every ML experiment run with AutoML. Themljar-supervisedcreates markdown reports from AutoML training full of ML details, metrics, and charts.AutoML Web App with User InterfaceWe created a Web App with GUI, so you don't need to write any code 🐍. Just upload your data. Please check the Web App atgithub.com/mljar/automl-app. You can run this Web App locally on your computer, so your data is safe and secure :cat:Automatic DocumentationThe AutoML ReportThe report from running AutoML will contain the table with information about each model score and the time needed to train the model. There is a link for each model, which you can click to see the model's details. The performance of all ML models is presented as scatter and box plots so you can visually inspect which algorithms perform the best :trophy:.TheDecision TreeReportThe example forDecision Treesummary with trees visualization. For classification tasks, additional metrics are provided:confusion matrixthreshold (optimized in the case of binary classification task)F1 scoreAccuracyPrecision, Recall, MCCTheLightGBMReportThe example forLightGBMsummary:Available ModesIn thedocsyou can find details about AutoML modes that are presented in the table.Explainautoml=AutoML(mode="Explain")It is aimed to be used when the user wants to explain and understand the data.It is using 75%/25% train/test split.It uses:Baseline,Linear,Decision Tree,Random Forest,Xgboost, `Neural Network' algorithms, and ensemble.It has full explanations: learning curves, importance plots, and SHAP plots.Performautoml=AutoML(mode="Perform")It should be used when the user wants to train a model that will be used in real-life use cases.It uses a 5-fold CV.It uses:Linear,Random Forest,LightGBM,Xgboost,CatBoost, andNeural Network. It uses ensembling.It has learning curves and importance plots in reports.Competeautoml=AutoML(mode="Compete")It should be used for machine learning competitions.It adapts the validation strategy depending on dataset size andtotal_time_limit. It can be: a train/test split (80/20), 5-fold CV or 10-fold CV.It is using:Linear,Decision Tree,Random Forest,Extra Trees,LightGBM,Xgboost,CatBoost,Neural Network, andNearest Neighbors. It uses ensemble andstacking.It has only learning curves in the reports.Optunaautoml=AutoML(mode="Optuna",optuna_time_budget=3600)It should be used when the performance is the most important and time is not limited.It uses a 10-fold CVIt uses:Random Forest,Extra Trees,LightGBM,Xgboost, andCatBoost. Those algorithms are tuned byOptunaframework foroptuna_time_budgetseconds, each. Algorithms are tuned with original data, without advanced feature engineering.It uses advanced feature engineering, stacking and ensembling. The hyperparameters found for original data are reused with those steps.It produces learning curves in the reports.How to save and load AutoML?All models in the AutoML are saved and loaded automatically. No need to callsave()orload().Example:Train AutoMLautoml=AutoML(results_path="AutoML_classifier")automl.fit(X,y)You will have all models saved in theAutoML_classifierdirectory. Each model will have a separate directory with theREADME.mdfile with all details from the training.Compute predictionsautoml=AutoML(results_path="AutoML_classifier")automl.predict(X)The  AutoML automatically loads models from theresults_pathdirectory. If you will callfit()on already trained AutoML then you will get a warning message that AutoML is already fitted.Why do you automatically save all models?All models are automatically saved to be able to restore the training after interruption. For example, you are training AutoML for 48 hours, and after 47 hours, there is some unexpected interruption. In MLJAR AutoML you just call the same training code after the interruption and AutoML reloads already trained models and finishes the training.Supported evaluation metrics (eval_metricargument inAutoML())for binary classification:logloss,auc,f1,average_precision,accuracy- default isloglossfor multiclass classification:logloss,f1,accuracy- default isloglossfor regression:rmse,mse,mae,r2,mape,spearman,pearson- default isrmseIf you don't find theeval_metricthat you need, please add a new issue. We will add it.Fairness Aware TrainingStarting from version1.0.0AutoML can optimize the Machine Learning pipeline with sensitive features. There are the following fairness related arguments in the AutoML constructor:fairness_metric- metric which will be used to decide if the model is fair,fairness_threshold- threshold used in decision about model fairness,privileged_groups- privileged groups used in fairness metrics computation,underprivileged_groups- underprivileged groups used in fairness metrics computation.Thefit()method acceptssensitive_features. When sensitive features are passed to AutoML, the best model will be selected among fair models only. In the AutoML reports, additional information about fairness metrics will be added. The MLJAR AutoML supports two methods for bias mitigation:Sample Weighting - assigns weights to samples to treat samples equally,Smart Grid Search - similar to Sample Weighting, where different weights are checked to optimize fairness metric.The fair ML building can be used with all algorithms, includingEnsembleandStacked Ensemble. We support three Machine Learning tasks:binary classification,mutliclass classification,regression.Example code:fromsklearn.model_selectionimporttrain_test_splitfromsklearn.datasetsimportfetch_openmlfromsupervised.automlimportAutoMLdata=fetch_openml(data_id=1590,as_frame=True)X=data.datay=(data.target==">50K")*1sensitive_features=X[["sex"]]X_train,X_test,y_train,y_test,S_train,S_test=train_test_split(X,y,sensitive_features,stratify=y,test_size=0.75,random_state=42)automl=AutoML(algorithms=["Xgboost"],train_ensemble=False,fairness_metric="demographic_parity_ratio",fairness_threshold=0.8,privileged_groups=[{"sex":"Male"}],underprivileged_groups=[{"sex":"Female"}],)automl.fit(X_train,y_train,sensitive_features=S_train)You can read more about fairness aware AutoML training in our articlehttps://mljar.com/blog/fairness-machine-learning/Examples:point_right: Binary Classification ExampleThere is a simple interface available withfitandpredictmethods.importpandasaspdfromsklearn.model_selectionimporttrain_test_splitfromsupervised.automlimportAutoMLdf=pd.read_csv("https://raw.githubusercontent.com/pplonski/datasets-for-start/master/adult/data.csv",skipinitialspace=True,)X_train,X_test,y_train,y_test=train_test_split(df[df.columns[:-1]],df["income"],test_size=0.25)automl=AutoML()automl.fit(X_train,y_train)predictions=automl.predict(X_test)AutoMLfitwill print:CreatedirectoryAutoML_1AutoMLtasktobesolved:binary_classificationAutoMLwillusealgorithms:['Baseline','Linear','Decision Tree','Random Forest','Xgboost','Neural Network']AutoMLwilloptimizeformetric:logloss1_Baselinefinallogloss0.5519845471086654time0.08seconds2_DecisionTreefinallogloss0.3655910192804364time10.28seconds3_Linearfinallogloss0.38139916864708445time3.19seconds4_Default_RandomForestfinallogloss0.2975204390214936time79.19seconds5_Default_Xgboostfinallogloss0.2731086827200411time5.17seconds6_Default_NeuralNetworkfinallogloss0.319812276905242time21.19secondsEnsemblefinallogloss0.2731086821194617time1.43secondsthe AutoML results inMarkdown reportthe XgboostMarkdown report, please take a look at amazing dependence plots produced by SHAP package :sparkling_heart:the Decision TreeMarkdown report, please take a look at beautiful tree visualization :sparkles:the Logistic RegressionMarkdown report, please take a look at coefficients table, and you can compare the SHAP plots between (Xgboost, Decision Tree and Logistic Regression) :coffee::point_right: Multi-Class Classification ExampleThe example code for classification of the optical recognition of handwritten digits dataset. Running this code in less than 30 minutes will result in test accuracy ~98%.importpandasaspd# scikit learn utilitesfromsklearn.datasetsimportload_digitsfromsklearn.metricsimportaccuracy_scorefromsklearn.model_selectionimporttrain_test_split# mljar-supervised packagefromsupervised.automlimportAutoML# load the datadigits=load_digits()X_train,X_test,y_train,y_test=train_test_split(pd.DataFrame(digits.data),digits.target,stratify=digits.target,test_size=0.25,random_state=123)# train models with AutoMLautoml=AutoML(mode="Perform")automl.fit(X_train,y_train)# compute the accuracy on test datapredictions=automl.predict_all(X_test)print(predictions.head())print("Test accuracy:",accuracy_score(y_test,predictions["label"].astype(int))):point_right: Regression ExampleRegression example onCalifornia Housinghouse prices data.importnumpyasnpimportpandasaspdfromsklearn.datasetsimportfetch_california_housingfromsklearn.model_selectionimporttrain_test_splitfromsklearn.metricsimportmean_squared_errorfromsupervised.automlimportAutoML# mljar-supervised# Load the datahousing=fetch_california_housing()X_train,X_test,y_train,y_test=train_test_split(pd.DataFrame(housing.data,columns=housing.feature_names),housing.target,test_size=0.25,random_state=123,)# train models with AutoMLautoml=AutoML(mode="Explain")automl.fit(X_train,y_train)# compute the MSE on test datapredictions=automl.predict(X_test)print("Test MSE:",mean_squared_error(y_test,predictions)):point_right: More ExamplesIncome classification- it is a binary classification task on census dataIris classification- it is a multiclass classification on Iris flowers dataHouse price regression- it is a regression task on Boston houses dataFAQWhat method is used for hyperparameters optimization?- For modes: `Explain`, `Perform`, and `Compete` there is used a random search method combined with hill climbing. In this approach, all checked models are saved and used for building Ensemble.
  - For mode: `Optuna` the Optuna framework is used. It uses using TPE sampler for tuning. Models checked during the Optuna hyperparameters search are not saved, only the best model is saved (the final model from tuning). You can check the details about checked hyperparameters from optuna by checking study files in the `optuna` directory in your AutoML `results_path`.How to save and load AutoML?The save and load of AutoML models is automatic. All models created during AutoML training are saved in the directory set inresults_path(argument ofAutoML()constructor). If there is noresults_pathset, then the directory is created based on following name convention:AutoML_{number}thenumberwill be number from 1 to 1000 (depends which directory name will be free).Example save and load:automl=AutoML(results_path='AutoML_1')automl.fit(X,y)The all models from AutoML are saved inAutoML_1directory.To load models:automl=AutoML(results_path='AutoML_1')automl.predict(X)How to set ML task (select between classification or regression)?The MLJAR AutoML can work with:binary classificationmulti-class classificationregressionThe ML task detection is automatic based on target values. There can be situation if you want to manually force AutoML to select the ML task, then you need to setml_taskparameter. It can be set to'binary_classification','multiclass_classification','regression'.Example:automl=AutoML(ml_task='regression')automl.fit(X,y)In the above example the regression model will be fitted.How to reuse Optuna hyperparameters?You can reuse Optuna hyperparameters that were found in other AutoML training. You need to pass them inoptuna_init_paramsargument. All hyperparameters found during Optuna tuning are saved in theoptuna/optuna.jsonfile (insideresults_pathdirectory).Example:optuna_init=json.loads(open('previous_AutoML_training/optuna/optuna.json').read())automl=AutoML(mode='Optuna',optuna_init_params=optuna_init)automl.fit(X,y)When reusing Optuna hyperparameters the Optuna tuning is simply skipped. The model will be trained with hyperparameters set inoptuna_init_params. Right now there is no option to continue Optuna tuning with seed parameters.How to know the order of classes for binary or multiclass problem when using predict_proba?To get predicted probabilites with information about class label please use thepredict_all()method. It returns the pandas DataFrame with class names in the columns. The order of predicted columns is the same in thepredict_proba()andpredict_all()methods. Thepredict_all()method will additionaly have the column with the predicted class label.DocumentationFor details please checkmljar-supervised docs.InstallationFrom PyPi repository:pip install mljar-supervisedTo install this package with conda run:conda install -c conda-forge mljar-supervisedFrom source code:git clone https://github.com/mljar/mljar-supervised.git
cd mljar-supervised
python setup.py installInstallation for developmentgit clone https://github.com/mljar/mljar-supervised.git
virtualenv venv --python=python3.6
source venv/bin/activate
pip install -r requirements.txt
pip install -r requirements_dev.txtRunning in the docker:FROM python:3.7-slim-buster
RUN apt-get update && apt-get -y update
RUN apt-get install -y build-essential python3-pip python3-dev
RUN pip3 -q install pip --upgrade
RUN pip3 install mljar-supervised jupyter
CMD ["jupyter", "notebook", "--port=8888", "--no-browser", "--ip=0.0.0.0", "--allow-root"]Install from GitHub with pip:pip install -q -U git+https://github.com/mljar/mljar-supervised.git@masterDemoIn the below demo GIF you will see:MLJAR AutoML trained in Jupyter Notebook on the Titanic datasetoverview of created filesa showcase of selected plots created during AutoML trainingalgorithm comparison report along with their plotsexample of README file and CSV file with resultsContributingTo get started take a look at ourContribution Guidefor information about our process and where you can fit in!ContributorsCiteWould you like to cite MLJAR? Great! :)You can cite MLJAR as follows:@misc{mljar,
  author    = {Aleksandra P\l{}o\'{n}ska and Piotr P\l{}o\'{n}ski},
  year      = {2021},
  publisher = {MLJAR},
  address   = {\L{}apy, Poland},
  title     = {MLJAR: State-of-the-art Automated Machine Learning Framework for Tabular Data.  Version 0.10.3},
  url       = {https://github.com/mljar/mljar-supervised}
}Would love to hear from you about how have you used MLJAR AutoML in your project.
Please feel free to let us know atLicenseThemljar-supervisedis provided withMIT license.Commercial supportLooking for commercial support? Do you need new feature implementation? Please contact us byemailfor details.MLJARThemljar-supervisedis an open-source project created byMLJAR. We care about ease of use in Machine Learning.
Themljar.comprovides a beautiful and simple user interface for building machine learning models.