Skip to main content

MultiTrain allows you to train multiple machine learning algorthims on a dataset all at once to determine the best for that particular use case

Project description

PyPI PyPI - Downloads GitHub branch checks state Languages GitHub repo size GitHub issues GitHub closed issues GitHub pull requests GitHub closed pull requests GitHub GitHub Repo stars GitHub forks GitHub contributors Downloads

MultiTrain

MultiTrain is a python module for machine learning, built with the aim of assisting you to find the machine learning model that works best on a particular dataset.

REQUIREMENTS

MultiTrain requires:

  • matplotlib==3.5.3
  • numpy==1.23.3
  • pandas==1.4.4
  • plotly==5.10.0
  • scikit-learn==1.1.2
  • xgboost==1.6.2
  • catboost==1.0.6
  • imbalanced-learn==0.9.1
  • seaborn==0.12.0
  • lightgbm==3.3.2
  • scikit-optimize==0.9.0

INSTALLATION

Install MultiTrain using:

pip install MultiTrain

ISSUES

If you experience a bug while using MultiTrain, make sure to update to the latest version with

pip install --upgrade MultiTrain

If that doesn't fix your bug, create an issue in the issue tracker

USAGE

CLASSIFICATION

MultiClassifier

The MultiClassifier is a combination of many classifier estimators, each of which is fitted on the training data and returns assessment metrics such as accuracy, balanced accuracy, r2 score, f1 score, precision, recall, roc auc score for each of the models.

#This is a code snippet of how to import the MultiClassifier and the parameters contained in an instance

from MultiTrain import MultiClassifier
train = MultiClassifier(cores=-1, #this parameter works exactly the same as setting n_jobs to -1, this uses all the cpu cores to make training faster
                        random_state=42, #setting random state here automatically sets a unified random state across function imports
                        verbose=True, #set this to True to display the name of the estimators being fitted at a particular time
                        target_class='binary', #Recommended: set this to one of binary or multiclass to allow the library to adjust to the type of classification problem
                        imbalanced=True, #set this parameter to true if you are working with an imbalanced dataset
                        sampling='SMOTE', #set this parameter to any over_sampling, under_sampling or over_under_sampling methods if imbalanced is True
                        strategy='auto' #not all samplers use this parameters, the parameter is named as sampling_strategy for the samplers that support,
                                        #read more in the imbalanced learn documentation before using this parameter
                        )

In continuation of the code snippet above, if you're unsure about the various sampling techniques accessible after setting imbalanced to True when working on an imbalanced dataset, a code snippet is provided below to generate a list of all available sampling techniques.

from MultiTrain import MultiClassifier
train = MultiClassifier()
print(train.strategies()) #this line of codes returns all the under sampling, over sampling and over_under sampling methods available for use

Classifier Model Names

To return a list of all models available for training

from MultiTrain import MultiClassifier
train = MultiClassifier()
print(train.classifier_model_names())

Split

This function operates identically like the scikit-learn framework's train test split function. However, it has some extra features. For example, the split method is demonstrated in the code below.

import pandas as pd
from MultiTrain import MultiClassifier

train = MultiClassifier()
df = pd.read_csv("nameofFile.csv")

features = df.drop("nameOflabelcolum", axis = 1)
labels = df["nameOflabelcolum"]

split = train.split(X=features, 
                    y=labels, 
                    sizeOfTest=0.3, 
                    randomState=42)

If you want to run Principal Component Analysis on your dataset to reduce its dimensionality, You can achieve this with the split function. See the code excerpt below.

import pandas as pd
from MultiTrain import MultiClassifier #import the module

train = MultiClassifier()
df = pd.read_csv('NameOfFile.csv')

features = df.drop("nameOfLabelColumn", axis=1)
labels = df['nameOfLabelColumn']
pretend_columns = ['columnA', 'columnB', 'columnC']

#It's important to note that when using the split function, it must be assigned to a variable as it returns values.
split = train.split(X=features, #the features of the dataset
                    y=labels,   #the labels of the dataset
                    sizeOfTest=0.2, #same as test_size parameter in train_test_split
                    randomState=42, #initialize the value of the random state parameter
                    dimensionality_reduction=True, #setting to True enables this function to perform PCA on both X_train and X_test automatically after splitting
                    normalize='StandardScaler', #when using dimensionality_reduction, this must be set to one of StandardScaler,MinMaxScaler or RobustScaler if feature columns aren't scaled before a split
                    n_components=2, #when using dimensionality_reduction, this parameter must be set to define the number of components to keep.
                    columns_to_scale=pretend_columns #pass in a list of the columns in your dataset that you wish to scale 
                    ) 

Fit

Now that the dataset has been split using the split method, it is time to train on it using the fit method. Instead of the standard training in scikit-learn, catboost, or xgboost, this fit method integrates almost all available machine learning algorithms and trains them all on the dataset. It then returns a pandas dataframe including information such as which algorithm is overfitting, which algorithm has the greatest accuracy, and so on. A basic code example for using the fit function is shown below.

import pandas as pd
from MultiTrain import MultiClassifier

train = MultiClassifier()
df = pd.read_csv('file.csv')

features = df.drop("nameOflabelcolumn", axis = 1)
labels = df["nameOflabelcolumn"]

split = train.split(X=features, 
                    y=labels, 
                    sizeOfTest=0.3, 
                    randomState=42,
                    strat=True,
                    shuffle_data=True)

fit = train.fit(X=features,
                y=labels,
                splitting=True,
                split_data=split)

Now, we would be looking at the various ways the fit method can be implemented.

If you used the traditional train_test_split method available in scikit-learn

import pandas as pd
from sklearn.model_selection import train_test_split
from MultiTrain import MultiClassifier
train = MultiClassifier()

df = pd.read_csv('filename.csv')

features = df.drop('labelName', axis=1)
labels = df['labelName']

X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
fit = train.fit(X_train=X_train, 
              X_test=X_test, 
              y_train=y_train, 
              y_test=y_test, 
              split_self=True, #always set this to true if you used the traditional train_test_split
              show_train_score=True, #only set this to true if you want to compare train equivalent of all the metrics shown on the dataframe
              return_best_model=True, #setting this to True means that you'll get a dataframe containing only the best performing model
              excel=True #when this parameter is set to true, an spreadsheet report of the training is stored in your current working directory
              ) 

If you used the split method provided by the MultiClassifier

import pandas as pd
from MultiTrain import MultiClassifier

train = MultiClassifier()
df = pd.read_csv('filename.csv')

features = df.drop('labelName', axis=1)
labels = df['labelName']

split = train.split(X=features,
                    y=labels,
                    sizeOfTest=0.2,
                    randomState=42,
                    shuffle_data=True)

fit = train.fit(splitting=True,
                split_data=split,
                show_train_score=True,
                excel=True)     

If you want to train on your dataset with KFold

import pandas as pd
from MultiTrain import MultiClassifier

train = MultiClassifier()
df = pd.read_csv('filename.csv')

features = df.drop('labelName', axis=1)
labels = df['labelName']

fit = train.fit(X=features,
                y=labels,
                kf=True, #set this to true if you want to train on your dataset with KFold
                fold=5, #you can adjust this to use any number of folds you want for kfold, higher numbers leads to higher training times
                show_train_score=True,
                excel=True)

If you're working on an NLP problem

import pandas as pd
from MultiTrain import MultiClassifier

train = MultiClassifier()
df = pd.read_csv('filename.csv')

features = df.drop('LabelName', axis=1)
labels = df['labelName']

data_split = train.split(X=features,
                         y=labels,
                         sizeOfTest=0.2,
                         randomState=42)

fit = train.fit(X=features,
                y=labels,
                splitting=True,
                split_data=data_split,
                show_train_score=True,
                excel=True,
                text=True, #setting text to True lets the method know you're working on NLP
                vectorizer='count', #set this to one of 'count' or 'tfidf' when text is True
                ngrams=(1,3) #this defines the sequence of N words
 )

After training on your dataset, it is only normal that you'd want to make use of the best algorithm based on a specific metric. A method is also provided for you to do this easily. Continuing from any of the code snippets above(for the fit method) - after training, to use the best algorithm based on it's name

mod=train.use_best_model(df=fit, model='LogisticRegression')

Or else if you want to automatically select the best algorithm based on a particular metric of your choice

mod=train.use_best_model(df=fit, best='Balanced Accuracy')

It gets interesting. After model training, it is obvious that you get a dataframe containing all algorithms and their performance. What if you could visualize this dataframe instead and even save all the plots to your directory? Check the code snippet below to see how

Note: In order to visualize your model training results, you must have passed the fit method into a variable.

If you want to visualize the plots with matplotlib

#this code is a continuation of the implementations of the fit method above

#if you only want to visualize the results in your notebook, use this code
train.visualize(param=fit, #this parameter takes in the dataframe of the training results 
                t_split=True, #set t_split to true here if you split your data with the split method provided by MultiTrain
                kf=False, #set kf to True here if you used KFold split to train, note t_split and kf can't be set to True at the same time
                size=(15,8) #this sets the size of each plots to be displayed in your notebook
                )

#if you want to visualize the results in your notebook and save the plots to your system
train.visualize(param=fit,
                t_split=True,
                size=(15,8),
                file_path='C:/Users/lenovo/', #you can set your own filepath here)
                save='png', #you can choose to set this parameter to either 'png' or 'pdf'
                save_name='dir1'
                )

# the value set to save_name becomes the name of the pdf file if you set save='pdf'
# the value set to save_name becomes the name of a folder created to accommodate the png file if you set save='png'

If you want to visualize the plots with plotly

Plotly unlike matplotlib provides you with interactive plots. The code syntax is exactly the same with the visualize function. The only exception is that you need to use train.show() instead of train.visualize()

REGRESSION


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

MultiTrain-0.1.30.tar.gz (27.0 kB view details)

Uploaded Source

Built Distribution

MultiTrain-0.1.30-py3-none-any.whl (28.2 kB view details)

Uploaded Python 3

File details

Details for the file MultiTrain-0.1.30.tar.gz.

File metadata

  • Download URL: MultiTrain-0.1.30.tar.gz
  • Upload date:
  • Size: 27.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.7

File hashes

Hashes for MultiTrain-0.1.30.tar.gz
Algorithm Hash digest
SHA256 a13aa054b2130bcf643da63fb2eb2e68a8359c8d92771e6c6f3640fea0a2d293
MD5 e7f09b2bffa20258431f896824d0ef77
BLAKE2b-256 c54c2cbe621184b35b8710079772eeea12f5372cf4ac2c154f4f16ddaa85b674

See more details on using hashes here.

Provenance

File details

Details for the file MultiTrain-0.1.30-py3-none-any.whl.

File metadata

  • Download URL: MultiTrain-0.1.30-py3-none-any.whl
  • Upload date:
  • Size: 28.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.7

File hashes

Hashes for MultiTrain-0.1.30-py3-none-any.whl
Algorithm Hash digest
SHA256 02cf079baff3c6d82b7dc21ef0edc185fd939f1e5a131a45c5eb218cb7884cfe
MD5 7c4ade847e2cdd3206c2b42bbba846f8
BLAKE2b-256 036ce57a8cda6c4d0857855b3488994e30a5676cc1f62cd9c22060214a957bd9

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page