├── assets
└── img
│ ├── test
│ ├── logo.png
│ ├── LUCIFER-ML.gif
│ └── logo-LuciferML.png
├── luciferml
├── __init__.py
├── supervised
│ ├── __init__.py
│ ├── utils
│ │ ├── __init__.py
│ │ ├── tuner
│ │ │ ├── optuna
│ │ │ │ ├── optuna_base.py
│ │ │ │ └── objectives
│ │ │ │ │ ├── regression_objectives.py
│ │ │ │ │ └── classification_objectives.py
│ │ │ └── luciferml_tuner.py
│ │ ├── best.py
│ │ ├── validator.py
│ │ ├── configs.py
│ │ ├── preprocesser.py
│ │ └── predictors.py
│ ├── README
│ │ ├── Preprocessing.md
│ │ ├── Regression.md
│ │ └── Classification.md
│ ├── classification.py
│ └── regression.py
├── README.md
└── preprocessing.py
├── examples
├── Folds5x2_pp.xlsx
├── README.md
├── Salary_Data.csv
└── Social_Network_Ads.csv
├── _config.yml
├── requirements.txt
├── .github
├── workflows
│ └── publish-package.yml
└── FUNDING.yml
├── docs
└── index.rst
├── setup.py
├── .gitignore
├── README.md
└── LICENSE
/assets/img/test:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/assets/img/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/d4rk-lucif3r/LuciferML/HEAD/assets/img/logo.png
--------------------------------------------------------------------------------
/luciferml/__init__.py:
--------------------------------------------------------------------------------
1 | # __version__ = "0.0.11"
2 |
3 | from luciferml import preprocessing
4 |
--------------------------------------------------------------------------------
/assets/img/LUCIFER-ML.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/d4rk-lucif3r/LuciferML/HEAD/assets/img/LUCIFER-ML.gif
--------------------------------------------------------------------------------
/examples/Folds5x2_pp.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/d4rk-lucif3r/LuciferML/HEAD/examples/Folds5x2_pp.xlsx
--------------------------------------------------------------------------------
/luciferml/supervised/__init__.py:
--------------------------------------------------------------------------------
1 | # __version__ = "0.0.11"
2 |
3 | from luciferml.supervised import *
4 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/__init__.py:
--------------------------------------------------------------------------------
1 | # __version__ = "0.0.11"
2 | from luciferml.supervised.utils import *
3 |
--------------------------------------------------------------------------------
/assets/img/logo-LuciferML.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/d4rk-lucif3r/LuciferML/HEAD/assets/img/logo-LuciferML.png
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | title: LuciferML
2 | theme: jekyll-theme-minimal
3 | logo: /assets/img/LUCIFER-ML.gif
4 | description: Semi-Auto Machine Learning Library by d4rk-lucif3r.
5 | show_downloads: true
6 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | pandas
3 | scipy
4 | seaborn
5 | matplotlib
6 | scikit-learn
7 | imblearn
8 | xgboost
9 | tensorflow
10 | catboost
11 | lightgbm
12 | optuna
13 | shap
14 | colorama
--------------------------------------------------------------------------------
/luciferml/README.md:
--------------------------------------------------------------------------------
1 | # Learn More About
2 |
3 | 1) [Preprocessing](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Preprocessing.md)
4 |
5 | 2) [Classification](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Classification.md)
6 |
7 | 3) [Regression](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Regression.md)
8 |
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | # Examples
2 |
3 | ## Notebooks
4 |
5 | 1. [Heart Attack Analysis](https://www.kaggle.com/d4rklucif3r/heart-attack-analysis-eda-luciferml-88)
6 | 2. [Water Quality Prediction](https://www.kaggle.com/d4rklucif3r/water-quality-eda-luciferml-73-accuracy)
7 | 3. [Salary Prediction](https://www.kaggle.com/d4rklucif3r/salary-eda-luciferml-plotly)
8 | 4. [Stars Prediction](https://www.kaggle.com/d4rklucif3r/spectral-classes-plotly-luciferml-93)
9 |
--------------------------------------------------------------------------------
/examples/Salary_Data.csv:
--------------------------------------------------------------------------------
1 | YearsExperience,Salary
2 | 1.1,39343.00
3 | 1.3,46205.00
4 | 1.5,37731.00
5 | 2.0,43525.00
6 | 2.2,39891.00
7 | 2.9,56642.00
8 | 3.0,60150.00
9 | 3.2,54445.00
10 | 3.2,64445.00
11 | 3.7,57189.00
12 | 3.9,63218.00
13 | 4.0,55794.00
14 | 4.0,56957.00
15 | 4.1,57081.00
16 | 4.5,61111.00
17 | 4.9,67938.00
18 | 5.1,66029.00
19 | 5.3,83088.00
20 | 5.9,81363.00
21 | 6.0,93940.00
22 | 6.8,91738.00
23 | 7.1,98273.00
24 | 7.9,101302.00
25 | 8.2,113812.00
26 | 8.7,109431.00
27 | 9.0,105582.00
28 | 9.5,116969.00
29 | 9.6,112635.00
30 | 10.3,122391.00
31 | 10.5,121872.00
32 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/tuner/optuna/optuna_base.py:
--------------------------------------------------------------------------------
1 | import optuna
2 |
3 |
4 | class Tuner:
5 | def __init__(self, sampler, n_trials=100, direction="maximize"):
6 | self.n_trials = n_trials
7 | self.sampler = sampler
8 | self.direction = direction
9 |
10 | def tune(self, objective):
11 | study = optuna.create_study(direction=self.direction, sampler=self.sampler)
12 | study.optimize(objective, n_trials=self.n_trials, n_jobs=-1, gc_after_trial=True)
13 | params = study.best_params
14 | best_score = study.best_value
15 | return params, best_score
16 |
--------------------------------------------------------------------------------
/.github/workflows/publish-package.yml:
--------------------------------------------------------------------------------
1 | name: Publish LuciferML to PyPI
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | jobs:
9 | deploy:
10 | runs-on: ubuntu-20.04
11 |
12 | steps:
13 | - uses: actions/checkout@v2
14 | - uses: actions/setup-python@v2
15 | - name: Install Dependencies
16 | run: |
17 | python -m pip install --upgrade pip
18 | pip install setuptools wheel twine
19 | - name: Build Package and Publish it.
20 | env:
21 | TWINE_USERNAME: __token__
22 | TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
23 | run: |
24 | python setup.py sdist bdist_wheel
25 | twine upload dist/*
26 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [d4rk-lucif3r] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: #['lucifer78908@okaxis', 'https://paypal.me/d4rklucif3r '] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | The LuciferML is a Semi-Automated Machine Learning Python Library that works with tabular data. It is designed to save time while doing data analysis. It will help you right from data preprocessing to Data Prediction.
2 |
3 | The LuciferML will help you with
4 |
5 | 1) Preprocessing Data:
6 |
7 | - Encoding
8 | - Splitting
9 | - Scaling
10 | - Dimensionality Reduction
11 | - Resampling
12 |
13 | 2) Trying many different machine learning models with hyperparameter tuning,
14 |
15 | ## Learn About
16 | 1) [Preprocessing](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Preprocessing.md)
17 | 2) [Classification](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Classification.md)
18 | 3) [Regression](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Regression.md)
19 |
--------------------------------------------------------------------------------
/luciferml/supervised/README/Preprocessing.md:
--------------------------------------------------------------------------------
1 | # Preprocessing
2 |
3 | ## Available Methods
4 |
5 | 1) skewcorrect
6 |
7 | Plots distplot and probability plot for non-normalized data and after normalizing the provided data.
8 | Normalizes data using boxcox normalization
9 |
10 | Parameters:
11 |
12 | dataset : pd.DataFrame
13 |
14 | Dataset on which skewness correction has to be done.
15 |
16 | except_columns : list
17 |
18 | Columns for which skewness correction need not to be done.Default = []
19 |
20 | :returns: Scaled Dataset
21 | :rtype: pd.DataFrame
22 |
23 | Example:
24 |
25 | 1) All Columns
26 |
27 | from luciferml.preprocessing import Preprocess as pp
28 |
29 | import pandas as pd
30 |
31 | dataset = pd.read_csv('/examples/Social_Network_Ads.csv')
32 | prep = pp(dataset, dataset.columns)
33 | dataset = prep.skewcorrect(dataset)
34 |
35 | 2) Except column/columns
36 |
37 | from luciferml.preprocessing import Preprocess as pp
38 |
39 | import pandas as pd
40 |
41 | dataset = pd.read_csv('/examples/Social_Network_Ads.csv')
42 | prep = pp(dataset, dataset.columns, except_columns=['Purchased'])
43 | dataset = prep.skewcorrect()
44 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 | from codecs import open
3 | from os import path
4 |
5 | here = path.abspath(path.dirname(__file__))
6 |
7 | # Get the long description from the README file
8 | with open(path.join(here, "README.md"), encoding="utf-8") as f:
9 | long_description = f.read()
10 |
11 | setup(
12 | name="lucifer-ml",
13 | packages=[
14 | "luciferml",
15 | "luciferml.supervised",
16 | "luciferml.supervised.utils",
17 | "luciferml.supervised.utils.tuner",
18 | "luciferml.supervised.utils.tuner.optuna",
19 | "luciferml.supervised.utils.tuner.optuna.objectives",
20 | ],
21 | version="0.0.81a",
22 | license="MIT",
23 | description="Automated ML by d4rk-lucif3r",
24 | long_description=long_description,
25 | long_description_content_type="text/markdown",
26 | author="Arsh Anwar",
27 | author_email="lucifer78908@gmail.com",
28 | url="https://github.com/d4rk-lucif3r/LuciferML",
29 | keywords=["luciferML", "AutoML", "Python"],
30 | install_requires=open("requirements.txt").readlines(),
31 | classifiers=[
32 | "Development Status :: 3 - Alpha",
33 | "Intended Audience :: Developers",
34 | "Topic :: Software Development :: Build Tools",
35 | "License :: OSI Approved :: MIT License",
36 | "Programming Language :: Python :: 3",
37 | "Programming Language :: Python :: 3.4",
38 | "Programming Language :: Python :: 3.5",
39 | "Programming Language :: Python :: 3.6",
40 | ],
41 | )
42 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/best.py:
--------------------------------------------------------------------------------
1 | from colorama import Fore
2 |
3 |
4 | class Best:
5 | """
6 | Best is used to utilise the best model when predictor = 'all' is used.
7 |
8 | """
9 |
10 | def __init__(self, best_model, tune, isReg=False):
11 | self.__best_model = best_model
12 | self.model = self.__best_model["Model"]
13 | self.name = self.__best_model["Name"]
14 | self.tune = tune
15 | if isReg:
16 | self.r2_score = self.__best_model["R2 Score"]
17 | self.mae = self.__best_model["Mean Absolute Error"]
18 | self.rmse = self.__best_model["Root Mean Squared Error"]
19 | if not isReg:
20 | self.accuracy = self.__best_model["Accuracy"]
21 | self.kfold_acc = self.__best_model["KFold Accuracy"]
22 | if tune == True:
23 | self.best_params = self.__best_model["Best Parameters"]
24 | self.best_accuracy = self.__best_model["Best Accuracy"]
25 | else:
26 | self.best_params = "Run with tune = True to get best parameters"
27 | self.isReg = isReg
28 |
29 | def summary(self):
30 | """Returns a summary of the best model"""
31 | print("\nBest Model Summary:")
32 | print(Fore.CYAN + "Name: ", self.name)
33 | if self.isReg:
34 | print(Fore.CYAN + "R2 Score: ", self.r2_score)
35 | print(Fore.CYAN + "Mean Absolute Error: ", self.mae)
36 | print(Fore.CYAN + "Root Mean Squared Error: ", self.rmse)
37 | else:
38 | print(Fore.CYAN + "Accuracy: ", self.accuracy)
39 | print(Fore.CYAN + "KFold Accuracy: ", self.kfold_acc)
40 | if self.tune:
41 | print(Fore.CYAN + "Best Parameters: ", self.best_params)
42 | print(Fore.CYAN + "Best Accuracy: ", self.best_accuracy)
43 | print("\n")
44 |
45 | def predict(self, pred):
46 | """Predicts the output of the best model"""
47 | prediction = self.__best_model["Model"].predict(pred)
48 | return prediction
49 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/tuner/luciferml_tuner.py:
--------------------------------------------------------------------------------
1 | import traceback
2 |
3 | from luciferml.supervised.utils.predictors import classification_predictor
4 | from luciferml.supervised.utils.predictors import regression_predictor
5 | from luciferml.supervised.utils.tuner.optuna.optuna_base import Tuner
6 | from colorama import Fore
7 |
8 |
9 | def luciferml_tuner(
10 | predictor,
11 | objective,
12 | n_trials,
13 | sampler,
14 | direction,
15 | X_train,
16 | y_train,
17 | cv_folds,
18 | random_state,
19 | metric,
20 | all_mode=False,
21 | verbose=False,
22 | isReg=False,
23 | ):
24 | """
25 | Takes classifier, tune-parameters, Training Data and no. of folds as input and Performs GridSearch Crossvalidation.
26 | """
27 | tuner = Tuner(n_trials=n_trials, sampler=sampler, direction=direction)
28 | try:
29 | best_params, best_score = tuner.tune(objective)
30 | if isReg:
31 | model, _ = regression_predictor(
32 | predictor,
33 | best_params,
34 | X_train,
35 | y_train,
36 | cv_folds,
37 | random_state,
38 | metric,
39 | mode="tune",
40 | verbose=verbose,
41 | )
42 | if not isReg:
43 | model, _ = classification_predictor(
44 | predictor,
45 | best_params,
46 | X_train,
47 | y_train,
48 | cv_folds,
49 | random_state,
50 | metric,
51 | mode="tune",
52 | verbose=verbose,
53 | )
54 | if not all_mode:
55 | print(Fore.CYAN + " Best Params: ", best_params)
56 | print(Fore.CYAN + " Best Score: ", best_score * 100, "\n")
57 | return best_params, best_score, model
58 | except Exception as error:
59 | print(Fore.RED + "HyperParam Tuning Failed with Error: ", error, "\n")
60 | return None, 0, None
61 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | # models
132 | */catboost_info/*
133 | */lucifer_ml_info/*
134 | #venv
135 | *venv/*
136 | #misc
137 | *test*
--------------------------------------------------------------------------------
/luciferml/supervised/utils/validator.py:
--------------------------------------------------------------------------------
1 | from sklearn.model_selection import cross_val_score
2 | import scipy
3 | from luciferml.supervised.utils.configs import *
4 | from colorama import Fore
5 |
6 |
7 | def pred_check(predictor, pred_type):
8 | if pred_type == "regression":
9 | avlbl_predictors = list(regressors_ver.keys())
10 | elif pred_type == "classification":
11 | avlbl_predictors = list(classifiers_ver.keys())
12 | if type(predictor) == str:
13 | if predictor in avlbl_predictors:
14 | return True, predictor
15 | else:
16 | return False, predictor
17 | elif type(predictor) == list:
18 | for i in predictor:
19 | if i not in avlbl_predictors:
20 | return False, i
21 | return True, None
22 |
23 |
24 | def sparse_check(features, labels):
25 | features = features
26 | labels = labels
27 | """
28 | Takes features and labels as input and checks if any of those is sparse csr_matrix.
29 | """
30 | try:
31 | if scipy.sparse.issparse(features[()]):
32 | features = features[()].toarray()
33 | elif scipy.sparse.issparse(labels[()]):
34 | labels = labels[()].toarray()
35 | except Exception as error:
36 | pass
37 | return (features, labels)
38 |
39 |
40 | def kfold(model, predictor, X_train, y_train, cv_folds, isReg=False, all_mode=False):
41 | """
42 | Takes predictor, input_units, epochs, batch_size, X_train, y_train, cv_folds, and accuracy_scores dictionary.
43 | Performs K-Fold Cross validation and stores result in accuracy_scores dictionary and returns it.
44 | """
45 | if not isReg:
46 | name = classifiers
47 | scoring = "accuracy"
48 | if isReg:
49 | name = regressors
50 | scoring = "r2"
51 | try:
52 | accuracies = cross_val_score(
53 | estimator=model, X=X_train, y=y_train, cv=cv_folds, scoring=scoring
54 | )
55 | if not all_mode:
56 | if not isReg:
57 | print(" KFold Accuracy: {:.2f} %".format(accuracies.mean() * 100))
58 | if isReg:
59 | print(" R2 Score: {:.2f} %".format(accuracies.mean() * 100))
60 | model_name = name[predictor]
61 | accuracy = accuracies.mean() * 100
62 | if not all_mode:
63 | print(
64 | " Standard Deviation: {:.2f} %".format(accuracies.std() * 100),
65 | "\n",
66 | )
67 | return (model_name, accuracy)
68 |
69 | except Exception as error:
70 | print(Fore.RED + "K-Fold Cross Validation failed with error: ", error, "\n")
71 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/configs.py:
--------------------------------------------------------------------------------
1 | intro = """
2 |
3 | ██╗░░░░░██╗░░░██╗░█████╗░██╗███████╗███████╗██████╗░░░░░░░███╗░░░███╗██╗░░░░░
4 | ██║░░░░░██║░░░██║██╔══██╗██║██╔════╝██╔════╝██╔══██╗░░░░░░████╗░████║██║░░░░░
5 | ██║░░░░░██║░░░██║██║░░╚═╝██║█████╗░░█████╗░░██████╔╝█████╗██╔████╔██║██║░░░░░
6 | ██║░░░░░██║░░░██║██║░░██╗██║██╔══╝░░██╔══╝░░██╔══██╗╚════╝██║╚██╔╝██║██║░░░░░
7 | ███████╗╚██████╔╝╚█████╔╝██║██║░░░░░███████╗██║░░██║░░░░░░██║░╚═╝░██║███████╗
8 | ╚══════╝░╚═════╝░░╚════╝░╚═╝╚═╝░░░░░╚══════╝╚═╝░░╚═╝░░░░░░╚═╝░░░░░╚═╝╚══════╝
9 | """
10 |
11 | classifiers = {
12 | "lr": "Logistic Regression",
13 | "sgd": "Stochastic Gradient Descent",
14 | "perc": "Perceptron",
15 | "pass": "Passive Aggressive Classifier",
16 | "ridg": "Ridge Classifier",
17 | "svm": "Support Vector Machine",
18 | "knn": "K-Nearest Neighbours",
19 | "dt": "Decision Trees",
20 | "nb": "Naive Bayes",
21 | "rfc": "Random Forest Classifier",
22 | "gbc": "Gradient Boosting Classifier",
23 | "ada": "AdaBoost Classifier",
24 | "bag": "Bagging Classifier",
25 | "extc": "Extra Trees Classifier",
26 | "lgbm": "LightGBM Classifier",
27 | "cat": "CatBoost Classifier",
28 | "xgb": "XGBoost Classifier",
29 | "ann": "Multi Layer Perceptron Classifier",
30 | }
31 |
32 | regressors = {
33 | "lin": "Linear Regression",
34 | "sgd": "Stochastic Gradient Descent Regressor",
35 | "krr": "Kernel Ridge Regressor",
36 | "elas": "Elastic Net Regressor",
37 | "br": "Bayesian Ridge Regressor",
38 | "svr": "Support Vector Regressor",
39 | "knr": "K-Neighbors Regressor",
40 | "dt": "Decision Trees Regressor",
41 | "rfr": "Random Forest Regressor",
42 | "gbr": "Gradient Boost Regressor",
43 | "ada": "AdaBoost Regressor",
44 | "bag": "Bagging Regressor",
45 | "extr": "Extra Trees Regressor",
46 | "lgbm": "LightGBM Regressor",
47 | "xgb": "XGBoost Regressor",
48 | "cat": "Catboost Regressor",
49 | "ann": "Multi-Layer Perceptron Regressor",
50 | }
51 |
52 | classifiers_ver = {
53 | "lr": "Logistic Regression",
54 | "sgd": "Stochastic Gradient Descent",
55 | "perc": "Perceptron",
56 | "pass": "Passive Aggressive Classifier",
57 | "ridg": "Ridge Classifier",
58 | "svm": "Support Vector Machine",
59 | "knn": "K-Nearest Neighbours",
60 | "dt": "Decision Trees",
61 | "nb": "Naive Bayes",
62 | "rfc": "Random Forest Classifier",
63 | "gbc": "Gradient Boosting Classifier",
64 | "ada": "AdaBoost Classifier",
65 | "bag": "Bagging Classifier",
66 | "extc": "Extra Trees Classifier",
67 | "lgbm": "LightGBM Classifier",
68 | "cat": "CatBoost Classifier",
69 | "xgb": "XGBoost Classifier",
70 | "ann": "Multi Layer Perceptron Classifier",
71 | "all": "All Classifiers",
72 | }
73 |
74 | regressors_ver = {
75 | "lin": "Linear Regression",
76 | "sgd": "Stochastic Gradient Descent Regressor",
77 | "krr": "Kernel Ridge Regressor",
78 | "elas": "Elastic Net Regressor",
79 | "br": "Bayesian Ridge Regressor",
80 | "svr": "Support Vector Regressor",
81 | "knr": "K-Neighbors Regressor",
82 | "dt": "Decision Trees Regressor",
83 | "rfr": "Random Forest Regressor",
84 | "gbr": "Gradient Boost Regressor",
85 | "ada": "AdaBoost Regressor",
86 | "bag": "Bagging Regressor",
87 | "extr": "Extra Trees Regressor",
88 | "lgbm": "LightGBM Regressor",
89 | "xgb": "XGBoost Regressor",
90 | "cat": "Catboost Regressor",
91 | "ann": "Multi Layer Perceptron Regressor",
92 | "all": "All Regressors",
93 | }
94 | params_use_warning = (
95 | "Params will not work with predictor = 'all'. Settings params = {} "
96 | )
97 |
98 | unsupported_pred_warning = """Predictor not available. Please use the predictor which is supported by LuciferML.
99 | Check the documentation for more details.\nConflicting Predictor is : {}"""
100 |
--------------------------------------------------------------------------------
/luciferml/supervised/README/Regression.md:
--------------------------------------------------------------------------------
1 | # Regression
2 |
3 | Encodes Categorical Data then Applies SMOTE , Splits the features and labels in training and validation sets with test_size = .2
4 | scales X_train, X_val using StandardScaler.
5 | Fits every model on training set and predicts results,Finds R2 Score and mean square error
6 | finds accuracy of model applies K-Fold Cross Validation
7 | and stores its accuracies in a dictionary containing Model name as Key and accuracies as values and returns it
8 | Applies HyperParam Tuning and gives best params and accuracy.
9 |
10 | Parameters:
11 |
12 | features : array
13 | features array
14 | lables : array
15 | labels array
16 | predictor : str
17 | Predicting model to be used
18 | Default 'lin'
19 | Available Predictors:
20 | lin - Linear Regression
21 | sgd - Stochastic Gradient Descent Regressor
22 | elas - Elastic Net Regressor
23 | krr - Kernel Ridge Regressor
24 | br - Bayesian Ridge Regressor
25 | svr - Support Vector Regressor
26 | knr - K-Nearest Regressor
27 | dt - Decision Trees
28 | rfr - Random Forest Regressor
29 | gbr - Gradient Boost Regressor
30 | ada - AdaBoost Regressor,
31 | bag - Bagging Regressor,
32 | extr - Extra Trees Regressor,
33 | lgbm - LightGB Regressor
34 | xgb - XGBoost Regressor
35 | cat - Catboost Regressor
36 | ann - Multi Layer Perceptron Regressor
37 | all - Applies all above regressors
38 | params : dict
39 | contains parameters for model
40 | tune : boolean
41 | when True Applies GridSearch CrossValidation
42 | Default is False
43 |
44 | test_size: float or int, default=.2
45 | If float, should be between 0.0 and 1.0 and represent
46 | the proportion of the dataset to include in
47 | the test split.
48 | If int, represents the absolute number of test samples.
49 |
50 | cv_folds : int
51 | No. of cross validation folds. Default = 10
52 | pca : str
53 | if 'y' will apply PCA on Train and Validation set. Default = 'n'
54 | lda : str
55 | if 'y' will apply LDA on Train and Validation set. Default = 'n'
56 | pca_kernel : str
57 | Kernel to be use in PCA. Default = 'linear'
58 | n_components_lda : int
59 | No. of components for LDA. Default = 1
60 | n_components_pca : int
61 | No. of components for PCA. Default = 2
62 | loss : str
63 | loss method for ann. Default = 'mean_squared_error'
64 | smote : str,
65 | Whether to apply SMOTE. Default = 'y'
66 | k_neighbors : int
67 | No. of neighbours for SMOTE. Default = 1
68 | verbose : boolean
69 | Verbosity of models. Default = False
70 | exclude_models : list
71 | List of models to be excluded when using predictor = 'all' . Default = []
72 | path : list
73 | List containing path to saved model and scaler. Default = None
74 | Example: [model.pkl, scaler.pkl]
75 | random_state : int
76 | Random random_state for reproducibility. Default = 42
77 | optuna_sampler : Function
78 | Sampler to be used in optuna. Default = TPESampler()
79 | optuna_direction : str
80 | Direction of optimization. Default = 'maximize'
81 | Available Directions:
82 | maximize : Maximize
83 | minimize : Minimize
84 | optuna_n_trials : int
85 | No. of trials for optuna. Default = 100
86 | optuna_metric: str
87 | Metric to be used in optuna. Default = 'r2'
88 |
89 | Returns:
90 |
91 | Dict Containing Name of Regressor, Its K-Fold Cross Validated Accuracy, RMSE, Prediction set
92 | Dataframe containing all the models and their accuracies when predictor is 'all'
93 |
94 | Example:
95 |
96 | from luciferml.supervised.regression import Regression
97 | dataset = pd.read_excel('examples\Folds5x2_pp.xlsx')
98 | X = dataset.iloc[:, :-1]
99 | y = dataset.iloc[:, -1]
100 | regressor = Regression(predictor = 'lin')
101 | regressor.fit(X, y)
102 | result = regressor.result()
103 |
--------------------------------------------------------------------------------
/luciferml/supervised/README/Classification.md:
--------------------------------------------------------------------------------
1 | # Classification
2 |
3 | Encode Categorical Data then Applies SMOTE , Splits the features and labels in training and validation sets with test_size = .2 , scales X_train, X_val using StandardScaler.
4 | Fits every model on training set and predicts results find and plots Confusion Matrix,
5 | finds accuracy of model applies K-Fold Cross Validation
6 | and stores accuracy in variable name accuracy and model name in self.classifier name and returns both as a tuple.
7 | Applies HyperParam Tuning and gives best params and accuracy.
8 |
9 | Parameters:
10 |
11 | features : array
12 | features array
13 | lables : array
14 | labels array
15 | predictor : list
16 | Predicting model to be used
17 | Default ['lr']
18 | Available Predictors:
19 | lr - Logisitic Regression
20 | sgd - Stochastic Gradient Descent Classifier
21 | perc - Perceptron
22 | pass - Passive Aggressive Classifier
23 | ridg - Ridge Classifier
24 | svm -SupportVector Machine
25 | knn - K-Nearest Neighbours
26 | dt - Decision Trees
27 | nb - GaussianNaive bayes
28 | rfc- Random Forest self.Classifier
29 | gbc - Gradient Boosting Classifier
30 | ada - AdaBoost Classifier
31 | bag - Bagging Classifier
32 | extc - Extra Trees Classifier
33 | lgbm - LightGBM Classifier
34 | cat - CatBoost Classifier
35 | xgb- XGBoost self.Classifier
36 | ann - Multi Layer Perceptron Classifier
37 | all - Applies all above classifiers
38 |
39 | params : dict
40 | contains parameters for model
41 | tune : boolean
42 | when True Applies GridSearch CrossValidation
43 | Default is False
44 |
45 | test_size: float or int, default=.2
46 | If float, should be between 0.0 and 1.0 and represent
47 | the proportion of the dataset to include in
48 | the test split.
49 | If int, represents the absolute number of test samples.
50 |
51 | cv_folds : int
52 | No. of cross validation folds. Default = 10
53 | pca : str
54 | if 'y' will apply PCA on Train and Validation set. Default = 'n'
55 | lda : str
56 | if 'y' will apply LDA on Train and Validation set. Default = 'n'
57 | pca_kernel : str
58 | Kernel to be use in PCA. Default = 'linear'
59 | n_components_lda : int
60 | No. of components for LDA. Default = 1
61 | n_components_pca : int
62 | No. of components for PCA. Default = 2
63 | loss : str
64 | loss method for ann. Default = 'binary_crossentropy'
65 | rate for dropout layer. Default = 0
66 | tune_mode : int
67 | HyperParam tune modes. Default = 1
68 | Available Modes:
69 | 1 : Basic Tune
70 | 2 : Intermediate Tune
71 | 3 : Extreme Tune (Can Take Much Time)
72 | smote : str,
73 | Whether to apply SMOTE. Default = 'y'
74 | k_neighbors : int
75 | No. of neighbours for SMOTE. Default = 1
76 | verbose : boolean
77 | Verbosity of models. Default = False
78 | exclude_models : list
79 | List of models to be excluded when using predictor = 'all' . Default = []
80 | path : list
81 | List containing path to saved model and scaler. Default = None
82 | Example: [model.pkl, scaler.pkl]
83 | random_state : int
84 | Random random_state for reproducibility. Default = 42
85 | optuna_sampler : Function
86 | Sampler to be used in optuna. Default = TPESampler()
87 | optuna_direction : str
88 | Direction of optimization. Default = 'maximize'
89 | Available Directions:
90 | maximize : Maximize
91 | minimize : Minimize
92 | optuna_n_trials : int
93 | No. of trials for optuna. Default = 100
94 | optuna_metric: str
95 | Metric to be used in optuna. Default = 'r2'
96 | lgbm_objective : str
97 | Objective for lgbm classifier. Default = 'binary'
98 | Returns:
99 |
100 | Dict Containing Name of Classifiers, Its K-Fold Cross Validated Accuracy and Prediction set
101 |
102 | Dataframe containing all the models and their accuracies when predictor is 'all'
103 |
104 | Example :
105 |
106 | from luciferml.supervised.classification import Classification
107 | dataset = pd.read_csv('Social_Network_Ads.csv')
108 | X = dataset.iloc[:, :-1]
109 | y = dataset.iloc[:, -1]
110 | classifier = Classification(predictor = 'lr')
111 | classifier.fit(X, y)
112 | result = classifier.result()
113 |
--------------------------------------------------------------------------------
/examples/Social_Network_Ads.csv:
--------------------------------------------------------------------------------
1 | Age,EstimatedSalary,Purchased
2 | 19,19000,0
3 | 35,20000,0
4 | 26,43000,0
5 | 27,57000,0
6 | 19,76000,0
7 | 27,58000,0
8 | 27,84000,0
9 | 32,150000,1
10 | 25,33000,0
11 | 35,65000,0
12 | 26,80000,0
13 | 26,52000,0
14 | 20,86000,0
15 | 32,18000,0
16 | 18,82000,0
17 | 29,80000,0
18 | 47,25000,1
19 | 45,26000,1
20 | 46,28000,1
21 | 48,29000,1
22 | 45,22000,1
23 | 47,49000,1
24 | 48,41000,1
25 | 45,22000,1
26 | 46,23000,1
27 | 47,20000,1
28 | 49,28000,1
29 | 47,30000,1
30 | 29,43000,0
31 | 31,18000,0
32 | 31,74000,0
33 | 27,137000,1
34 | 21,16000,0
35 | 28,44000,0
36 | 27,90000,0
37 | 35,27000,0
38 | 33,28000,0
39 | 30,49000,0
40 | 26,72000,0
41 | 27,31000,0
42 | 27,17000,0
43 | 33,51000,0
44 | 35,108000,0
45 | 30,15000,0
46 | 28,84000,0
47 | 23,20000,0
48 | 25,79000,0
49 | 27,54000,0
50 | 30,135000,1
51 | 31,89000,0
52 | 24,32000,0
53 | 18,44000,0
54 | 29,83000,0
55 | 35,23000,0
56 | 27,58000,0
57 | 24,55000,0
58 | 23,48000,0
59 | 28,79000,0
60 | 22,18000,0
61 | 32,117000,0
62 | 27,20000,0
63 | 25,87000,0
64 | 23,66000,0
65 | 32,120000,1
66 | 59,83000,0
67 | 24,58000,0
68 | 24,19000,0
69 | 23,82000,0
70 | 22,63000,0
71 | 31,68000,0
72 | 25,80000,0
73 | 24,27000,0
74 | 20,23000,0
75 | 33,113000,0
76 | 32,18000,0
77 | 34,112000,1
78 | 18,52000,0
79 | 22,27000,0
80 | 28,87000,0
81 | 26,17000,0
82 | 30,80000,0
83 | 39,42000,0
84 | 20,49000,0
85 | 35,88000,0
86 | 30,62000,0
87 | 31,118000,1
88 | 24,55000,0
89 | 28,85000,0
90 | 26,81000,0
91 | 35,50000,0
92 | 22,81000,0
93 | 30,116000,0
94 | 26,15000,0
95 | 29,28000,0
96 | 29,83000,0
97 | 35,44000,0
98 | 35,25000,0
99 | 28,123000,1
100 | 35,73000,0
101 | 28,37000,0
102 | 27,88000,0
103 | 28,59000,0
104 | 32,86000,0
105 | 33,149000,1
106 | 19,21000,0
107 | 21,72000,0
108 | 26,35000,0
109 | 27,89000,0
110 | 26,86000,0
111 | 38,80000,0
112 | 39,71000,0
113 | 37,71000,0
114 | 38,61000,0
115 | 37,55000,0
116 | 42,80000,0
117 | 40,57000,0
118 | 35,75000,0
119 | 36,52000,0
120 | 40,59000,0
121 | 41,59000,0
122 | 36,75000,0
123 | 37,72000,0
124 | 40,75000,0
125 | 35,53000,0
126 | 41,51000,0
127 | 39,61000,0
128 | 42,65000,0
129 | 26,32000,0
130 | 30,17000,0
131 | 26,84000,0
132 | 31,58000,0
133 | 33,31000,0
134 | 30,87000,0
135 | 21,68000,0
136 | 28,55000,0
137 | 23,63000,0
138 | 20,82000,0
139 | 30,107000,1
140 | 28,59000,0
141 | 19,25000,0
142 | 19,85000,0
143 | 18,68000,0
144 | 35,59000,0
145 | 30,89000,0
146 | 34,25000,0
147 | 24,89000,0
148 | 27,96000,1
149 | 41,30000,0
150 | 29,61000,0
151 | 20,74000,0
152 | 26,15000,0
153 | 41,45000,0
154 | 31,76000,0
155 | 36,50000,0
156 | 40,47000,0
157 | 31,15000,0
158 | 46,59000,0
159 | 29,75000,0
160 | 26,30000,0
161 | 32,135000,1
162 | 32,100000,1
163 | 25,90000,0
164 | 37,33000,0
165 | 35,38000,0
166 | 33,69000,0
167 | 18,86000,0
168 | 22,55000,0
169 | 35,71000,0
170 | 29,148000,1
171 | 29,47000,0
172 | 21,88000,0
173 | 34,115000,0
174 | 26,118000,0
175 | 34,43000,0
176 | 34,72000,0
177 | 23,28000,0
178 | 35,47000,0
179 | 25,22000,0
180 | 24,23000,0
181 | 31,34000,0
182 | 26,16000,0
183 | 31,71000,0
184 | 32,117000,1
185 | 33,43000,0
186 | 33,60000,0
187 | 31,66000,0
188 | 20,82000,0
189 | 33,41000,0
190 | 35,72000,0
191 | 28,32000,0
192 | 24,84000,0
193 | 19,26000,0
194 | 29,43000,0
195 | 19,70000,0
196 | 28,89000,0
197 | 34,43000,0
198 | 30,79000,0
199 | 20,36000,0
200 | 26,80000,0
201 | 35,22000,0
202 | 35,39000,0
203 | 49,74000,0
204 | 39,134000,1
205 | 41,71000,0
206 | 58,101000,1
207 | 47,47000,0
208 | 55,130000,1
209 | 52,114000,0
210 | 40,142000,1
211 | 46,22000,0
212 | 48,96000,1
213 | 52,150000,1
214 | 59,42000,0
215 | 35,58000,0
216 | 47,43000,0
217 | 60,108000,1
218 | 49,65000,0
219 | 40,78000,0
220 | 46,96000,0
221 | 59,143000,1
222 | 41,80000,0
223 | 35,91000,1
224 | 37,144000,1
225 | 60,102000,1
226 | 35,60000,0
227 | 37,53000,0
228 | 36,126000,1
229 | 56,133000,1
230 | 40,72000,0
231 | 42,80000,1
232 | 35,147000,1
233 | 39,42000,0
234 | 40,107000,1
235 | 49,86000,1
236 | 38,112000,0
237 | 46,79000,1
238 | 40,57000,0
239 | 37,80000,0
240 | 46,82000,0
241 | 53,143000,1
242 | 42,149000,1
243 | 38,59000,0
244 | 50,88000,1
245 | 56,104000,1
246 | 41,72000,0
247 | 51,146000,1
248 | 35,50000,0
249 | 57,122000,1
250 | 41,52000,0
251 | 35,97000,1
252 | 44,39000,0
253 | 37,52000,0
254 | 48,134000,1
255 | 37,146000,1
256 | 50,44000,0
257 | 52,90000,1
258 | 41,72000,0
259 | 40,57000,0
260 | 58,95000,1
261 | 45,131000,1
262 | 35,77000,0
263 | 36,144000,1
264 | 55,125000,1
265 | 35,72000,0
266 | 48,90000,1
267 | 42,108000,1
268 | 40,75000,0
269 | 37,74000,0
270 | 47,144000,1
271 | 40,61000,0
272 | 43,133000,0
273 | 59,76000,1
274 | 60,42000,1
275 | 39,106000,1
276 | 57,26000,1
277 | 57,74000,1
278 | 38,71000,0
279 | 49,88000,1
280 | 52,38000,1
281 | 50,36000,1
282 | 59,88000,1
283 | 35,61000,0
284 | 37,70000,1
285 | 52,21000,1
286 | 48,141000,0
287 | 37,93000,1
288 | 37,62000,0
289 | 48,138000,1
290 | 41,79000,0
291 | 37,78000,1
292 | 39,134000,1
293 | 49,89000,1
294 | 55,39000,1
295 | 37,77000,0
296 | 35,57000,0
297 | 36,63000,0
298 | 42,73000,1
299 | 43,112000,1
300 | 45,79000,0
301 | 46,117000,1
302 | 58,38000,1
303 | 48,74000,1
304 | 37,137000,1
305 | 37,79000,1
306 | 40,60000,0
307 | 42,54000,0
308 | 51,134000,0
309 | 47,113000,1
310 | 36,125000,1
311 | 38,50000,0
312 | 42,70000,0
313 | 39,96000,1
314 | 38,50000,0
315 | 49,141000,1
316 | 39,79000,0
317 | 39,75000,1
318 | 54,104000,1
319 | 35,55000,0
320 | 45,32000,1
321 | 36,60000,0
322 | 52,138000,1
323 | 53,82000,1
324 | 41,52000,0
325 | 48,30000,1
326 | 48,131000,1
327 | 41,60000,0
328 | 41,72000,0
329 | 42,75000,0
330 | 36,118000,1
331 | 47,107000,1
332 | 38,51000,0
333 | 48,119000,1
334 | 42,65000,0
335 | 40,65000,0
336 | 57,60000,1
337 | 36,54000,0
338 | 58,144000,1
339 | 35,79000,0
340 | 38,55000,0
341 | 39,122000,1
342 | 53,104000,1
343 | 35,75000,0
344 | 38,65000,0
345 | 47,51000,1
346 | 47,105000,1
347 | 41,63000,0
348 | 53,72000,1
349 | 54,108000,1
350 | 39,77000,0
351 | 38,61000,0
352 | 38,113000,1
353 | 37,75000,0
354 | 42,90000,1
355 | 37,57000,0
356 | 36,99000,1
357 | 60,34000,1
358 | 54,70000,1
359 | 41,72000,0
360 | 40,71000,1
361 | 42,54000,0
362 | 43,129000,1
363 | 53,34000,1
364 | 47,50000,1
365 | 42,79000,0
366 | 42,104000,1
367 | 59,29000,1
368 | 58,47000,1
369 | 46,88000,1
370 | 38,71000,0
371 | 54,26000,1
372 | 60,46000,1
373 | 60,83000,1
374 | 39,73000,0
375 | 59,130000,1
376 | 37,80000,0
377 | 46,32000,1
378 | 46,74000,0
379 | 42,53000,0
380 | 41,87000,1
381 | 58,23000,1
382 | 42,64000,0
383 | 48,33000,1
384 | 44,139000,1
385 | 49,28000,1
386 | 57,33000,1
387 | 56,60000,1
388 | 49,39000,1
389 | 39,71000,0
390 | 47,34000,1
391 | 48,35000,1
392 | 48,33000,1
393 | 47,23000,1
394 | 45,45000,1
395 | 60,42000,1
396 | 39,59000,0
397 | 46,41000,1
398 | 51,23000,1
399 | 50,20000,1
400 | 36,33000,0
401 | 49,36000,1
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Note: LuciferML is now deprecated and is being extended as [ANAI](https://github.com/Revca-ANAI/ANAI).
2 |
3 |

4 |
5 | # LuciferML a Semi-Automated Machine Learning Library by d4rk-lucif3r
6 |
7 | [](https://pepy.tech/project/lucifer-ml)
8 | [](https://pepy.tech/project/lucifer-ml)
9 | 
10 |
11 | ## About
12 |
13 | The LuciferML is a Semi-Automated Machine Learning Python Library that works with tabular data. It is designed to save time while doing data analysis. It will help you right from data preprocessing to Data Prediction.
14 |
15 | ### The LuciferML will help you with
16 |
17 | 1. Preprocessing Data:
18 | - Encoding
19 | - Splitting
20 | - Scaling
21 | - Dimensionality Reduction
22 | - Resampling
23 | 2. Trying many different machine learning models with hyperparameter tuning,
24 |
25 | ## Installation
26 |
27 | pip install lucifer-ml
28 |
29 | ## Available Preprocessing Techniques
30 |
31 | 1) Skewness Correction
32 |
33 | Takes Pandas Dataframe as input. Transforms each column in dataset except the columns given as an optional parameter.
34 | Returns Transformed Data.
35 |
36 | Example:
37 |
38 | 1) All Columns
39 |
40 | from luciferml.preprocessing import Preprocess as pp
41 | import pandas as pd
42 | dataset = pd.read_csv('/examples/Social_Network_Ads.csv')
43 | prep = pp(dataset, dataset.columns)
44 | dataset = prep.skewcorrect(dataset)
45 |
46 | 2) Except column/columns
47 |
48 | from luciferml.preprocessing import Preprocess as pp
49 | import pandas as pd
50 | dataset = pd.read_csv('/examples/Social_Network_Ads.csv')
51 | prep = pp(dataset, dataset.columns, except_columns=['Purchased'])
52 | dataset = prep.skewcorrect()
53 |
54 | More about Preprocessing [here](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Preprocessing.md)
55 |
56 | ## Available Modelling Techniques
57 |
58 | 1) Classification
59 |
60 | Available Models for Classification
61 |
62 | - 'lr' : 'Logistic Regression',
63 | - 'sgd' : 'Stochastic Gradient Descent',
64 | - 'perc': 'Perceptron',
65 | - 'pass': 'Passive Aggressive Classifier',
66 | - 'ridg': 'Ridge Classifier',
67 | - 'svm' : 'Support Vector Machine',
68 | - 'knn' : 'K-Nearest Neighbours',
69 | - 'dt' : 'Decision Trees',
70 | - 'nb' : 'Naive Bayes',
71 | - 'rfc' : 'Random Forest Classifier',
72 | - 'gbc' : 'Gradient Boosting Classifier',
73 | - 'ada' : 'AdaBoost Classifier',
74 | - 'bag' : 'Bagging Classifier',
75 | - 'extc': 'Extra Trees Classifier',
76 | - 'lgbm': 'LightGBM Classifier',
77 | - 'cat' : 'CatBoost Classifier',
78 | - 'xgb' : 'XGBoost Classifier',
79 | - 'ann' : 'Multilayer Perceptron Classifier',
80 | - 'all' : 'Applies all above classifiers'
81 |
82 | Example:
83 |
84 | from luciferml.supervised.classification import Classification
85 | dataset = pd.read_csv('Social_Network_Ads.csv')
86 | X = dataset.iloc[:, :-1]
87 | y = dataset.iloc[:, -1]
88 | classifier = Classification(predictor = ['lr'])
89 | classifier.fit(X, y)
90 | result = classifier.result()
91 |
92 | More About [Classification](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Classification.md)
93 |
94 | 2) Regression
95 |
96 | Available Models for Regression
97 |
98 | - 'lin' : 'Linear Regression',
99 | - 'sgd' : 'Stochastic Gradient Descent Regressor',
100 | - 'elas': 'Elastic Net Regressot',
101 | - 'krr' : 'Kernel Ridge Regressor',
102 | - 'br' : 'Bayesian Ridge Regressor',
103 | - 'svr' : 'Support Vector Regressor',
104 | - 'knr' : 'K-Nearest Regressor',
105 | - 'dt' : 'Decision Trees',
106 | - 'rfr' : 'Random Forest Regressor',
107 | - 'gbr' : 'Gradient Boost Regressor',
108 | - 'ada' : 'AdaBoost Regressor',
109 | - 'bag' : 'Bagging Regressor',
110 | - 'extr': 'Extra Trees Regressor',
111 | - 'lgbm': 'LightGBM Regressor',
112 | - 'xgb' : 'XGBoost Regressor',
113 | - 'cat' : 'Catboost Regressor',
114 | - 'ann' : 'Multilayer Perceptron Regressor',
115 | - 'all' : 'Applies all above regressors'
116 |
117 | Example:
118 |
119 | from luciferml.supervised.regression import Regression
120 | dataset = pd.read_excel('examples\Folds5x2_pp.xlsx')
121 | X = dataset.iloc[:, :-1]
122 | y = dataset.iloc[:, -1]
123 | regressor = Regression(predictor = ['lin'])
124 | regressor.fit(X, y)
125 | result = regressor.result()
126 |
127 | More about Regression [here](https://github.com/d4rk-lucif3r/LuciferML/blob/master/luciferml/supervised/README/Regression.md)
128 |
129 | ## Hyperparameter Tuning
130 |
131 | LuciferML is powered by [Optuna](https://github.com/optuna/optuna) for Hyperparam tuning. Just add "tune = True" in either Regressor or Classifier it will start tuning the model/s with Optuna.
132 |
133 | ## Persistence
134 |
135 | LuciferML's model can be saved as a pickle file. It will save both the model and the scaler to the pickle file.
136 |
137 |
138 | - Saving
139 |
140 | Ex:
141 | regressor.save([, ])
142 |
143 | A new LuciferML Object can be loaded as well by specifying path of model and scaler
144 |
145 | - Loading
146 |
147 | Ex:
148 | regressor = Regression(path = [, ])
149 |
150 | These are applicable for both Classification and Regression.
151 |
152 | ## Examples
153 |
154 | Please refer to more examples [here](https://github.com/d4rk-lucif3r/LuciferML/blob/master/examples/example.ipynb)
155 |
156 | ---
157 |
158 | ## [To-Do's](https://github.com/d4rk-lucif3r/LuciferML/issues/10)
159 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/preprocesser.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | import seaborn as sns
6 | import shap
7 | from imblearn.over_sampling import SMOTE
8 | from luciferml.supervised.utils.configs import *
9 | from sklearn.compose import ColumnTransformer
10 | from sklearn.decomposition import PCA, KernelPCA
11 | from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
12 | from sklearn.inspection import permutation_importance
13 | from sklearn.metrics import confusion_matrix
14 | from sklearn.model_selection import train_test_split
15 | from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
16 | from colorama import Fore
17 |
18 |
19 | class PreProcesser:
20 | def data_preprocess(
21 | self, features, labels, test_size, random_state, smote, k_neighbors
22 | ):
23 | try:
24 | if smote == "y":
25 | sm = SMOTE(k_neighbors=k_neighbors, random_state=random_state)
26 | features, labels = sm.fit_resample(features, labels)
27 | # Splitting ---------------------------------------------------------------------
28 | X_train, X_val, y_train, y_val = train_test_split(
29 | features, labels, test_size=test_size, random_state=random_state
30 | )
31 | # Scaling ---------------------------------------------------------------------
32 | sc = StandardScaler()
33 | X_train = sc.fit_transform(X_train)
34 | X_val = sc.transform(X_val)
35 | return (X_train, X_val, y_train, y_val, sc)
36 | except Exception as error:
37 | print(Fore.RED + "Preprocessing Failed with error: ", error, "\n")
38 |
39 | def confusion_matrix(self, y_pred, y_val):
40 | """
41 | Takes Predicted data and Validation data as input and prepares and plots Confusion Matrix.
42 | """
43 | try:
44 | cm = confusion_matrix(y_val, y_pred)
45 | ax = plt.subplot()
46 | sns.heatmap(cm, annot=True, fmt="g", ax=ax)
47 | ax.set_xlabel("Predicted labels")
48 | ax.set_ylabel("True labels")
49 | ax.set_title("Confusion Matrix")
50 | ax.xaxis.set_ticklabels(np.unique(y_val))
51 | ax.yaxis.set_ticklabels(np.unique(y_val))
52 | plt.show()
53 | except Exception as error:
54 | print(
55 | Fore.RED + "Building Confusion Matrix Failed with error :", error, "\n"
56 | )
57 |
58 | def dimensionality_reduction(
59 | self,
60 | lda,
61 | pca,
62 | X_train,
63 | X_val,
64 | y_train,
65 | n_components_lda,
66 | n_components_pca,
67 | pca_kernel,
68 | start,
69 | ):
70 | """
71 | Performs Dimensionality Reduction on Training and Validation independent variables.
72 | """
73 | try:
74 | if lda == "y":
75 | lda = LDA(n_components=n_components_lda)
76 | X_train = lda.fit_transform(X_train, y_train)
77 | X_val = lda.transform(X_val)
78 | if pca == "y" and not lda == "y":
79 | if not pca_kernel == "linear":
80 | try:
81 |
82 | kpca = KernelPCA(
83 | n_components=n_components_pca, kernel=pca_kernel
84 | )
85 | X_train = kpca.fit_transform(X_train)
86 | X_val = kpca.transform(X_val)
87 | except MemoryError as error:
88 | print(error)
89 | end = time.time()
90 | print("Time Elapsed :", end - start)
91 | return
92 |
93 | elif pca_kernel == "linear":
94 | pca = PCA(n_components=n_components_pca)
95 | X_train = pca.fit_transform(X_train)
96 | X_val = pca.transform(X_val)
97 | else:
98 | print("Un-identified PCA Kernel\n")
99 | return
100 | return (X_train, X_val)
101 | except Exception as error:
102 | print(
103 | Fore.RED + "Dimensionality Reduction Failed with error :", error, "\n"
104 | )
105 | return (X_train, X_val)
106 |
107 | def encoder(self, features, labels):
108 | """
109 | Takes features and labels as arguments and encodes features using onehot encoding and labels with label encoding.
110 | Returns Encoded Features and Labels.
111 | """
112 | try:
113 | cat_features = [
114 | i for i in features.columns if features.dtypes[i] == "object"
115 | ]
116 | if len(cat_features) >= 1:
117 | index = []
118 | for i in range(0, len(cat_features)):
119 | index.append(features.columns.get_loc(cat_features[i]))
120 | ct = ColumnTransformer(
121 | transformers=[("encoder", OneHotEncoder(), index)],
122 | remainder="passthrough",
123 | )
124 | print("Encoding Features [*]\n")
125 | features = np.array(ct.fit_transform(features))
126 | if labels.dtype == "O":
127 | le = LabelEncoder()
128 | labels = le.fit_transform(labels)
129 | return (features, labels)
130 | except Exception as error:
131 | print(Fore.RED + "Encoding Failed with error :", error)
132 |
133 | def permutational_feature_imp(self, features, X_test, y_test, model):
134 | perm_importance = permutation_importance(model, X_test, y_test)
135 | sorted_idx = perm_importance.importances_mean.argsort()
136 | plt.barh(
137 | features.columns[sorted_idx], perm_importance.importances_mean[sorted_idx]
138 | )
139 | plt.xlabel("Feature Importance")
140 |
141 | def shap_feature_imp(self, features, X_train, model, *args, **kwargs):
142 | explainer = shap.TreeExplainer(model)
143 | shap_values = explainer.shap_values(X_train)
144 | shap.summary_plot(
145 | shap_values,
146 | X_train,
147 | feature_names=features.columns,
148 | plot_type="bar",
149 | *args,
150 | **kwargs
151 | )
152 | shap.summary_plot(
153 | shap_values, X_train, feature_names=features.columns, *args, **kwargs
154 | )
155 | for i in range(len(features.columns)):
156 | shap.dependence_plot(
157 | i, shap_values, X_train, feature_names=features.columns, *args, **kwargs
158 | )
159 |
--------------------------------------------------------------------------------
/luciferml/preprocessing.py:
--------------------------------------------------------------------------------
1 | import time
2 | from collections import Counter
3 |
4 | import matplotlib.pyplot as plt
5 | import numpy as np
6 | import pandas as pd
7 | import seaborn as sns
8 | from colorama import Fore
9 | from IPython.display import display
10 | from scipy.special import boxcox1p
11 | from scipy.stats import norm, probplot, skew
12 |
13 | from luciferml.supervised.utils.configs import intro
14 |
15 |
16 | class Preprocess:
17 |
18 | def __init__(self, dataset, columns, except_columns=[]):
19 | self.__dataset = dataset
20 | self.__columns = columns
21 | self.__except_columns = except_columns
22 |
23 | def __plotter(self, name, text, color):
24 | plt.figure(figsize=(20, 10))
25 | plt.subplot(1, 2, 1)
26 | sns.distplot(
27 | self.__dataset[name],
28 | fit=norm,
29 | color=color,
30 | label="Skewness: %.2f" % (self.__dataset[name].skew()),
31 | )
32 | plt.title(
33 | name.capitalize()
34 | + " Distplot for {} {} Skewness Transformation".format(name, text),
35 | color="black",
36 | )
37 | plt.legend()
38 | plt.subplot(1, 2, 2)
39 |
40 | probplot(self.__dataset[name], plot=plt)
41 | plt.show()
42 |
43 | def __skewcheck(self):
44 | numeric_feats = self.__dataset.dtypes[self.__dataset.dtypes !=
45 | "object"].index
46 | if not len(self.__except_columns) == 0:
47 | if len(self.__except_columns) > len(numeric_feats):
48 | numeric_feats = set(self.__except_columns) - set(numeric_feats)
49 | else:
50 | numeric_feats = set(numeric_feats) - set(self.__except_columns)
51 | skewed_feats = (
52 | self.__dataset[numeric_feats]
53 | .apply(lambda x: skew(x.dropna()))
54 | .sort_values(ascending=False)
55 | )
56 | print(Fore.GREEN + "\nSkewness in numerical features: \n")
57 | skewness = pd.DataFrame(skewed_feats, columns=["Skewness"])
58 | display(skewness)
59 | skew_dict = dict(skewness["Skewness"])
60 | skewed_features = skewness.index
61 | return (skewed_features, skew_dict)
62 |
63 | def skewcorrect(self) -> pd.DataFrame:
64 | """
65 | Plots distplot and probability plot for non-normalized data and after normalizing the provided data.
66 | Normalizes data using boxcox normalization
67 |
68 | :returns: Scaled Dataset
69 | :rtype: pd.DataFrame
70 |
71 | Example:
72 |
73 | 1) All Columns
74 |
75 | from luciferml.preprocessing import Preprocess as pp
76 |
77 | import pandas as pd
78 |
79 | dataset = pd.read_csv('/examples/Social_Network_Ads.csv')
80 | prep = pp(dataset, dataset.columns)
81 | dataset = prep.skewcorrect(dataset)
82 |
83 | 2) Except column/columns
84 |
85 | from luciferml.preprocessing import Preprocess as pp
86 |
87 | import pandas as pd
88 |
89 | dataset = pd.read_csv('/examples/Social_Network_Ads.csv')
90 | prep = pp(dataset, dataset.columns, except_columns=['Purchased'])
91 | dataset = prep.skewcorrect()
92 |
93 |
94 | """
95 | try:
96 | start = time.time()
97 | print(Fore.MAGENTA + intro, "\n")
98 | print(Fore.GREEN + "Started LuciferML [", "\u2713", "]\n")
99 | if not isinstance(self.__dataset, pd.DataFrame):
100 | print(
101 | Fore.RED + "TypeError: This Function expects Pandas Dataframe but {}".format(
102 | type(self.__dataset)
103 | ),
104 | " is given \n",
105 | )
106 | end = time.time()
107 | print(Fore.GREEN + "Elapsed Time: ", end - start, "seconds\n")
108 | return
109 |
110 | (skewed_features, skew_dict) = self.__skewcheck()
111 | for column_name in skewed_features:
112 | lam = 0
113 | (mu, sigma) = norm.fit(self.__dataset[column_name])
114 | print(
115 | Fore.CYAN +
116 | "Skewness Before Transformation for {}: ".format(
117 | column_name),
118 | self.__dataset[column_name].skew(),
119 | "\n",
120 | )
121 | print(
122 | Fore.CYAN + "Mean before Transformation for {} : {}, Standard Deviation before Transformation for {} : {}".format(
123 | column_name.capitalize(), mu, column_name.capitalize(), sigma
124 | ),
125 | "\n",
126 | )
127 | self.__plotter(
128 | column_name, "Before", "lightcoral")
129 | try:
130 | if skew_dict[column_name] > 0.75:
131 | lam = 0.15
132 | self.__dataset[column_name] = boxcox1p(
133 | self.__dataset[column_name], lam)
134 | print(
135 | Fore.GREEN +
136 | "Skewness After Transformation for {}: ".format(
137 | column_name),
138 | self.__dataset[column_name].skew(),
139 | "\n",
140 | )
141 | (mu, sigma) = norm.fit(self.__dataset[column_name])
142 | print(
143 | Fore.GREEN + "Mean before Transformation for {} : {}, Standard Deviation before Transformation for {} : {}".format(
144 | column_name.capitalize(),
145 | mu,
146 | column_name.capitalize(),
147 | sigma,
148 | ),
149 | "\n",
150 | )
151 | self.__plotter(
152 | column_name, "After", "orange")
153 | except Exception as error:
154 | print(
155 | Fore.RED + "\nPlease check your dataset's column :",
156 | column_name,
157 | "Raised Error: ",
158 | error,
159 | "\n",
160 | )
161 | pass
162 | end = time.time()
163 | print(Fore.GREEN + "Elapsed Time: ", end - start, "seconds\n")
164 | return self.__dataset
165 |
166 | except Exception as error:
167 | print(Fore.RED + "Skewness Correction Failed with error : ", error, "\n")
168 |
169 | def detect_outliers(self):
170 | """
171 | This function takes dataset and columns as input and finds Q1, Q3 and IQR for that list of column
172 | Detects the outlier and it index and stores them in a list.
173 | Then it creates as counter object with that list and stores it
174 | in Multiple Outliers list if the value of outlier is greater than 1.5
175 |
176 | Ex:
177 | 1) For printing no. of outliers.
178 | print("number of outliers detected --> ",
179 | len(dataset.loc[detect_outliers(dataset, dataset.columns[:-1])]))
180 | 2) Printing rows and columns collecting the outliers
181 | dataset.loc[detect_outliers(dataset.columns[:-1])]
182 | 3) Dropping those detected outliers
183 | dataset = dataset.drop(detect_outliers(dataset.columns[:-1]),axis = 0).reset_index(drop = True)
184 | """
185 | outlier_indices = []
186 | for column in self.__columns:
187 | Q1 = np.percentile(self.__dataset[column], 25)
188 | Q3 = np.percentile(self.__dataset[column], 75)
189 | IQR = Q3 - Q1
190 | outlier_step = IQR * 1.5
191 | outlier_list_col = self.__dataset[(self.__dataset[column] < Q1 - outlier_step)
192 | | (self.__dataset[column] > Q3 + outlier_step)].index
193 | outlier_indices.extend(outlier_list_col)
194 | outlier_indices = Counter(outlier_indices)
195 | multiple_outliers = list(
196 | i for i, v in outlier_indices.items() if v > 1.5)
197 | return multiple_outliers
198 |
199 | def preprocess(self):
200 |
201 | display(self.__datasetdescribe().T.style.bar(
202 | subset=['mean'],
203 | color='#606ff2').background_gradient(
204 | subset=['std'], cmap='PuBu').background_gradient(subset=['50%'], cmap='PuBu'))
205 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/predictors.py:
--------------------------------------------------------------------------------
1 | from tkinter import N
2 | from catboost import CatBoostClassifier, CatBoostRegressor
3 | from colorama import Fore
4 | from lightgbm import LGBMClassifier, LGBMRegressor
5 | from luciferml.supervised.utils.tuner.optuna.objectives.classification_objectives import (
6 | ClassificationObjectives,
7 | )
8 | from luciferml.supervised.utils.tuner.optuna.objectives.regression_objectives import (
9 | RegressionObjectives,
10 | )
11 | from sklearn.ensemble import (
12 | AdaBoostClassifier,
13 | AdaBoostRegressor,
14 | BaggingClassifier,
15 | BaggingRegressor,
16 | ExtraTreesClassifier,
17 | ExtraTreesRegressor,
18 | GradientBoostingClassifier,
19 | GradientBoostingRegressor,
20 | RandomForestClassifier,
21 | RandomForestRegressor,
22 | )
23 | from sklearn.kernel_ridge import KernelRidge
24 | from sklearn.linear_model import (
25 | BayesianRidge,
26 | ElasticNet,
27 | LinearRegression,
28 | LogisticRegression,
29 | PassiveAggressiveClassifier,
30 | Perceptron,
31 | RidgeClassifier,
32 | SGDClassifier,
33 | SGDRegressor,
34 | )
35 | from sklearn.naive_bayes import GaussianNB
36 | from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
37 | from sklearn.neural_network import MLPClassifier, MLPRegressor
38 | from sklearn.svm import SVC, SVR
39 | from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
40 | from xgboost import XGBClassifier, XGBRegressor
41 |
42 |
43 | def classification_predictor(
44 | predictor,
45 | params,
46 | X_train,
47 | y_train,
48 | cv_folds,
49 | random_state,
50 | metric,
51 | mode="single",
52 | verbose=False,
53 | lgbm_objective="binary",
54 | ):
55 | """
56 | Takes Predictor string , parameters , Training and Validation set and Returns a classifier for the Choosen Predictor.
57 | """
58 | try:
59 | objective = ClassificationObjectives(
60 | X_train,
61 | y_train,
62 | cv=cv_folds,
63 | random_state=random_state,
64 | metric=metric,
65 | lgbm_objective=lgbm_objective,
66 | )
67 | if predictor == "lr":
68 | if mode == "single":
69 | print(
70 | Fore.YELLOW + "Training Logistic Regression on Training Set [*]\n"
71 | )
72 | classifier = LogisticRegression(**params)
73 | objective_to_be_tuned = objective.lr_classifier_objective
74 |
75 | elif predictor == "sgd":
76 | if mode == "single":
77 | print(
78 | Fore.YELLOW
79 | + "Training Stochastic Gradient Descent on Training Set [*]\n"
80 | )
81 | classifier = SGDClassifier(**params)
82 | objective_to_be_tuned = objective.sgd_classifier_objective
83 |
84 | elif predictor == "perc":
85 | if mode == "single":
86 | print(Fore.YELLOW + "Training Perceptron on Training Set [*]\n")
87 | classifier = Perceptron(**params)
88 | objective_to_be_tuned = objective.perc_classifier_objective
89 |
90 | elif predictor == "pass":
91 | if mode == "single":
92 | print(Fore.YELLOW + "Training Passive Aggressive on Training Set [*]\n")
93 | classifier = PassiveAggressiveClassifier(**params)
94 | objective_to_be_tuned = objective.pass_classifier_objective
95 |
96 | elif predictor == "ridg":
97 | if mode == "single":
98 | print(Fore.YELLOW + "Training Ridge Classifier on Training Set [*]\n")
99 | classifier = RidgeClassifier(**params)
100 | objective_to_be_tuned = objective.ridg_classifier_objective
101 |
102 | elif predictor == "svm":
103 | if mode == "single":
104 | print(
105 | Fore.YELLOW
106 | + "Training Support Vector Machine on Training Set [*]\n"
107 | )
108 | classifier = SVC(**params)
109 | objective_to_be_tuned = objective.svm_classifier_objective
110 |
111 | elif predictor == "knn":
112 | if mode == "single":
113 | print(
114 | Fore.YELLOW + "Training K-Nearest Neighbours on Training Set [*]\n"
115 | )
116 | classifier = KNeighborsClassifier(**params)
117 | objective_to_be_tuned = objective.knn_classifier_objective
118 |
119 | elif predictor == "dt":
120 | if mode == "single":
121 | print(
122 | Fore.YELLOW
123 | + "Training Decision Tree Classifier on Training Set [*]\n"
124 | )
125 | classifier = DecisionTreeClassifier(**params)
126 | objective_to_be_tuned = objective.dt_classifier_objective
127 |
128 | elif predictor == "nb":
129 | if mode == "single":
130 | print(
131 | Fore.YELLOW
132 | + "Training Naive Bayes Classifier on Training Set [*]\n"
133 | )
134 | classifier = GaussianNB(**params)
135 | objective_to_be_tuned = None
136 |
137 | elif predictor == "rfc":
138 | if mode == "single":
139 | print(
140 | Fore.YELLOW
141 | + "Training Random Forest Classifier on Training Set [*]\n"
142 | )
143 | classifier = RandomForestClassifier(**params)
144 | objective_to_be_tuned = objective.rfc_classifier_objective
145 |
146 | elif predictor == "gbc":
147 | if mode == "single":
148 | print(
149 | Fore.YELLOW
150 | + "Training Gradient Boosting Classifier on Training Set [*]\n"
151 | )
152 | classifier = GradientBoostingClassifier(**params)
153 | objective_to_be_tuned = objective.gbc_classifier_objective
154 |
155 | elif predictor == "ada":
156 | if mode == "single":
157 | print(
158 | Fore.YELLOW + "Training AdaBoost Classifier on Training Set [*]\n"
159 | )
160 | classifier = AdaBoostClassifier(**params)
161 | objective_to_be_tuned = objective.ada_classifier_objective
162 |
163 | elif predictor == "bag":
164 | if mode == "single":
165 | print(Fore.YELLOW + "Training Bagging Classifier on Training Set [*]\n")
166 | classifier = BaggingClassifier(**params)
167 | objective_to_be_tuned = objective.bag_classifier_objective
168 |
169 | elif predictor == "extc":
170 | if mode == "single":
171 | print(
172 | Fore.YELLOW
173 | + "Training Extra Trees Classifier on Training Set [*]\n"
174 | )
175 | classifier = ExtraTreesClassifier(**params)
176 | objective_to_be_tuned = objective.extc_classifier_objective
177 |
178 | elif predictor == "lgbm":
179 | if mode == "single":
180 | print(Fore.YELLOW + "Training LightGBM on Training Set [*]\n")
181 | classifier = LGBMClassifier(**params)
182 | objective_to_be_tuned = objective.lgbm_classifier_objective
183 |
184 | elif predictor == "cat":
185 | if mode == "single":
186 | print(Fore.YELLOW + "Training CatBoostClassifier on Training Set [*]\n")
187 | params["verbose"] = verbose
188 | classifier = CatBoostClassifier(**params)
189 | params.pop("verbose")
190 | objective_to_be_tuned = objective.cat_classifier_objective
191 |
192 | elif predictor == "xgb":
193 | if mode == "single":
194 | print(Fore.YELLOW + "Training XGBClassifier on Training Set [*]\n")
195 | if verbose:
196 | params["verbosity"] = 2
197 | if not verbose:
198 | params["verbosity"] = 0
199 |
200 | classifier = XGBClassifier(**params)
201 | params.pop("verbosity")
202 | objective_to_be_tuned = objective.xgb_classifier_objective
203 |
204 | elif predictor == "ann":
205 | classifier = MLPClassifier(**params)
206 | objective_to_be_tuned = objective.mlp_classifier_objective
207 | return (classifier, objective_to_be_tuned)
208 | except Exception as error:
209 | print(Fore.RED + "Model Build Failed with error :", error, "\n")
210 |
211 |
212 | def regression_predictor(
213 | predictor,
214 | params,
215 | X_train,
216 | y_train,
217 | cv_folds,
218 | random_state,
219 | metric,
220 | mode="single",
221 | verbose=False,
222 | ):
223 | """
224 | Takes Predictor string , parameters , Training and Validation set and Returns a regressor for the Choosen Predictor.
225 | """
226 | try:
227 | objective = RegressionObjectives(
228 | X_train, y_train, cv=cv_folds, random_state=random_state, metric=metric
229 | )
230 | if predictor == "lin":
231 | if mode == "single":
232 | print(Fore.YELLOW + "Training Linear Regression on Training Set [*]\n")
233 | regressor = LinearRegression(**params)
234 | objective_to_be_tuned = objective.lin_regressor_objective
235 | elif predictor == "sgd":
236 | if mode == "single":
237 | print(
238 | "Training Stochastic Gradient Descent Regressor on Training Set [*]\n"
239 | )
240 | regressor = SGDRegressor(**params)
241 | objective_to_be_tuned = objective.sgd_regressor_objective
242 | elif predictor == "krr":
243 | if mode == "single":
244 | print(
245 | Fore.YELLOW
246 | + "Training Kernel Ridge Regressor on Training Set [*]\n"
247 | )
248 | regressor = KernelRidge(**params)
249 | objective_to_be_tuned = objective.krr_regressor_objective
250 | elif predictor == "elas":
251 | if mode == "single":
252 | print(
253 | Fore.YELLOW + "Training ElasticNet Regressor on Training Set [*]\n"
254 | )
255 | regressor = ElasticNet(**params)
256 | objective_to_be_tuned = objective.elas_regressor_objective
257 | elif predictor == "br":
258 | if mode == "single":
259 | print(
260 | Fore.YELLOW
261 | + "Training BayesianRidge Regressor on Training Set [*]\n"
262 | )
263 | regressor = BayesianRidge(**params)
264 | objective_to_be_tuned = objective.br_regressor_objective
265 | elif predictor == "svr":
266 | if mode == "single":
267 | print(
268 | Fore.YELLOW
269 | + "Training Support Vector Machine on Training Set [*]\n"
270 | )
271 | regressor = SVR(**params)
272 | objective_to_be_tuned = objective.svr_regressor_objective
273 | elif predictor == "knr":
274 | if mode == "single":
275 | print(
276 | Fore.YELLOW + "Training KNeighbors Regressor on Training Set [*]\n"
277 | )
278 | regressor = KNeighborsRegressor(**params)
279 | objective_to_be_tuned = objective.knr_regressor_objective
280 | elif predictor == "dt":
281 | if mode == "single":
282 | print(
283 | Fore.YELLOW
284 | + "Training Decision Tree regressor on Training Set [*]\n"
285 | )
286 | regressor = DecisionTreeRegressor(**params)
287 | objective_to_be_tuned = objective.dt_regressor_objective
288 | elif predictor == "rfr":
289 | if mode == "single":
290 | print(
291 | Fore.YELLOW
292 | + "Training Random Forest regressor on Training Set [*]\n"
293 | )
294 | regressor = RandomForestRegressor(**params)
295 | objective_to_be_tuned = objective.rfr_regressor_objective
296 | elif predictor == "gbr":
297 | if mode == "single":
298 | print(
299 | Fore.YELLOW
300 | + "Training Gradient Boosting Regressor on Training Set [*]\n"
301 | )
302 | regressor = GradientBoostingRegressor(**params)
303 | objective_to_be_tuned = objective.gbr_regressor_objective
304 |
305 | elif predictor == "ada":
306 | if mode == "single":
307 | print(Fore.YELLOW + "Training AdaBoost Regressor on Training Set [*]\n")
308 | regressor = AdaBoostRegressor(**params)
309 | objective_to_be_tuned = objective.ada_regressor_objective
310 | elif predictor == "bag":
311 | if mode == "single":
312 | print(Fore.YELLOW + "Training Bagging Regressor on Training Set [*]\n")
313 | regressor = BaggingRegressor(**params)
314 | objective_to_be_tuned = objective.bag_regressor_objective
315 | elif predictor == "extr":
316 | if mode == "single":
317 | print(
318 | Fore.YELLOW + "Training Extra Trees Regressor on Training Set [*]\n"
319 | )
320 | regressor = ExtraTreesRegressor(**params)
321 | objective_to_be_tuned = objective.extr_regressor_objective
322 | elif predictor == "xgb":
323 | if mode == "single":
324 | print(Fore.YELLOW + "Training XGBregressor on Training Set [*]\n")
325 | regressor = XGBRegressor(**params)
326 | objective_to_be_tuned = objective.xgb_regressor_objective
327 | elif predictor == "lgbm":
328 | if mode == "single":
329 | print(Fore.YELLOW + "Training LGBMRegressor on Training Set [*]\n")
330 | regressor = LGBMRegressor(**params)
331 | objective_to_be_tuned = objective.lgbm_regressor_objective
332 | elif predictor == "cat":
333 | if mode == "single":
334 | print(Fore.YELLOW + "Training CatBoost Regressor on Training Set [*]\n")
335 | params["verbose"] = verbose
336 | regressor = CatBoostRegressor(**params)
337 | params.pop("verbose")
338 | objective_to_be_tuned = objective.cat_regressor_objective
339 | elif predictor == "ann":
340 | if mode == "single":
341 | print(
342 | Fore.YELLOW
343 | + "Training Multi Layered Perceptron on Training Set [*]\n"
344 | )
345 | regressor = MLPRegressor(**params)
346 | objective_to_be_tuned = objective.mlp_regressor_objective
347 | return (regressor, objective_to_be_tuned)
348 | except Exception as error:
349 | print(Fore.RED + "Model Build Failed with error :", error, "\n")
350 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/tuner/optuna/objectives/regression_objectives.py:
--------------------------------------------------------------------------------
1 | from catboost import CatBoostRegressor
2 | from lightgbm import LGBMRegressor
3 | from sklearn.ensemble import (
4 | AdaBoostRegressor,
5 | BaggingRegressor,
6 | ExtraTreesRegressor,
7 | GradientBoostingRegressor,
8 | RandomForestRegressor,
9 | )
10 | from sklearn.kernel_ridge import KernelRidge
11 | from sklearn.linear_model import (
12 | BayesianRidge,
13 | ElasticNet,
14 | LinearRegression,
15 | SGDRegressor,
16 | )
17 | from sklearn.model_selection import cross_val_score
18 | from sklearn.neighbors import KNeighborsRegressor
19 | from sklearn.neural_network import MLPRegressor
20 | from sklearn.svm import SVR
21 | from sklearn.tree import DecisionTreeRegressor
22 | from xgboost import XGBRegressor
23 |
24 |
25 | class RegressionObjectives:
26 | def __init__(self, X, y, cv=5, random_state=42, metric="r2"):
27 | self.metric = metric
28 | self.cv = cv
29 | self.X = X
30 | self.y = y
31 | self.random_state = random_state
32 |
33 | def lin_regressor_objective(self, trial):
34 | param = {
35 | "fit_intercept": trial.suggest_categorical("fit_intercept", [True, False]),
36 | "copy_X": trial.suggest_categorical("copy_X", [True, False]),
37 | }
38 | regressor = LinearRegression(**param, n_jobs=-1)
39 | scores = cross_val_score(
40 | regressor, self.X, self.y, cv=self.cv, scoring=self.metric
41 | )
42 | return scores.mean()
43 |
44 | def sgd_regressor_objective(self, trial):
45 | param = {
46 | "loss": trial.suggest_categorical(
47 | "loss", ["squared_loss", "huber", "epsilon_insensitive"]
48 | ),
49 | "penalty": trial.suggest_categorical(
50 | "penalty", ["none", "l2", "l1", "elasticnet"]
51 | ),
52 | "alpha": trial.suggest_float("alpha", 1e-10, 1e-3),
53 | "l1_ratio": trial.suggest_float("l1_ratio", 0.0, 1.0),
54 | "learning_rate": trial.suggest_categorical(
55 | "learning_rate", ["constant", "optimal", "invscaling", "adaptive"]
56 | ),
57 | "eta0": trial.suggest_float("eta0", 0.0, 1.0),
58 | "power_t": trial.suggest_float("power_t", 0.0, 1.0),
59 | "warm_start": trial.suggest_categorical("warm_start", [True, False]),
60 | "average": trial.suggest_categorical("average", [True, False]),
61 | "random_state": self.random_state,
62 | }
63 | regressor = SGDRegressor(**param)
64 | scores = cross_val_score(
65 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
66 | )
67 | return scores.mean()
68 |
69 | def krr_regressor_objective(self, trial):
70 | param = {
71 | "alpha": trial.suggest_loguniform("alpha", 1e-10, 1e-3),
72 | "kernel": trial.suggest_categorical("kernel", ["linear", "rbf"]),
73 | "degree": trial.suggest_int("degree", 1, 3),
74 | "gamma": trial.suggest_loguniform("gamma", 1e-10, 1e-3),
75 | "coef0": trial.suggest_loguniform("coef0", 1e-10, 1e-3),
76 | }
77 | regressor = KernelRidge(**param)
78 | scores = cross_val_score(
79 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
80 | )
81 | return scores.mean()
82 |
83 | def elas_regressor_objective(self, trial):
84 | param = {
85 | "alpha": trial.suggest_loguniform("alpha", 1e-10, 1e-3),
86 | "l1_ratio": trial.suggest_float("l1_ratio", 0.0, 1.0),
87 | "max_iter": trial.suggest_int("max_iter", 100, 1000),
88 | "selection": trial.suggest_categorical("selection", ["cyclic", "random"]),
89 | "tol": trial.suggest_loguniform("tol", 1e-10, 1e-3),
90 | "random_state": self.random_state,
91 | }
92 | regressor = ElasticNet(**param)
93 | scores = cross_val_score(
94 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
95 | )
96 | return scores.mean()
97 |
98 | def br_regressor_objective(self, trial):
99 | param = {
100 | "alpha_1": trial.suggest_loguniform("alpha_1", 1e-10, 1e-3),
101 | "alpha_2": trial.suggest_loguniform("alpha_2", 1e-10, 1e-3),
102 | "lambda_1": trial.suggest_loguniform("lambda_1", 1e-10, 1e-3),
103 | "lambda_2": trial.suggest_loguniform("lambda_2", 1e-10, 1e-3),
104 | "fit_intercept": trial.suggest_categorical("fit_intercept", [True, False]),
105 | "normalize": trial.suggest_categorical("normalize", [True, False]),
106 | "copy_X": trial.suggest_categorical("copy_X", [True, False]),
107 | }
108 | regressor = BayesianRidge(**param)
109 | scores = cross_val_score(
110 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
111 | )
112 | return scores.mean()
113 |
114 | def svr_regressor_objective(self, trial):
115 | param = {
116 | "C": trial.suggest_loguniform("C", 1e-10, 1e-3),
117 | "kernel": trial.suggest_categorical("kernel", ["linear", "rbf"]),
118 | "degree": trial.suggest_int("degree", 1, 3),
119 | "gamma": trial.suggest_loguniform("gamma", 1e-10, 1e-3),
120 | "coef0": trial.suggest_loguniform("coef0", 1e-10, 1e-3),
121 | "shrinking": trial.suggest_categorical("shrinking", [True, False]),
122 | "tol": trial.suggest_loguniform("tol", 1e-10, 1e-3),
123 | "cache_size": trial.suggest_loguniform("cache_size", 1e-10, 1e-3),
124 | "verbose": trial.suggest_categorical("verbose", [True, False]),
125 | "max_iter": trial.suggest_int("max_iter", 100, 1000),
126 | }
127 | regressor = SVR(**param)
128 | scores = cross_val_score(
129 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
130 | )
131 | return scores.mean()
132 |
133 | def knr_regressor_objective(self, trial):
134 | param = {
135 | "n_neighbors": trial.suggest_int("n_neighbors", 1, 10),
136 | "weights": trial.suggest_categorical("weights", ["uniform", "distance"]),
137 | "algorithm": trial.suggest_categorical(
138 | "algorithm", ["auto", "ball_tree", "kd_tree", "brute"]
139 | ),
140 | "leaf_size": trial.suggest_int("leaf_size", 1, 100),
141 | "p": trial.suggest_int("p", 1, 3),
142 | "n_jobs": -1,
143 | }
144 | regressor = KNeighborsRegressor(**param)
145 | scores = cross_val_score(
146 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
147 | )
148 | return scores.mean()
149 |
150 | def dt_regressor_objective(self, trial):
151 | param = {
152 | "criterion": trial.suggest_categorical(
153 | "criterion", ["mse", "friedman_mse", "mae"]
154 | ),
155 | "splitter": trial.suggest_categorical("splitter", ["best", "random"]),
156 | "max_depth": trial.suggest_int("max_depth", 1, 10),
157 | "min_samples_split": trial.suggest_int("min_samples_split", 2, 10),
158 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
159 | "min_weight_fraction_leaf": trial.suggest_loguniform(
160 | "min_weight_fraction_leaf", 1e-10, 1e-3
161 | ),
162 | "max_features": trial.suggest_categorical(
163 | "max_features", ["auto", "sqrt", "log2", None]
164 | ),
165 | "max_leaf_nodes": trial.suggest_int("max_leaf_nodes", 2, 10),
166 | "min_impurity_decrease": trial.suggest_loguniform(
167 | "min_impurity_decrease", 1e-10, 1e-3
168 | ),
169 | "random_state": self.random_state,
170 | }
171 | regressor = DecisionTreeRegressor(**param)
172 | scores = cross_val_score(
173 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
174 | )
175 | return scores.mean()
176 |
177 | def gbr_regressor_objective(self, trial):
178 | param = {
179 | "loss": trial.suggest_categorical(
180 | "loss", ["ls", "lad", "huber", "quantile"]
181 | ),
182 | "learning_rate": trial.suggest_loguniform("learning_rate", 1e-10, 1e-3),
183 | "n_estimators": trial.suggest_int("n_estimators", 10, 1000),
184 | "criterion": trial.suggest_categorical(
185 | "criterion", ["friedman_mse", "mae"]
186 | ),
187 | "max_depth": trial.suggest_int("max_depth", 1, 10),
188 | "min_samples_split": trial.suggest_int("min_samples_split", 2, 10),
189 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
190 | "min_weight_fraction_leaf": trial.suggest_loguniform(
191 | "min_weight_fraction_leaf", 1e-10, 1e-3
192 | ),
193 | "max_features": trial.suggest_categorical(
194 | "max_features", ["auto", "sqrt", "log2", None]
195 | ),
196 | "max_leaf_nodes": trial.suggest_int("max_leaf_nodes", 2, 10),
197 | "min_impurity_decrease": trial.suggest_loguniform(
198 | "min_impurity_decrease", 1e-10, 1e-3
199 | ),
200 | "random_state": self.random_state,
201 | }
202 | regressor = GradientBoostingRegressor(**param)
203 | scores = cross_val_score(
204 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
205 | )
206 | return scores.mean()
207 |
208 | def ada_regressor_objective(self, trial):
209 | param = {
210 | "learning_rate": trial.suggest_loguniform("learning_rate", 1e-10, 1e-3),
211 | "n_estimators": trial.suggest_int("n_estimators", 10, 1000),
212 | "loss": trial.suggest_categorical(
213 | "loss", ["linear", "square", "exponential"]
214 | ),
215 | "random_state": self.random_state,
216 | }
217 | regressor = AdaBoostRegressor(**param)
218 | scores = cross_val_score(
219 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
220 | )
221 | return scores.mean()
222 |
223 | def bag_regressor_objective(self, trial):
224 | param = {
225 | "n_estimators": trial.suggest_int("n_estimators", 10, 1000),
226 | "bootstrap_features": trial.suggest_categorical(
227 | "bootstrap_features", [True, False]
228 | ),
229 | "oob_score": trial.suggest_categorical("oob_score", [True, False]),
230 | "max_samples": trial.suggest_uniform("max_samples", 0.0, 1.0),
231 | "max_features": trial.suggest_uniform("max_features", 0.0, 1.0),
232 | "random_state": self.random_state,
233 | "n_jobs": -1,
234 | }
235 | regressor = BaggingRegressor(**param)
236 | scores = cross_val_score(
237 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
238 | )
239 | return scores.mean()
240 |
241 | def extr_regressor_objective(self, trial):
242 | param = {
243 | "n_estimators": trial.suggest_int("n_estimators", 10, 1000),
244 | "criterion": trial.suggest_categorical(
245 | "criterion", ["mse", "friedman_mse", "mae"]
246 | ),
247 | "max_depth": trial.suggest_int("max_depth", 1, 10),
248 | "min_samples_split": trial.suggest_int("min_samples_split", 2, 10),
249 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
250 | "min_weight_fraction_leaf": trial.suggest_loguniform(
251 | "min_weight_fraction_leaf", 1e-10, 1e-3
252 | ),
253 | "max_features": trial.suggest_categorical(
254 | "max_features", ["auto", "sqrt", "log2", None]
255 | ),
256 | "max_leaf_nodes": trial.suggest_int("max_leaf_nodes", 2, 10),
257 | "min_impurity_decrease": trial.suggest_loguniform(
258 | "min_impurity_decrease", 1e-10, 1e-3
259 | ),
260 | "bootstrap": True,
261 | "oob_score": trial.suggest_categorical("oob_score", [True, False]),
262 | "random_state": self.random_state,
263 | "n_jobs": -1,
264 | }
265 | regressor = ExtraTreesRegressor(**param)
266 | scores = cross_val_score(
267 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
268 | )
269 | return scores.mean()
270 |
271 | def rfr_regressor_objective(self, trial):
272 | param = {
273 | "n_estimators": trial.suggest_int("n_estimators", 200, 1500),
274 | "max_features": trial.suggest_categorical("max_features", ["auto", "sqrt"]),
275 | "max_depth": trial.suggest_int("max_depth", 10, 80, log=True),
276 | "min_samples_split": trial.suggest_int("min_samples_split", 2, 15),
277 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 9),
278 | "bootstrap": trial.suggest_categorical("bootstrap", [True, False]),
279 | }
280 | regressor = RandomForestRegressor(**param, n_jobs=-1, verbose=0)
281 | scores = cross_val_score(
282 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
283 | )
284 | return scores.mean()
285 |
286 | def xgb_regressor_objective(self, trial):
287 | param = {
288 | "n_estimators": trial.suggest_int("n_estimators", 500, 4000),
289 | "max_depth": trial.suggest_int("max_depth", 8, 16),
290 | "min_child_weight": trial.suggest_int("min_child_weight", 1, 300),
291 | "gamma": trial.suggest_int("gamma", 1, 3),
292 | "learning_rate": 0.01,
293 | "colsample_bytree": trial.suggest_discrete_uniform(
294 | "colsample_bytree", 0.5, 1, 0.1
295 | ),
296 | "lambda": trial.suggest_loguniform("lambda", 1e-3, 10.0),
297 | "alpha": trial.suggest_loguniform("alpha", 1e-3, 10.0),
298 | "subsample": trial.suggest_categorical("subsample", [0.6, 0.7, 0.8, 1.0]),
299 | "random_state": 42,
300 | }
301 | regressor = XGBRegressor(**param)
302 | scores = cross_val_score(
303 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
304 | )
305 | return scores.mean()
306 |
307 | def cat_regressor_objective(self, trial):
308 | params = {
309 | "iterations": trial.suggest_int("iterations", 50, 300),
310 | "depth": trial.suggest_int("depth", 4, 10),
311 | "random_strength": trial.suggest_int("random_strength", 0, 100),
312 | "bagging_temperature": trial.suggest_loguniform(
313 | "bagging_temperature", 0.01, 100.00
314 | ),
315 | "learning_rate": trial.suggest_loguniform("learning_rate", 1e-3, 1e-1),
316 | "od_type": trial.suggest_categorical("od_type", ["IncToDec", "Iter"]),
317 | }
318 | regressor = CatBoostRegressor(**params)
319 | scores = cross_val_score(
320 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
321 | )
322 | return scores.mean()
323 |
324 | def lgbm_regressor_objective(self, trial):
325 |
326 | param = {
327 | "boosting_type": "gbdt",
328 | "objective": "regression",
329 | "metric": "rmse",
330 | "learning_rate": trial.suggest_categorical(
331 | "learning_rate", [0.0125, 0.025, 0.05, 0.1]
332 | ),
333 | "num_leaves": trial.suggest_int("num_leaves", 2, 2048),
334 | "lambda_l1": trial.suggest_float("lambda_l1", 1e-8, 10.0, log=True),
335 | "lambda_l2": trial.suggest_float("lambda_l2", 1e-8, 10.0, log=True),
336 | "colsample_bytree": min(
337 | trial.suggest_float("colsample_bytree", 0.3, 1.0 + 1e-8), 1.0
338 | ),
339 | "bagging_fraction": min(
340 | trial.suggest_float("bagging_fraction", 0.3, 1.0 + 1e-8), 1.0
341 | ),
342 | "bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
343 | "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1, 100),
344 | "feature_pre_filter": False,
345 | "random_state": self.random_state,
346 | "num_threads": -1,
347 | "extra_trees": trial.suggest_categorical("extra_trees", [True, False]),
348 | }
349 | regressor = LGBMRegressor(**param)
350 | scores = cross_val_score(
351 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
352 | )
353 | return scores.mean()
354 |
355 | def mlp_regressor_objective(self, trial):
356 | param = {
357 | "hidden_layer_sizes": trial.suggest_int("hidden_layer_sizes", 2, 10),
358 | "activation": trial.suggest_categorical("activation", ["logistic", "tanh"]),
359 | "solver": trial.suggest_categorical("solver", ["lbfgs", "adam"]),
360 | "alpha": trial.suggest_loguniform("alpha", 1e-8, 1e-1),
361 | "learning_rate": trial.suggest_categorical(
362 | "learning_rate", ["constant", "adaptive"]
363 | ),
364 | "max_iter": trial.suggest_int("max_iter", 1, 2000),
365 | "random_state": self.random_state,
366 | "verbose": 0,
367 | "early_stopping": True,
368 | "validation_fraction": 0.2,
369 | "n_iter_no_change": 10,
370 | }
371 | regressor = MLPRegressor(**param)
372 | scores = cross_val_score(
373 | regressor, self.X, self.y, cv=self.cv, n_jobs=-1, scoring=self.metric
374 | )
375 | return scores.mean()
376 |
--------------------------------------------------------------------------------
/luciferml/supervised/utils/tuner/optuna/objectives/classification_objectives.py:
--------------------------------------------------------------------------------
1 | from catboost import CatBoostClassifier
2 | from lightgbm import LGBMClassifier
3 | from sklearn.ensemble import (
4 | AdaBoostClassifier,
5 | BaggingClassifier,
6 | ExtraTreesClassifier,
7 | GradientBoostingClassifier,
8 | RandomForestClassifier,
9 | )
10 | from sklearn.linear_model import (
11 | LogisticRegression,
12 | PassiveAggressiveClassifier,
13 | Perceptron,
14 | RidgeClassifier,
15 | SGDClassifier,
16 | )
17 | from sklearn.model_selection import cross_val_score
18 | from sklearn.neighbors import KNeighborsClassifier
19 | from sklearn.neural_network import MLPClassifier
20 | from sklearn.svm import SVC
21 | from sklearn.tree import DecisionTreeClassifier
22 | from xgboost import XGBClassifier
23 |
24 |
25 | class ClassificationObjectives:
26 | def __init__(
27 | self, X, y, cv=5, random_state=42, metric="accuracy", lgbm_objective="binary"
28 | ):
29 | self.metric = metric
30 | self.cv = cv
31 | self.X = X
32 | self.y = y
33 | self.random_state = random_state
34 | self.lgbm_objective = lgbm_objective
35 |
36 | def lr_classifier_objective(self, trial):
37 | param = {
38 | "C": trial.suggest_loguniform("C", 1e-5, 1e5),
39 | "solver": trial.suggest_categorical(
40 | "solver", ["newton-cg", "lbfgs", "liblinear", "sag", "saga"]
41 | ),
42 | "max_iter": trial.suggest_int("max_iter", 1, 1000),
43 | "tol": trial.suggest_loguniform("tol", 1e-5, 1e-2),
44 | "random_state": self.random_state,
45 | }
46 | clf = LogisticRegression(**param)
47 | scores = cross_val_score(
48 | clf,
49 | self.X,
50 | self.y,
51 | cv=self.cv,
52 | scoring=self.metric,
53 | n_jobs=-1,
54 | )
55 | return scores.mean()
56 |
57 | def sgd_classifier_objective(self, trial):
58 | param = {
59 | "loss": trial.suggest_categorical(
60 | "loss",
61 | ["hinge", "log", "modified_huber", "squared_hinge", "perceptron"],
62 | ),
63 | "penalty": trial.suggest_categorical("penalty", ["l2", "l1", "elasticnet"]),
64 | "alpha": trial.suggest_loguniform("alpha", 1e-5, 1e5),
65 | "l1_ratio": trial.suggest_uniform("l1_ratio", 0, 1),
66 | "fit_intercept": trial.suggest_categorical("fit_intercept", [True, False]),
67 | "max_iter": trial.suggest_int("max_iter", 1, 1000),
68 | "tol": trial.suggest_loguniform("tol", 1e-5, 1e-2),
69 | "random_state": self.random_state,
70 | }
71 | clf = SGDClassifier(**param)
72 | scores = cross_val_score(
73 | clf, self.X, self.y, cv=self.cv, scoring=self.metric, n_jobs=-1
74 | )
75 | return scores.mean()
76 |
77 | def ridg_classifier_objective(self, trial):
78 | param = {
79 | "alpha": trial.suggest_loguniform("alpha", 1e-5, 1e5),
80 | "fit_intercept": trial.suggest_categorical("fit_intercept", [True, False]),
81 | "max_iter": trial.suggest_int("max_iter", 1, 1000),
82 | "tol": trial.suggest_loguniform("tol", 1e-5, 1e-2),
83 | "random_state": self.random_state,
84 | }
85 | clf = RidgeClassifier(**param)
86 | scores = cross_val_score(
87 | clf,
88 | self.X,
89 | self.y,
90 | cv=self.cv,
91 | scoring=self.metric,
92 | n_jobs=-1,
93 | )
94 | return scores.mean()
95 |
96 | def perc_classifier_objective(self, trial):
97 | param = {
98 | "penalty": trial.suggest_categorical("penalty", ["l2", "l1", "elasticnet"]),
99 | "alpha": trial.suggest_loguniform("alpha", 1e-5, 1e5),
100 | "fit_intercept": trial.suggest_categorical("fit_intercept", [True, False]),
101 | "max_iter": trial.suggest_int("max_iter", 1, 1000),
102 | "tol": trial.suggest_loguniform("tol", 1e-5, 1e-2),
103 | "random_state": self.random_state,
104 | }
105 | clf = Perceptron(**param)
106 | scores = cross_val_score(
107 | clf,
108 | self.X,
109 | self.y,
110 | cv=self.cv,
111 | scoring=self.metric,
112 | n_jobs=-1,
113 | )
114 | return scores.mean()
115 |
116 | def pass_classifier_objective(self, trial):
117 | param = {
118 | "C": trial.suggest_loguniform("C", 1e-5, 1e5),
119 | "fit_intercept": trial.suggest_categorical("fit_intercept", [True, False]),
120 | "max_iter": trial.suggest_int("max_iter", 1, 1000),
121 | "tol": trial.suggest_loguniform("tol", 1e-5, 1e-2),
122 | "random_state": self.random_state,
123 | }
124 | clf = PassiveAggressiveClassifier(**param)
125 | scores = cross_val_score(
126 | clf,
127 | self.X,
128 | self.y,
129 | cv=self.cv,
130 | scoring=self.metric,
131 | n_jobs=-1,
132 | )
133 | return scores.mean()
134 |
135 | def svm_classifier_objective(self, trial):
136 | param = {
137 | "C": trial.suggest_loguniform("C", 1e-5, 1e5),
138 | "kernel": trial.suggest_categorical(
139 | "kernel", ["rbf", "linear", "poly", "sigmoid"]
140 | ),
141 | "gamma": trial.suggest_loguniform("gamma", 1e-5, 1e5),
142 | "degree": trial.suggest_int("degree", 1, 10),
143 | "coef0": trial.suggest_loguniform("coef0", 1e-5, 1e5),
144 | "shrinking": trial.suggest_categorical("shrinking", [True, False]),
145 | "tol": trial.suggest_loguniform("tol", 1e-5, 1e-2),
146 | "random_state": self.random_state,
147 | }
148 | clf = SVC(**param)
149 | scores = cross_val_score(
150 | clf,
151 | self.X,
152 | self.y,
153 | cv=self.cv,
154 | scoring=self.metric,
155 | n_jobs=-1,
156 | )
157 | return scores.mean()
158 |
159 | def knn_classifier_objective(self, trial):
160 | param = {
161 | "n_neighbors": trial.suggest_int("n_neighbors", 1, 256),
162 | "weights": trial.suggest_categorical("weights", ["uniform", "distance"]),
163 | "p": trial.suggest_int("p", 1, 10),
164 | "n_jobs": -1,
165 | "rows_limit": 100000,
166 | }
167 | clf = KNeighborsClassifier(**param)
168 | scores = cross_val_score(
169 | clf,
170 | self.X,
171 | self.y,
172 | cv=self.cv,
173 | scoring=self.metric,
174 | n_jobs=-1,
175 | )
176 | return scores.mean()
177 |
178 | def dt_classifier_objective(self, trial):
179 | param = {
180 | "criterion": trial.suggest_categorical("criterion", ["gini", "entropy"]),
181 | "splitter": trial.suggest_categorical("splitter", ["best", "random"]),
182 | "max_depth": trial.suggest_int("max_depth", 1, 10),
183 | "min_samples_split": trial.suggest_int("min_samples_split", 1, 10),
184 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
185 | "min_weight_fraction_leaf": trial.suggest_float(
186 | "min_weight_fraction_leaf", 0, 0.5
187 | ),
188 | "max_features": trial.suggest_categorical(
189 | "max_features", ["auto", "sqrt", "log2"]
190 | ),
191 | "random_state": self.random_state,
192 | }
193 | clf = DecisionTreeClassifier(**param)
194 | scores = cross_val_score(
195 | clf,
196 | self.X,
197 | self.y,
198 | cv=self.cv,
199 | scoring=self.metric,
200 | n_jobs=-1,
201 | )
202 | return scores.mean()
203 |
204 | def rfc_classifier_objective(self, trial):
205 | param = {
206 | "n_estimators": trial.suggest_int("n_estimators", 1, 100),
207 | "criterion": trial.suggest_categorical("criterion", ["gini", "entropy"]),
208 | "min_weight_fraction_leaf": trial.suggest_float(
209 | "min_weight_fraction_leaf", 0, 0.5
210 | ),
211 | "max_depth": trial.suggest_int("max_depth", 2, 32),
212 | "min_samples_split": trial.suggest_int("min_samples_split", 2, 100),
213 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 100),
214 | "max_features": trial.suggest_float("max_features", 0.01, 1),
215 | "seed": self.random_state,
216 | "n_jobs": -1,
217 | "max_steps": 10,
218 | }
219 | clf = RandomForestClassifier(**param)
220 | scores = cross_val_score(
221 | clf,
222 | self.X,
223 | self.y,
224 | cv=self.cv,
225 | scoring=self.metric,
226 | n_jobs=-1,
227 | )
228 | return scores.mean()
229 |
230 | def gbc_classifier_objective(self, trial):
231 | param = {
232 | "n_estimators": trial.suggest_int("n_estimators", 1, 100),
233 | "learning_rate": trial.suggest_loguniform("learning_rate", 1e-5, 1e5),
234 | "max_depth": trial.suggest_int("max_depth", 1, 10),
235 | "min_samples_split": trial.suggest_int("min_samples_split", 1, 10),
236 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
237 | "min_weight_fraction_leaf": trial.suggest_float(
238 | "min_weight_fraction_leaf", 0, 0.5
239 | ),
240 | "max_features": trial.suggest_categorical(
241 | "max_features", ["auto", "sqrt", "log2"]
242 | ),
243 | }
244 | clf = GradientBoostingClassifier(**param)
245 | scores = cross_val_score(
246 | clf,
247 | self.X,
248 | self.y,
249 | cv=self.cv,
250 | scoring=self.metric,
251 | n_jobs=-1,
252 | )
253 | return scores.mean()
254 |
255 | def ada_classifier_objective(self, trial):
256 | param = {
257 | "n_estimators": trial.suggest_int("n_estimators", 1, 100),
258 | "learning_rate": trial.suggest_loguniform("learning_rate", 1e-5, 1e5),
259 | "algorithm": trial.suggest_categorical("algorithm", ["SAMME", "SAMME.R"]),
260 | "random_state": self.random_state,
261 | }
262 | clf = AdaBoostClassifier(**param)
263 | scores = cross_val_score(
264 | clf,
265 | self.X,
266 | self.y,
267 | cv=self.cv,
268 | scoring=self.metric,
269 | n_jobs=-1,
270 | )
271 | return scores.mean()
272 |
273 | def bag_classifier_objective(self, trial):
274 | param = {
275 | "n_estimators": trial.suggest_int("n_estimators", 1, 100),
276 | "bootstrap": trial.suggest_categorical("bootstrap", [True, False]),
277 | "bootstrap_features": trial.suggest_categorical(
278 | "bootstrap_features", [True, False]
279 | ),
280 | "max_samples": trial.suggest_uniform("max_samples", 0.1, 1),
281 | "max_features": trial.suggest_uniform("max_features", 0.1, 1),
282 | "n_jobs": -1,
283 | "random_state": self.random_state,
284 | }
285 | clf = BaggingClassifier(**param)
286 | scores = cross_val_score(
287 | clf,
288 | self.X,
289 | self.y,
290 | cv=self.cv,
291 | scoring=self.metric,
292 | n_jobs=-1,
293 | )
294 | return scores.mean()
295 |
296 | def extc_classifier_objective(self, trial):
297 | param = {
298 | "criterion": trial.suggest_categorical("criterion", ["gini", "entropy"]),
299 | "min_weight_fraction_leaf": trial.suggest_float(
300 | "min_weight_fraction_leaf", 0, 0.5
301 | ),
302 | "max_depth": trial.suggest_int("max_depth", 2, 32),
303 | "min_samples_split": trial.suggest_int("min_samples_split", 2, 100),
304 | "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 100),
305 | "max_features": trial.suggest_float("max_features", 0.01, 1),
306 | "random_state": self.random_state,
307 | "n_jobs": -1,
308 | "max_steps": 10,
309 | }
310 | clf = ExtraTreesClassifier(**param)
311 | scores = cross_val_score(
312 | clf,
313 | self.X,
314 | self.y,
315 | cv=self.cv,
316 | scoring=self.metric,
317 | n_jobs=-1,
318 | )
319 | return scores.mean()
320 |
321 | def lgbm_classifier_objective(self, trial):
322 | param = {
323 | "learning_rate": trial.suggest_categorical(
324 | "learning_rate", [0.0125, 0.025, 0.05, 0.1]
325 | ),
326 | "num_leaves": trial.suggest_int("num_leaves", 2, 2048),
327 | "lambda_l1": trial.suggest_float("lambda_l1", 1e-8, 10.0, log=True),
328 | "lambda_l2": trial.suggest_float("lambda_l2", 1e-8, 10.0, log=True),
329 | "feature_fraction": min(
330 | trial.suggest_float("feature_fraction", 0.3, 1.0 + 1e-8), 1.0
331 | ),
332 | "bagging_fraction": min(
333 | trial.suggest_float("bagging_fraction", 0.3, 1.0 + 1e-8), 1.0
334 | ),
335 | "bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
336 | "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1, 100),
337 | "extra_trees": trial.suggest_categorical("extra_trees", [True, False]),
338 | "feature_pre_filter": False,
339 | "boosting_type": "gbdt",
340 | "seed": self.random_state,
341 | "num_threads": -1,
342 | "objective": self.lgbm_objective,
343 | }
344 | clf = LGBMClassifier(**param)
345 | scores = cross_val_score(
346 | clf,
347 | self.X,
348 | self.y,
349 | cv=self.cv,
350 | scoring=self.metric,
351 | n_jobs=-1,
352 | )
353 | return scores.mean()
354 |
355 | def cat_classifier_objective(self, trial):
356 | param = {
357 | "objective": trial.suggest_categorical("objective", ["Logloss", "CrossEntropy"]),
358 | "iterations": 1000,
359 | "colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.01, 0.1),
360 | "depth": trial.suggest_int("depth", 1, 12),
361 | "boosting_type": trial.suggest_categorical("boosting_type", ["Ordered", "Plain"]),
362 | "bootstrap_type": trial.suggest_categorical(
363 | "bootstrap_type", ["Bayesian", "Bernoulli", "MVS"]
364 | ),
365 | "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1, 100),
366 | "learning_rate": trial.suggest_categorical(
367 | "learning_rate", [0.05, 0.1, 0.2]
368 | ),
369 | "rsm": trial.suggest_float("rsm", 0.1, 1),
370 | "l2_leaf_reg": trial.suggest_float(
371 | "l2_leaf_reg", 0.0001, 10.0, log=False
372 | ),
373 | "random_state": self.random_state,
374 | "verbose": False,
375 | "allow_writing_files": False,
376 | }
377 |
378 | if param["bootstrap_type"] == "Bayesian":
379 | param["bagging_temperature"] = trial.suggest_float("bagging_temperature", 0, 10)
380 | elif param["bootstrap_type"] == "Bernoulli":
381 | param["subsample"] = trial.suggest_float("subsample", 0.1, 1)
382 | clf = CatBoostClassifier(**param)
383 | scores = cross_val_score(
384 | clf,
385 | self.X,
386 | self.y,
387 | cv=self.cv,
388 | scoring=self.metric,
389 | n_jobs=-1,
390 | )
391 | return scores.mean()
392 |
393 | def xgb_classifier_objective(self, trial):
394 | param = {
395 | "learning_rate": trial.suggest_categorical(
396 | "learning_rate", [0.05, 0.1, 0.2]
397 | ),
398 | "eta": trial.suggest_categorical("eta", [0.0125, 0.025, 0.05, 0.1]),
399 | "max_depth": trial.suggest_int("max_depth", 2, 12),
400 | "lambda": trial.suggest_float("lambda", 1e-8, 10.0, log=True),
401 | "alpha": trial.suggest_float("alpha", 1e-8, 10.0, log=True),
402 | "colsample_bytree": min(
403 | trial.suggest_float("colsample_bytree", 0.3, 1.0 + 1e-8), 1.0
404 | ),
405 | "subsample": min(trial.suggest_float("subsample", 0.3, 1.0 + 1e-8), 1.0),
406 | "min_child_weight": trial.suggest_int("min_child_weight", 1, 100),
407 | "tree_method": "hist",
408 | "booster": "gbtree",
409 | "n_jobs": -1,
410 | "seed": self.random_state,
411 | "verbosity": 0,
412 |
413 | }
414 | clf = XGBClassifier(**param)
415 | scores = cross_val_score(
416 | clf,
417 | self.X,
418 | self.y,
419 | cv=self.cv,
420 | scoring=self.metric,
421 | n_jobs=-1,
422 | )
423 | return scores.mean()
424 |
425 | def mlp_classifier_objective(self, trial):
426 | param = {
427 | "hidden_layer_sizes": trial.suggest_int("hidden_layer_sizes", 1, 10),
428 | "max_iter": trial.suggest_int("max_iter", 1, 2000),
429 | "dense_1_size": trial.suggest_int("dense_1_size", 4, 100),
430 | "dense_2_size": trial.suggest_int("dense_2_size", 2, 100),
431 | "learning_rate": trial.suggest_categorical(
432 | "learning_rate", [0.005, 0.01, 0.05, 0.1, 0.2]
433 | ),
434 | "learning_rate_type": trial.suggest_categorical(
435 | "learning_rate_type", ["constant", "adaptive"]
436 | ),
437 | "alpha": trial.suggest_float("alpha", 1e-8, 10.0, log=True),
438 | "seed": self.random_state,
439 | }
440 | clf = MLPClassifier(**param)
441 | scores = cross_val_score(
442 | clf,
443 | self.X,
444 | self.y,
445 | cv=self.cv,
446 | scoring=self.metric,
447 | n_jobs=-1,
448 | )
449 | return scores.mean()
450 |
--------------------------------------------------------------------------------
/luciferml/supervised/classification.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import os
3 | from re import S
4 | import time
5 | import warnings
6 |
7 | import numpy as np
8 | import optuna
9 | import pandas as pd
10 | from IPython.display import display
11 | from joblib import dump, load
12 | from luciferml.supervised.utils.best import Best
13 | from luciferml.supervised.utils.configs import *
14 | from luciferml.supervised.utils.predictors import classification_predictor
15 | from luciferml.supervised.utils.preprocesser import PreProcesser
16 | from luciferml.supervised.utils.tuner.luciferml_tuner import luciferml_tuner
17 | from luciferml.supervised.utils.validator import *
18 | from optuna.samplers._tpe.sampler import TPESampler
19 | from sklearn.metrics import accuracy_score
20 | from colorama import Fore
21 |
22 |
23 | class Classification:
24 | def __init__(
25 | self,
26 | predictor=["lr"],
27 | params={},
28 | tune=False,
29 | test_size=0.2,
30 | cv_folds=10,
31 | random_state=42,
32 | pca_kernel="linear",
33 | n_components_lda=1,
34 | lda="n",
35 | pca="n",
36 | n_components_pca=2,
37 | metrics=[
38 | "accuracy",
39 | ],
40 | loss="binary_crossentropy",
41 | validation_split=0.20,
42 | tune_mode=1,
43 | smote="n",
44 | k_neighbors=1,
45 | verbose=False,
46 | exclude_models=[],
47 | path=None,
48 | optuna_sampler=TPESampler(multivariate=True),
49 | optuna_direction="maximize",
50 | optuna_n_trials=100,
51 | optuna_metric="accuracy",
52 | lgbm_objective="binary",
53 | ):
54 | """
55 | Encode Categorical Data then Applies SMOTE , Splits the features and labels in training and validation sets with test_size = .2 , scales self.X_train, self.X_val using StandardScaler.\n
56 | Fits every model on training set and predicts results find and plots Confusion Matrix,\n
57 | finds accuracy of model applies K-Fold Cross Validation\n
58 | and stores accuracy in variable name accuracy and model name in self.classifier name and returns both as a tuple.\n
59 | Applies HyperParam Tuning and gives best params and accuracy.\n
60 |
61 | Parameters:
62 |
63 | features : array
64 | features array
65 | lables : array
66 | labels array
67 | predictor : list
68 | Predicting model to be used
69 | Default ['lr'] - Logistic Regression\n
70 | Available Predictors:
71 | lr - Logisitic Regression\n
72 | sgd - Stochastic Gradient Descent Classifier\n
73 | perc - Perceptron\n
74 | pass - Passive Aggressive Classifier\n
75 | ridg - Ridge Classifier\n
76 | svm -SupportVector Machine\n
77 | knn - K-Nearest Neighbours\n
78 | nb - GaussianNaive bayes\n
79 | rfc- Random Forest self.Classifier\n
80 | gbc - Gradient Boosting Classifier\n
81 | ada - AdaBoost Classifier\n
82 | bag - Bagging Classifier\n
83 | extc - Extra Trees Classifier\n
84 | lgbm - LightGBM Classifier\n
85 | cat - CatBoost Classifier\n
86 | xgb- XGBoost self.Classifier\n
87 | ann - MultiLayer Perceptron Classifier\n
88 | all - Applies all above classifiers\n
89 |
90 | params : dict
91 | contains parameters for model
92 | tune : boolean
93 | when True Applies GridSearch CrossValidation
94 | Default is False
95 | test_size: float or int, default=.2
96 | If float, should be between 0.0 and 1.0 and represent
97 | the proportion of the dataset to include in
98 | the test split.
99 | If int, represents the absolute number of test samples.
100 | cv_folds : int
101 | No. of cross validation folds. Default = 10
102 | pca : str
103 | if 'y' will apply PCA on Train and Validation set. Default = 'n'
104 | lda : str
105 | if 'y' will apply LDA on Train and Validation set. Default = 'n'
106 | pca_kernel : str
107 | Kernel to be use in PCA. Default = 'linear'
108 | n_components_lda : int
109 | No. of components for LDA. Default = 1
110 | n_components_pca : int
111 | No. of components for PCA. Default = 2
112 | loss : str
113 | loss method for ann. Default = 'binary_crossentropy'
114 | rate for dropout layer. Default = 0
115 | smote : str,
116 | Whether to apply SMOTE. Default = 'y'
117 | k_neighbors : int
118 | No. of neighbours for SMOTE. Default = 1
119 | verbose : boolean
120 | Verbosity of models. Default = False
121 | exclude_models : list
122 | List of models to be excluded when using predictor = 'all' . Default = []
123 | path : list
124 | List containing path to saved model and scaler. Default = None
125 | Example: [model.pkl, scaler.pkl]
126 | random_state : int
127 | Random random_state for reproducibility. Default = 42
128 | optuna_sampler : Function
129 | Sampler to be used in optuna. Default = TPESampler()
130 | optuna_direction : str
131 | Direction of optimization. Default = 'maximize'
132 | Available Directions:
133 | maximize : Maximize
134 | minimize : Minimize
135 | optuna_n_trials : int
136 | No. of trials for optuna. Default = 100
137 | optuna_metric: str
138 | Metric to be used in optuna. Default = 'r2'
139 | lgbm_objective : str
140 | Objective for lgbm classifier. Default = 'binary'
141 |
142 | Returns:
143 |
144 | Dict Containing Name of Classifiers, Its K-Fold Cross Validated Accuracy and Prediction set
145 |
146 | Dataframe containing all the models and their accuracies when predictor is 'all'
147 |
148 | Example:
149 |
150 | from luciferml.supervised.classification import Classification
151 |
152 | dataset = pd.read_csv('Social_Network_Ads.csv')
153 |
154 | X = dataset.iloc[:, :-1]
155 |
156 | y = dataset.iloc[:, -1]
157 |
158 | classifier = Classification(predictor = 'lr')
159 |
160 | classifier.fit(X, y)
161 |
162 | result = classifier.result()
163 |
164 | """
165 | self.preprocess = PreProcesser()
166 | if type(predictor) == list:
167 | if not "all" in predictor:
168 | self.predictor = predictor[0] if len(
169 | predictor) == 1 else predictor
170 | else:
171 | self.predictor = predictor
172 | else:
173 | self.predictor = predictor
174 | bool_pred, pred = pred_check(predictor, pred_type="classification")
175 | if not bool_pred:
176 | raise ValueError(unsupported_pred_warning.format(pred))
177 | self.original_predictor = predictor
178 | self.params = params
179 | self.tune = tune
180 | self.test_size = test_size
181 | self.cv_folds = cv_folds
182 | self.random_state = random_state
183 | self.pca_kernel = pca_kernel
184 | self.n_components_lda = n_components_lda
185 | self.lda = lda
186 | self.pca = pca
187 | self.n_components_pca = n_components_pca
188 | self.metrics = metrics
189 | self.loss = loss
190 | self.validation_split = validation_split
191 | self.tune_mode = tune_mode
192 | self.rerun = False
193 | self.smote = smote
194 | self.k_neighbors = k_neighbors
195 | self.verbose = verbose
196 | self.exclude_models = exclude_models
197 | self.sampler = optuna_sampler
198 | self.direction = optuna_direction
199 | self.n_trials = optuna_n_trials
200 | self.metric = optuna_metric
201 | self.lgbm_objective = lgbm_objective
202 |
203 | self.accuracy_scores = {}
204 | self.reg_result = {}
205 | self.accuracy = 0
206 | self.y_pred = []
207 | self.kfold_accuracy = 0
208 | self.classifier_name = ""
209 | self.sc = 0
210 |
211 | self.kfoldacc = []
212 | self.acc = []
213 | self.bestacc = []
214 | self.bestparams = []
215 | self.tuned_trained_model = []
216 | self.best_classifier_path = ""
217 | self.scaler_path = ""
218 | self.classifier_model = []
219 | self.result_df = pd.DataFrame(index=None)
220 | self.classifiers = copy.deepcopy(classifiers)
221 | for i in self.exclude_models:
222 | self.classifiers.pop(i)
223 | self.best_classifier = "First Run the Predictor in All mode"
224 | self.objective = None
225 | self.pred_mode = ""
226 | self.model_to_predict = []
227 |
228 | if path != None:
229 | try:
230 | self.classifier, self.sc = self.__load(path)
231 | except Exception as e:
232 | print(Fore.RED + e)
233 | print(Fore.RED + "Model not found")
234 | if not self.verbose:
235 | optuna.logging.set_verbosity(optuna.logging.WARNING)
236 |
237 | def fit(self, features, labels):
238 | """[Takes Features and Labels and Encodes Categorical Data then Applies SMOTE , Splits the features and labels in training and validation sets with test_size = .2
239 | scales X_train, self.X_val using StandardScaler.
240 | Fits every model on training set and predicts results,
241 | finds accuracy of model applies K-Fold Cross Validation
242 | and stores its accuracies in a dictionary containing Model name as Key and accuracies as values and returns it
243 | Applies GridSearch Cross Validation and gives best params out from param list.]
244 |
245 | Args:
246 | features ([Pandas DataFrame]): [DataFrame containing Features]
247 | labels ([Pandas DataFrame]): [DataFrame containing Labels]
248 | """
249 | self.features = features
250 | self.labels = labels
251 | # Time Function ---------------------------------------------------------------------
252 |
253 | self.start = time.time()
254 | print(Fore.MAGENTA + intro, "\n")
255 | print(Fore.GREEN + "Started LuciferML [", "\u2713", "]\n")
256 | if not self.rerun:
257 | # CHECKUP ---------------------------------------------------------------------
258 | if not isinstance(self.features, pd.DataFrame) and not isinstance(
259 | self.labels, pd.Series
260 | ):
261 | print(
262 | Fore.RED
263 | + "TypeError: This Function take features as Pandas Dataframe and labels as Pandas Series. Please check your implementation.\n"
264 | )
265 | self.end = time.time()
266 | print(self.end - self.start)
267 | return
268 |
269 | print(Fore.YELLOW + "Preprocessing Started [*]\n")
270 | self.features, self.labels = self.preprocess.encoder(
271 | self.features, self.labels
272 | )
273 |
274 | self.features, self.labels = sparse_check(self.features, self.labels)
275 |
276 | (
277 | self.X_train,
278 | self.X_val,
279 | self.y_train,
280 | self.y_val,
281 | self.sc,
282 | ) = self.preprocess.data_preprocess(
283 | self.features,
284 | self.labels,
285 | self.test_size,
286 | self.random_state,
287 | self.smote,
288 | self.k_neighbors,
289 | )
290 |
291 | self.X_train, self.X_val = self.preprocess.dimensionality_reduction(
292 | self.lda,
293 | self.pca,
294 | self.X_train,
295 | self.X_val,
296 | self.y_train,
297 | self.n_components_lda,
298 | self.n_components_pca,
299 | self.pca_kernel,
300 | self.start,
301 | )
302 |
303 | print(Fore.GREEN + "Preprocessing Done [", "\u2713", "]\n")
304 |
305 | if self.original_predictor == "all" or type(self.predictor) == list:
306 | if 'all' in self.predictor and type(self.predictor)==list:
307 | self.predictor.remove('all')
308 | self.model_to_predict = (
309 | self.predictor if len(self.predictor) > 1 and type(self.predictor) == list else self.classifiers
310 | )
311 |
312 | self.result_df["Name"] = (
313 | list(self.classifiers[i] for i in self.predictor)
314 | if type(self.predictor) == list and len(self.predictor) > 1
315 | else list(self.classifiers.values())
316 | )
317 | self.pred_mode = "all" if len(self.predictor) > 1 and type(
318 | self.predictor) == list else "single"
319 | self.__fitall()
320 | return
321 |
322 | self.classifier, self.objective = classification_predictor(
323 | self.predictor,
324 | self.params,
325 | self.X_train,
326 | self.y_train,
327 | self.cv_folds,
328 | self.random_state,
329 | self.metric,
330 | verbose=self.verbose,
331 | lgbm_objective=self.lgbm_objective,
332 | )
333 | try:
334 | self.classifier.fit(self.X_train, self.y_train)
335 | except Exception as error:
336 | print(Fore.RED + "Classifier Build Failed with error: ", error, "\n")
337 | finally:
338 | print(Fore.GREEN + "Model Trained Successfully [", "\u2713", "]\n")
339 |
340 | try:
341 | print(Fore.YELLOW + "Evaluating Model Performance [*]\n")
342 | self.y_pred = self.classifier.predict(self.X_val)
343 | if self.predictor == "ann":
344 | self.y_pred = (self.y_pred > 0.5).astype("int32")
345 | self.accuracy = accuracy_score(self.y_val, self.y_pred)
346 | print(Fore.CYAN + " Validation Accuracy is : {:.2f} %".format(self.accuracy * 100))
347 | self.classifier_name, self.kfold_accuracy = kfold(
348 | self.classifier,
349 | self.predictor,
350 | self.X_train,
351 | self.y_train,
352 | self.cv_folds,
353 | )
354 | self.preprocess.confusion_matrix(self.y_pred, self.y_val)
355 | except Exception as error:
356 | print(Fore.RED + "Model Evaluation Failed with error: ", error, "\n")
357 | finally:
358 | print(Fore.GREEN + "Model Evaluation Completed [", "\u2713", "]\n")
359 |
360 | if not self.predictor == "nb" and self.tune:
361 | self.__tuner()
362 |
363 | print(Fore.GREEN + "Completed LuciferML Run [", "\u2713", "]\n")
364 | self.end = time.time()
365 | final_time = self.end - self.start
366 | print(Fore.BLUE + "Time Elapsed : ", f"{final_time:.2f}", "seconds \n")
367 |
368 | def __fitall(self):
369 | print(Fore.YELLOW + "Training LuciferML [*]\n")
370 | if self.params != {}:
371 | warnings.warn(params_use_warning, UserWarning)
372 | self.params = {}
373 | for _, self.predictor in enumerate(self.model_to_predict):
374 | if not self.predictor in self.exclude_models:
375 | try:
376 | self.classifier, self.objective = classification_predictor(
377 | self.predictor,
378 | self.params,
379 | self.X_train,
380 | self.y_train,
381 | self.cv_folds,
382 | self.random_state,
383 | self.metric,
384 | mode="multi",
385 | verbose=self.verbose,
386 | lgbm_objective=self.lgbm_objective,
387 | )
388 | except Exception as error:
389 | print(
390 | Fore.RED + classifiers[self.predictor],
391 | "Model Train Failed with error: ",
392 | error,
393 | "\n",
394 | )
395 | try:
396 | self.classifier.fit(self.X_train, self.y_train)
397 | self.y_pred = self.classifier.predict(self.X_val)
398 | if self.predictor == "ann":
399 | self.y_pred = (self.y_pred > 0.5).astype("int32")
400 | self.accuracy = accuracy_score(self.y_val, self.y_pred)
401 | self.acc.append(self.accuracy * 100)
402 | self.classifier_name, self.kfold_accuracy = kfold(
403 | self.classifier,
404 | self.predictor,
405 | self.X_train,
406 | self.y_train,
407 | self.cv_folds,
408 | all_mode=True,
409 | )
410 | self.kfoldacc.append(self.kfold_accuracy)
411 | self.classifier_model.append(self.classifier)
412 | except Exception as error:
413 | print(
414 | classifiers[self.predictor],
415 | "Evaluation Failed with error: ",
416 | error,
417 | "\n",
418 | )
419 | if self.tune:
420 | self.__tuner(all_mode=True, single_mode=False)
421 |
422 | self.result_df["Accuracy"] = self.acc
423 | self.result_df["KFold Accuracy"] = self.kfoldacc
424 | self.result_df["Model"] = self.classifier_model
425 | if self.tune:
426 | self.result_df["Best Parameters"] = self.bestparams
427 | self.result_df["Best Accuracy"] = self.bestacc
428 | self.best_classifier = Best(
429 | self.result_df.loc[self.result_df["Best Accuracy"].idxmax()],
430 | self.tune,
431 | )
432 | else:
433 | self.best_classifier = Best(
434 | self.result_df.loc[self.result_df["KFold Accuracy"].idxmax()], self.tune
435 | )
436 | print(Fore.GREEN + "Training Done [", "\u2713", "]\n")
437 | print(Fore.CYAN + "Results Below\n")
438 | display(self.result_df)
439 | print(Fore.GREEN + "\nCompleted LuciferML Run [", "\u2713", "]\n")
440 | if len(self.model_to_predict) > 1:
441 | self.best_classifier_path, self.scaler_path = self.save(
442 | best=True, model=self.best_classifier.model, scaler=self.sc
443 | )
444 | print(
445 | Fore.CYAN
446 | + "Saved Best Model to {} and its scaler to {}".format(
447 | self.best_classifier_path, self.scaler_path
448 | ),
449 | "\n",
450 | )
451 | self.end = time.time()
452 | final_time = self.end - self.start
453 | print(Fore.BLUE + "Time Elapsed : ", f"{final_time:.2f}", "seconds \n")
454 | return
455 |
456 | def __tuner(self, all_mode=False, single_mode=False):
457 | if not all_mode:
458 | print(Fore.YELLOW + "Tuning Started [*]\n")
459 | if not self.predictor == "nb":
460 | (
461 | self.best_params,
462 | self.best_accuracy,
463 | self.best_trained_model,
464 | ) = luciferml_tuner(
465 | self.predictor,
466 | self.objective,
467 | self.n_trials,
468 | self.sampler,
469 | self.direction,
470 | self.X_train,
471 | self.y_train,
472 | self.cv_folds,
473 | self.random_state,
474 | self.metric,
475 | all_mode=all_mode,
476 | )
477 | if self.predictor == "nb":
478 | self.best_params = "Not Applicable"
479 | self.best_accuracy = 0
480 | self.bestparams.append(self.best_params)
481 | self.bestacc.append(self.best_accuracy * 100)
482 | self.tuned_trained_model.append(self.best_trained_model)
483 | if not all_mode or single_mode:
484 | print(Fore.GREEN + "Tuning Done [", "\u2713", "]\n")
485 |
486 | def result(self):
487 | """[Makes a dictionary containing Classifier Name, K-Fold CV Accuracy, RMSE, Prediction set.]
488 |
489 | Returns:
490 | [dict]: [Dictionary containing :
491 | - "Classifier" - Classifier Name
492 | - "Accuracy" - KFold CV Accuracy
493 | - "YPred" - Array for Prediction set
494 | ]
495 | [dataframe] : [Dataset containing accuracy and best_params
496 | for all predictors only when predictor = 'all' is used
497 | ]
498 | """
499 | if not self.pred_mode == "all":
500 | self.reg_result["Classifier"] = self.classifier_name
501 | self.reg_result["Accuracy"] = self.kfold_accuracy
502 | self.reg_result["YPred"] = self.y_pred
503 |
504 | return self.reg_result
505 | if self.pred_mode == "all":
506 | return self.result_df
507 |
508 | def predict(self, X_test):
509 | """[Takes test set and returns predictions for that test set]
510 |
511 | Args:
512 | X_test ([Array]): [Array Containing Test Set]
513 |
514 | Returns:
515 | [Array]: [Predicted set for given test set]
516 | """
517 | if not self.pred_mode == "all":
518 | X_test = np.array(X_test)
519 | if X_test.ndim == 1:
520 | X_test = X_test.reshape(1, -1)
521 |
522 | y_test = self.classifier.predict(self.sc.transform(X_test))
523 |
524 | return y_test
525 | if self.pred_mode == "all":
526 | raise TypeError("Predict is only applicable on single predictor")
527 |
528 | def save(self, path=None, best=False, **kwargs):
529 | """
530 | Saves the model and its scaler to a file provided with a path.
531 | If no path is provided will create a directory named
532 | lucifer_ml_info/models/ and lucifer_ml_info/scaler/ in current working directory
533 | Args:
534 | path ([list]): [List containing path to save the model and scaler.]
535 | Example: path = ["model.pkl", "scaler.pkl"]
536 |
537 | Returns:
538 | Path to the saved model and its scaler.
539 | """
540 | if not type(path) == list and path != None:
541 | raise TypeError("Path must be a list")
542 | if self.pred_mode == "all" and best == False:
543 | raise TypeError("Cannot save model for all predictors")
544 | dir_path_model = path[0] if path else "lucifer_ml_info/models/classifier/"
545 | dir_path_scaler = path[1] if path else "lucifer_ml_info/scalers/classifier/"
546 | model_name = classifiers[self.predictor].replace(" ", "_")
547 | if best:
548 | dir_path_model = "lucifer_ml_info/best/classifier/models/"
549 | dir_path_scaler = "lucifer_ml_info/best/classifier/scalers/"
550 | model_name = self.best_classifier.name.replace(" ", "_")
551 | os.makedirs(dir_path_model, exist_ok=True)
552 | os.makedirs(dir_path_scaler, exist_ok=True)
553 | timestamp = str(int(time.time()))
554 | path_model = dir_path_model + model_name + "_" + timestamp + ".pkl"
555 | path_scaler = (
556 | dir_path_scaler + model_name + "_" + "Scaler" + "_" + timestamp + ".pkl"
557 | )
558 | if (
559 | not kwargs.get("model")
560 | and not kwargs.get("best")
561 | and not kwargs.get("scaler")
562 | ):
563 | dump(self.classifier, open(path_model, "wb"))
564 | dump(self.sc, open(path_scaler, "wb"))
565 | else:
566 | dump(kwargs.get("model"), open(path_model, "wb"))
567 | dump(kwargs.get("scaler"), open(path_scaler, "wb"))
568 | if not best:
569 | print("Model Saved at {} and Scaler at {}".format(path_model, path_scaler))
570 | return path_model, path_scaler
571 |
572 | def __load(self, path=None):
573 | """
574 | Loads model and scaler from the specified path
575 | Args:
576 | path ([list]): [List containing path to load the model and scaler.]
577 | Example: path = ["model.pkl", "scaler.pkl"]
578 |
579 | Returns:
580 | [Model] : [Loaded model]
581 | [Scaler] : [Loaded scaler]
582 | """
583 |
584 | model_path = path[0] if path[0] else None
585 | scaler_path = path[1] if path[1] else None
586 | if not ".pkl" in model_path and not model_path == None:
587 | raise TypeError(
588 | "[Error] Model Filetype not supported. Please use .pkl type "
589 | )
590 | if not ".pkl" in scaler_path and not scaler_path == None:
591 | raise TypeError(
592 | "[Error] Scaler Filetype not supported. Please use .pkl type "
593 | )
594 | if model_path != None and scaler_path != None:
595 | model = load(open(model_path, "rb"))
596 | scaler = load(open(scaler_path, "rb"))
597 | print(
598 | Fore.GREEN
599 | + "[Info] Model and Scaler Loaded from {} and {}".format(
600 | model_path, scaler_path
601 | )
602 | )
603 | return model, scaler
604 | elif model_path != None and scaler_path == None:
605 | model = load(open(model_path, "rb"))
606 | print(Fore.GREEN + "[Info] Model Loaded from {}".format(model_path))
607 | return model
608 | elif model_path == None and scaler_path != None:
609 | scaler = load(open(scaler_path, "rb"))
610 | print(Fore.GREEN + "[Info] Scaler Loaded from {}".format(scaler_path))
611 | return scaler
612 | else:
613 | raise ValueError("No path specified.Please provide actual path\n")
614 |
615 | def imp_features(self, extensive=False, *args, **kwargs):
616 | """
617 | Returns the importance features of the dataset
618 |
619 | Args:
620 |
621 | extensive (bool): [If True shows the importance of all features exitensively and will take more time] [default = False]
622 | **args: [Additional arguments]
623 | **kwargs: [Additional keyword arguments]
624 | """
625 | if self.original_predictor == "all":
626 | raise TypeError(
627 | "[Error] This method is only applicable on single predictor"
628 | )
629 | if not extensive:
630 | self.preprocesspermutational_feature_imp(
631 | self.features, self.X_train, self.y_train, model=self.classifier
632 | )
633 | if extensive:
634 | self.preprocessshap_feature_imp(
635 | self.features, self.X_train, model=self.classifier, *args, **kwargs
636 | )
637 |
--------------------------------------------------------------------------------
/luciferml/supervised/regression.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import os
3 | import time
4 | import warnings
5 | from pickle import dump, load
6 |
7 | import numpy as np
8 | import optuna
9 | import pandas as pd
10 | from colorama import Fore
11 | from IPython.display import display
12 | from luciferml.supervised.utils.best import Best
13 | from luciferml.supervised.utils.configs import *
14 | from luciferml.supervised.utils.predictors import regression_predictor
15 | from luciferml.supervised.utils.preprocesser import PreProcesser
16 | from luciferml.supervised.utils.tuner.luciferml_tuner import luciferml_tuner
17 | from luciferml.supervised.utils.validator import *
18 | from optuna.samplers._tpe.sampler import TPESampler
19 | from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
20 |
21 |
22 | class Regression:
23 | def __init__(
24 | self,
25 | predictor=["lin"],
26 | params={},
27 | tune=False,
28 | test_size=0.2,
29 | cv_folds=10,
30 | random_state=42,
31 | pca_kernel="linear",
32 | n_components_lda=1,
33 | lda="n",
34 | pca="n",
35 | n_components_pca=2,
36 | loss="mean_squared_error",
37 | validation_split=0.20,
38 | smote="n",
39 | k_neighbors=1,
40 | verbose=False,
41 | exclude_models=[],
42 | path=None,
43 | optuna_sampler=TPESampler(multivariate=True),
44 | optuna_direction="maximize",
45 | optuna_n_trials=100,
46 | optuna_metric="r2",
47 | ):
48 | """
49 | Encodes Categorical Data then Applies SMOTE , Splits the features and labels in training and validation sets with test_size = .2\n
50 | scales X_train, X_val using StandardScaler.\n
51 | Fits every model on training set and predicts results,Finds R2 Score and mean square error\n
52 | finds accuracy of model applies K-Fold Cross Validation\n
53 | and stores its accuracies in a dictionary containing Model name as Key and accuracies as values and returns it\n
54 | Applies HyperParam Tuning and gives best params and accuracy.\n
55 |
56 | Parameters:
57 |
58 | features : array
59 | features array
60 | lables : array
61 | labels array
62 | predictor : list
63 | Predicting models to be used
64 | Default ['lin'] - 'Linear Regression'\n
65 | Available Predictors:
66 | lin - Linear Regression\n
67 | sgd - Stochastic Gradient Descent Regressor\n
68 | elas - Elastic Net Regressor\n
69 | krr - Kernel Ridge Regressor\n
70 | br - Bayesian Ridge Regressor\n
71 | svr - Support Vector Regressor\n
72 | knr - K-Nearest Regressor\n
73 | dt - Decision Trees\n
74 | rfr - Random Forest Regressor\n
75 | gbr - Gradient Boost Regressor\n
76 | ada - AdaBoost Regressor,\n
77 | bag - Bagging Regressor,\n
78 | extr - Extra Trees Regressor,\n
79 | lgbm - LightGB Regressor\n
80 | xgb - XGBoost Regressor\n
81 | cat - Catboost Regressor\n
82 | ann - Multi Layer Perceptron Regressor\n
83 | all - Applies all above regressors\n
84 | params : dict
85 | contains parameters for model
86 | tune : boolean
87 | when True Applies GridSearch CrossValidation
88 | Default is False
89 | test_size: float or int, default=.2
90 | If float, should be between 0.0 and 1.0 and represent
91 | the proportion of the dataset to include in
92 | the test split.
93 | If int, represents the absolute number of test samples.
94 | cv_folds : int
95 | No. of cross validation folds. Default = 10
96 | pca : str
97 | if 'y' will apply PCA on Train and Validation set. Default = 'n'
98 | lda : str
99 | if 'y' will apply LDA on Train and Validation set. Default = 'n'
100 | pca_kernel : str
101 | Kernel to be use in PCA. Default = 'linear'
102 | n_components_lda : int
103 | No. of components for LDA. Default = 1
104 | n_components_pca : int
105 | No. of components for PCA. Default = 2
106 | loss : str
107 | loss method for ann. Default = 'mean_squared_error'
108 | smote : str,
109 | Whether to apply SMOTE. Default = 'y'
110 | k_neighbors : int
111 | No. of neighbours for SMOTE. Default = 1
112 | verbose : boolean
113 | Verbosity of models. Default = False
114 | exclude_models : list
115 | List of models to be excluded when using predictor = 'all' . Default = []
116 | path : list
117 | List containing path to saved model and scaler. Default = None
118 | Example: [model.pkl, scaler.pkl]
119 | random_state : int
120 | Random random_state for reproducibility. Default = 42
121 | optuna_sampler : Function
122 | Sampler to be used in optuna. Default = TPESampler()
123 | optuna_direction : str
124 | Direction of optimization. Default = 'maximize'
125 | Available Directions:
126 | maximize : Maximize
127 | minimize : Minimize
128 | optuna_n_trials : int
129 | No. of trials for optuna. Default = 100
130 | optuna_metric: str
131 | Metric to be used in optuna. Default = 'r2'
132 | Returns:
133 |
134 | Dict Containing Name of Regressor, Its K-Fold Cross Validated Accuracy, RMSE, Prediction set
135 |
136 | Dataframe containing all the models and their accuracies when predictor is 'all'
137 |
138 | Example:
139 |
140 | from luciferml.supervised.regression import Regression
141 |
142 | dataset = pd.read_excel('examples\Folds5x2_pp.xlsx')
143 |
144 | X = dataset.iloc[:, :-1]
145 |
146 | y = dataset.iloc[:, -1]
147 |
148 | regressor = Regression(predictor = 'lin')
149 |
150 | regressor.fit(X, y)
151 |
152 | result = regressor.result()
153 |
154 | """
155 | self.preprocess = PreProcesser()
156 | if type(predictor) == list:
157 | if not "all" in predictor:
158 | self.predictor = predictor[0] if len(predictor) == 1 else predictor
159 | else:
160 | self.predictor = predictor
161 | else:
162 | self.predictor = predictor
163 | bool_pred, pred = pred_check(predictor, pred_type="regression")
164 | if not bool_pred:
165 | raise ValueError(unsupported_pred_warning.format(pred))
166 | self.original_predictor = predictor
167 | self.params = params
168 | self.tune = tune
169 | self.test_size = test_size
170 | self.cv_folds = cv_folds
171 | self.random_state = random_state
172 | self.pca_kernel = pca_kernel
173 | self.n_components_lda = n_components_lda
174 | self.lda = lda
175 | self.pca = pca
176 | self.n_components_pca = n_components_pca
177 | self.loss = loss
178 | self.validation_split = validation_split
179 | self.rerun = False
180 | self.smote = smote
181 | self.k_neighbors = k_neighbors
182 | self.verbose = verbose
183 | self.exclude_models = exclude_models
184 | self.sampler = optuna_sampler
185 | self.direction = optuna_direction
186 | self.n_trials = optuna_n_trials
187 | self.metric = optuna_metric
188 |
189 | self.accuracy_scores = {}
190 | self.reg_result = {}
191 | self.rm_squared_error = 0
192 | self.accuracy = 0
193 | self.y_pred = []
194 | self.kfold_accuracy = 0
195 | self.regressor_name = ""
196 | self.sc = 0
197 |
198 | self.kfoldacc = []
199 | self.acc = []
200 | self.mae = []
201 | self.rmse = []
202 | self.bestacc = []
203 | self.bestparams = []
204 | self.regressor_model = []
205 | self.tuned_trained_model = []
206 | self.best_regressor_path = ""
207 | self.scaler_path = ""
208 | self.result_df = pd.DataFrame(index=None)
209 | self.regressors = copy.deepcopy(regressors)
210 | for i in self.exclude_models:
211 | self.regressors.pop(i)
212 | self.best_regressor = "First Run the Predictor in All mode"
213 | self.objective = None
214 | self.pred_mode = ""
215 | self.model_to_predict = None
216 |
217 | if path != None:
218 | try:
219 | self.regressor, self.sc = self.__load(path)
220 | except Exception as e:
221 | print(Fore.RED + e)
222 | print(Fore.RED + "Model not found")
223 | if not self.verbose:
224 | optuna.logging.set_verbosity(optuna.logging.WARNING)
225 |
226 | def fit(self, features, labels):
227 | """[Takes Features and Labels and Encodes Categorical Data then Applies SMOTE , Splits the features and labels in training and validation sets with test_size = .2
228 | scales X_train, X_val using StandardScaler.
229 | Fits model on training set and predicts results, Finds R2 Score and mean square error
230 | finds accuracy of model applies K-Fold Cross Validation
231 | and stores its accuracies in a dictionary containing Model name as Key and accuracies as values and returns it
232 | Applies GridSearch Cross Validation and gives best params out from param list.]
233 |
234 | Args:
235 |
236 | features ([Pandas DataFrame]): [DataFrame containing Features]
237 | labels ([Pandas DataFrame]): [DataFrame containing Labels]
238 | """
239 |
240 | self.features = features
241 | self.labels = labels
242 |
243 | # Time Function ---------------------------------------------------------------------
244 |
245 | self.start = time.time()
246 | print(Fore.MAGENTA + intro, "\n")
247 | print(Fore.GREEN + "Started LuciferML [", "\u2713", "]\n")
248 | if not self.rerun:
249 | # CHECKUP ---------------------------------------------------------------------
250 | if not isinstance(self.features, pd.DataFrame) and not isinstance(
251 | self.labels, pd.Series
252 | ):
253 | print(
254 | Fore.RED
255 | + "TypeError: This Function take features as Pandas Dataframe and labels as Pandas Series. Please check your implementation.\n"
256 | )
257 | end = time.time()
258 | print(self.end - self.start)
259 | return
260 | print(Fore.YELLOW + "Preprocessing Started [*]\n")
261 |
262 | self.features, self.labels = self.preprocess.encoder(
263 | self.features, self.labels
264 | )
265 | self.features, self.labels = sparse_check(self.features, self.labels)
266 | (
267 | self.X_train,
268 | self.X_val,
269 | self.y_train,
270 | self.y_val,
271 | self.sc,
272 | ) = self.preprocess.data_preprocess(
273 | self.features,
274 | self.labels,
275 | self.test_size,
276 | self.random_state,
277 | self.smote,
278 | self.k_neighbors,
279 | )
280 | self.X_train, self.X_val = self.preprocess.dimensionality_reduction(
281 | self.lda,
282 | self.pca,
283 | self.X_train,
284 | self.X_val,
285 | self.y_train,
286 | self.n_components_lda,
287 | self.n_components_pca,
288 | self.pca_kernel,
289 | self.start,
290 | )
291 |
292 | print(Fore.GREEN + "Preprocessing Done [", "\u2713", "]\n")
293 |
294 | if self.original_predictor == "all" or type(self.predictor) == list:
295 | if 'all' in self.predictor and type(self.predictor)==list:
296 | self.predictor.remove('all')
297 | self.model_to_predict = (
298 | self.predictor if len(self.predictor) > 1 and type(self.predictor) == list else self.regressors
299 | )
300 | self.result_df["Name"] = (
301 | list(self.regressors[i] for i in self.predictor)
302 | if type(self.predictor) == list and len(self.predictor) > 1
303 | else list(self.regressors.values())
304 | )
305 | self.pred_mode = "all" if type(self.predictor) == list and len(
306 | self.predictor) > 1 else "single"
307 | self.__fitall()
308 | return
309 | self.regressor, self.objective = regression_predictor(
310 | self.predictor,
311 | self.params,
312 | self.X_train,
313 | self.y_train,
314 | self.cv_folds,
315 | self.random_state,
316 | self.metric,
317 | verbose=self.verbose,
318 | )
319 | try:
320 | self.regressor.fit(self.X_train, self.y_train)
321 | except Exception as error:
322 | print(Fore.RED + "Regressor Build Failed with error: ", error, "\n")
323 | finally:
324 | print(Fore.GREEN + "Model Trained Successfully [", "\u2713", "]\n")
325 |
326 | try:
327 | print(Fore.YELLOW + "Evaluating Model Performance [*]\n")
328 | self.y_pred = self.regressor.predict(self.X_val)
329 | self.accuracy = r2_score(self.y_val, self.y_pred)
330 | self.m_absolute_error = mean_absolute_error(self.y_val, self.y_pred)
331 | self.rm_squared_error = mean_squared_error(
332 | self.y_val, self.y_pred, squared=False
333 | )
334 | print(
335 | Fore.CYAN
336 | + " Validation R2 Score is {:.2f} %".format(self.accuracy * 100)
337 | )
338 | print(
339 | Fore.CYAN + " Validation Mean Absolute Error is :",
340 | self.m_absolute_error,
341 | )
342 | print(
343 | Fore.CYAN + " Validation Root Mean Squared Error is :",
344 | self.rm_squared_error,
345 | )
346 | self.regressor_name, self.kfold_accuracy = kfold(
347 | self.regressor,
348 | self.predictor,
349 | self.X_train,
350 | self.y_train,
351 | self.cv_folds,
352 | isReg=True,
353 | )
354 | except Exception as error:
355 | print(Fore.RED + "Model Evaluation Failed with error: ", error, "\n")
356 | finally:
357 | print(Fore.GREEN + "Model Evaluation Completed [", "\u2713", "]\n")
358 |
359 | if not self.predictor == "nb" and self.tune:
360 | self.__tuner()
361 |
362 | print(Fore.GREEN + "Completed LuciferML Run [", "\u2713", "]\n")
363 | self.end = time.time()
364 | final_time = self.end - self.start
365 | print(Fore.BLUE + "Time Elapsed : ", f"{final_time:.2f}", "seconds \n")
366 |
367 | def __fitall(self):
368 | print(Fore.YELLOW + "Training LuciferML [*]\n")
369 | if self.params != {}:
370 | warnings.warn(params_use_warning, UserWarning)
371 | self.params = {}
372 | for _, self.predictor in enumerate(self.model_to_predict):
373 | if not self.predictor in self.exclude_models:
374 | (self.regressor, self.objective,) = regression_predictor(
375 | self.predictor,
376 | self.params,
377 | self.X_train,
378 | self.y_train,
379 | self.cv_folds,
380 | self.random_state,
381 | self.metric,
382 | mode="multi",
383 | verbose=self.verbose,
384 | )
385 | try:
386 | self.regressor.fit(self.X_train, self.y_train)
387 | except Exception as error:
388 | print(
389 | Fore.RED + regressors[self.predictor],
390 | "Model Train Failed with error: ",
391 | error,
392 | "\n",
393 | )
394 | try:
395 | self.y_pred = self.regressor.predict(self.X_val)
396 | self.accuracy = r2_score(self.y_val, self.y_pred)
397 | self.m_absolute_error = mean_absolute_error(self.y_val, self.y_pred)
398 | self.rm_squared_error = mean_squared_error(
399 | self.y_val, self.y_pred, squared=False
400 | )
401 | self.acc.append(self.accuracy * 100)
402 | self.rmse.append(self.rm_squared_error)
403 | self.mae.append(self.m_absolute_error)
404 | self.regressor_name, self.kfold_accuracy = kfold(
405 | self.regressor,
406 | self.predictor,
407 | self.X_train,
408 | self.y_train,
409 | self.cv_folds,
410 | all_mode=True,
411 | isReg=True,
412 | )
413 | self.kfoldacc.append(self.kfold_accuracy)
414 | self.regressor_model.append(self.regressor)
415 | except Exception as error:
416 | print(
417 | Fore.RED + regressors[self.predictor],
418 | "Evaluation Failed with error: ",
419 | error,
420 | "\n",
421 | )
422 |
423 | if self.tune:
424 | self.__tuner(all_mode=True, single_mode=False)
425 | if self.predictor == "nb":
426 | self.best_params = ""
427 | self.best_accuracy = self.kfold_accuracy
428 | self.result_df["R2 Score"] = self.acc
429 | self.result_df["Mean Absolute Error"] = self.mae
430 | self.result_df["Root Mean Squared Error"] = self.rmse
431 | self.result_df["KFold Accuracy"] = self.kfoldacc
432 | self.result_df["Model"] = self.regressor_model
433 |
434 | if self.tune:
435 | self.result_df["Best Parameters"] = self.bestparams
436 | self.result_df["Best Accuracy"] = self.bestacc
437 | self.result_df["Trained Model"] = self.tuned_trained_model
438 | self.best_regressor = Best(
439 | self.result_df.loc[self.result_df["Best Accuracy"].idxmax()],
440 | self.tune,
441 | isReg=True,
442 | )
443 | else:
444 | self.best_regressor = Best(
445 | self.result_df.loc[self.result_df["KFold Accuracy"].idxmax()],
446 | self.tune,
447 | isReg=True,
448 | )
449 | print(Fore.GREEN + "Training Done [", "\u2713", "]\n")
450 | print(Fore.CYAN + "Results Below\n")
451 | display(self.result_df)
452 | print(Fore.GREEN + "\nCompleted LuciferML Run [", "\u2713", "]\n")
453 | if len(self.model_to_predict) > 1:
454 | self.best_regressor_path, self.scaler_path = self.save(
455 | best=True, model=self.best_regressor.model, scaler=self.sc
456 | )
457 | print(
458 | Fore.CYAN
459 | + "Saved Best Model to {} and its scaler to {}".format(
460 | self.best_regressor_path, self.scaler_path
461 | ),
462 | "\n",
463 | )
464 | self.end = time.time()
465 | final_time = self.end - self.start
466 | print(Fore.BLUE + "Time Elapsed : ", f"{final_time:.2f}", "seconds \n")
467 | return
468 |
469 | def __tuner(self, all_mode=False, single_mode=True):
470 | if not all_mode or single_mode:
471 | print(Fore.YELLOW + "Tuning Started [*]\n")
472 | if not self.predictor == "nb":
473 | (
474 | self.best_params,
475 | self.best_accuracy,
476 | self.best_trained_model,
477 | ) = luciferml_tuner(
478 | self.predictor,
479 | self.objective,
480 | self.n_trials,
481 | self.sampler,
482 | self.direction,
483 | self.X_train,
484 | self.y_train,
485 | self.cv_folds,
486 | self.random_state,
487 | self.metric,
488 | all_mode=all_mode,
489 | isReg=True,
490 | )
491 | if self.predictor == "nb":
492 | self.best_params = "Not Applicable"
493 | self.best_accuracy = 0
494 | self.bestparams.append(self.best_params)
495 | self.bestacc.append(self.best_accuracy * 100)
496 | self.tuned_trained_model.append(self.best_trained_model)
497 | if not all_mode or single_mode:
498 | print(Fore.GREEN + "Tuning Done [", "\u2713", "]\n")
499 |
500 | def result(self):
501 | """[Makes a dictionary containing Regressor Name, K-Fold CV Accuracy, RMSE, Prediction set.]
502 |
503 | Returns:
504 |
505 | [dict]: [Dictionary containing :
506 | - "Regressor" - Regressor Name
507 | - "Accuracy" - KFold CV Accuracy
508 | - "RMSE" - Root Mean Square
509 | - "YPred" - Array for Prediction set
510 | ]
511 | [dataframe] : [Dataset containing accuracy and best_params
512 | for all predictors only when predictor = 'all' is used
513 | ]
514 | """
515 | if not self.pred_mode == "all":
516 | self.reg_result["Regressor"] = self.regressor_name
517 | self.reg_result["Accuracy"] = self.kfold_accuracy
518 | self.reg_result["RMSE"] = self.rm_squared_error
519 | self.reg_result["YPred"] = self.y_pred
520 |
521 | return self.reg_result
522 | if self.pred_mode == "all":
523 | return self.result_df
524 |
525 | def predict(self, X_test):
526 | """[Takes test set and returns predictions for that test set]
527 |
528 | Args:
529 | X_test ([Array]): [Array Containing Test Set]
530 |
531 | Returns:
532 | [Array]: [Predicted set for given test set]
533 | """
534 | if not self.pred_mode == "all":
535 | X_test = np.array(X_test)
536 | if X_test.ndim == 1:
537 | X_test = X_test.reshape(1, -1)
538 |
539 | y_test = self.regressor.predict(self.sc.transform(X_test))
540 |
541 | return y_test
542 | if self.pred_mode == "all":
543 | raise TypeError("Predict is only applicable on single predictor")
544 |
545 | def save(self, path=None, best=False, **kwargs):
546 | """
547 | Saves the model and its scaler to a file provided with a path.
548 | If no path is provided will create a directory named
549 | lucifer_ml_info/models/ and lucifer_ml_info/scaler/ in current working directory
550 |
551 | Args:
552 |
553 | path ([list]): [List containing path to save the model and scaler.]
554 | Example: path = ["model.pkl", "scaler.pkl"]
555 |
556 | Returns:
557 |
558 | Path to the saved model and its scaler.
559 | """
560 | if not type(path) == list and path != None:
561 | raise TypeError("Path must be a list")
562 | if self.pred_mode == "all" and best == False:
563 | raise TypeError("Cannot save model for all predictors")
564 | dir_path_model = path[0] if path else "lucifer_ml_info/models/regression/"
565 | dir_path_scaler = path[1] if path else "lucifer_ml_info/scalers/regression/"
566 | model_name = regressors[self.predictor].replace(" ", "_")
567 | if best:
568 | dir_path_model = "lucifer_ml_info/best/regression/models/"
569 | dir_path_scaler = "lucifer_ml_info/best/regression/scalers/"
570 | model_name = self.best_regressor.name.replace(" ", "_")
571 | os.makedirs(dir_path_model, exist_ok=True)
572 | os.makedirs(dir_path_scaler, exist_ok=True)
573 | timestamp = str(int(time.time()))
574 | path_model = dir_path_model + model_name + "_" + timestamp + ".pkl"
575 | path_scaler = (
576 | dir_path_scaler + model_name + "_" + "Scaler" + "_" + timestamp + ".pkl"
577 | )
578 | if (
579 | not kwargs.get("model")
580 | and not kwargs.get("best")
581 | and not kwargs.get("scaler")
582 | ):
583 | dump(self.regressor, open(path_model, "wb"))
584 | dump(self.sc, open(path_scaler, "wb"))
585 | else:
586 | dump(kwargs.get("model"), open(path_model, "wb"))
587 | dump(kwargs.get("scaler"), open(path_scaler, "wb"))
588 | if not best:
589 | print("Model Saved at {} and Scaler at {}".format(path_model, path_scaler))
590 | return path_model, path_scaler
591 |
592 | def __load(self, path=None):
593 | """
594 | Loads model and scaler from the specified path
595 |
596 | Args:
597 |
598 | path ([list]): [List containing path to load the model and scaler.]
599 | Example: path = ["model.pkl", "scaler.pkl"]
600 |
601 | Returns:
602 | [Model] : [Loaded model]
603 | [Scaler] : [Loaded scaler]
604 | """
605 | model_path = path[0] if path[0] else None
606 | scaler_path = path[1] if path[1] else None
607 | if not ".pkl" in model_path and not model_path == None:
608 | raise TypeError(
609 | "[Error] Model Filetype not supported. Please use .pkl type "
610 | )
611 | if not ".pkl" in scaler_path and not scaler_path == None:
612 | raise TypeError(
613 | "[Error] Scaler Filetype not supported. Please use .pkl type "
614 | )
615 | if model_path != None and scaler_path != None:
616 | model = load(open(model_path, "rb"))
617 | scaler = load(open(scaler_path, "rb"))
618 | print(
619 | Fore.GREEN
620 | + "[Info] Model and Scaler Loaded from {} and {}".format(
621 | model_path, scaler_path
622 | )
623 | )
624 | return model, scaler
625 | elif model_path != None and scaler_path == None:
626 | model = load(open(model_path, "rb"))
627 | print(Fore.GREEN + "[Info] Model Loaded from {}".format(model_path))
628 | return model
629 | elif model_path == None and scaler_path != None:
630 | scaler = load(open(scaler_path, "rb"))
631 | print(Fore.GREEN + "[Info] Scaler Loaded from {}".format(scaler_path))
632 | return scaler
633 | else:
634 | raise ValueError("No path specified.Please provide actual path\n")
635 |
636 | def imp_features(self, extensive=False, *args, **kwargs):
637 | """
638 | Returns the importance features of the dataset
639 |
640 | Args:
641 |
642 | extensive (bool): [If True shows the importance of all features exitensively and will take more time] [default = False]
643 | **args: [Additional arguments]
644 | **kwargs: [Additional keyword arguments]
645 | """
646 | if self.original_predictor == "all":
647 | raise TypeError(
648 | "[Error] This method is only applicable on single predictor"
649 | )
650 | if not extensive:
651 | self.preprocess.permutational_feature_imp(
652 | self.features, self.X_train, self.y_train, model=self.regressor
653 | )
654 | if extensive:
655 | self.preprocess.shap_feature_imp(
656 | self.features, self.X_train, model=self.regressor, *args, **kwargs
657 | )
658 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------