multimodel-analysis 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- multimodel_analysis-0.0.1/LICENSE +201 -0
- multimodel_analysis-0.0.1/MANIFEST.in +2 -0
- multimodel_analysis-0.0.1/PKG-INFO +211 -0
- multimodel_analysis-0.0.1/README.md +182 -0
- multimodel_analysis-0.0.1/multimodel_analysis/__init__.py +7 -0
- multimodel_analysis-0.0.1/multimodel_analysis/multimodel.py +407 -0
- multimodel_analysis-0.0.1/multimodel_analysis.egg-info/PKG-INFO +211 -0
- multimodel_analysis-0.0.1/multimodel_analysis.egg-info/SOURCES.txt +12 -0
- multimodel_analysis-0.0.1/multimodel_analysis.egg-info/dependency_links.txt +1 -0
- multimodel_analysis-0.0.1/multimodel_analysis.egg-info/requires.txt +5 -0
- multimodel_analysis-0.0.1/multimodel_analysis.egg-info/top_level.txt +1 -0
- multimodel_analysis-0.0.1/requirements.txt +5 -0
- multimodel_analysis-0.0.1/setup.cfg +4 -0
- multimodel_analysis-0.0.1/setup.py +30 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2025] [Uditya Narayan Tiwari]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: multimodel_analysis
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: A Python Package for Automatic Multi-Model Analysis (Classification & Regression)
|
|
5
|
+
Author: Uditya Narayan Tiwari
|
|
6
|
+
Author-email: tiwarimerit@gmail.com
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: pandas
|
|
17
|
+
Requires-Dist: matplotlib
|
|
18
|
+
Requires-Dist: seaborn
|
|
19
|
+
Requires-Dist: scikit-learn
|
|
20
|
+
Dynamic: author
|
|
21
|
+
Dynamic: author-email
|
|
22
|
+
Dynamic: classifier
|
|
23
|
+
Dynamic: description
|
|
24
|
+
Dynamic: description-content-type
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
Dynamic: requires-dist
|
|
27
|
+
Dynamic: requires-python
|
|
28
|
+
Dynamic: summary
|
|
29
|
+
|
|
30
|
+
# Multi-Model Analysis
|
|
31
|
+
|
|
32
|
+
[](https://pypi.org/project/multimodel_analysis/)
|
|
33
|
+
[](https://opensource.org/licenses/MIT)
|
|
34
|
+
|
|
35
|
+
**multimodel_analysis** is a comprehensive machine learning library created by **Uditya Narayan Tiwari**. It automates the process of training, evaluating, and visualizing multiple models for both Classification and Regression tasks.
|
|
36
|
+
|
|
37
|
+
Designed for data scientists and researchers, it streamlines model selection by providing automatic feature scaling, detailed performance metrics, and professional-grade visualizations in just a few lines of code.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 📦 Installation
|
|
42
|
+
|
|
43
|
+
### Install via PyPI
|
|
44
|
+
The easiest way to install the package is via pip:
|
|
45
|
+
```bash
|
|
46
|
+
pip install multimodel_analysis
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Install from GitHub
|
|
51
|
+
|
|
52
|
+
To get the latest development version:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install git+[https://github.com/udityamerit/multimodel_analysis.git](https://github.com/udityamerit/Multimodel-Analysis-Pacakge.git) --upgrade --force-reinstall
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 📋 Requirements
|
|
60
|
+
|
|
61
|
+
* `numpy`
|
|
62
|
+
* `pandas`
|
|
63
|
+
* `matplotlib`
|
|
64
|
+
* `seaborn`
|
|
65
|
+
* `scikit-learn`
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## How to Use
|
|
70
|
+
|
|
71
|
+
### 1. Classification Analysis
|
|
72
|
+
|
|
73
|
+
Use `MultiModelClassifier` for categorical target variables. It automatically compares models like Logistic Regression, SVM, Decision Trees, Random Forest, Gradient Boosting, and more.
|
|
74
|
+
|
|
75
|
+
#### Step 1: Initialize and Train
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import pandas as pd
|
|
79
|
+
from multimodel_analysis import MultiModelClassifier
|
|
80
|
+
|
|
81
|
+
# Load your dataset
|
|
82
|
+
df = pd.read_csv('your_classification_data.csv')
|
|
83
|
+
X = df.drop('target_column', axis=1)
|
|
84
|
+
y = df['target_column']
|
|
85
|
+
|
|
86
|
+
# Initialize the classifier
|
|
87
|
+
# scaled_data=True applies StandardScaler automatically
|
|
88
|
+
classifier = MultiModelClassifier(X, y, test_size=0.3, scaled_data=True)
|
|
89
|
+
|
|
90
|
+
# Train all models and get results
|
|
91
|
+
results = classifier.run_all_models()
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
#### Step 2: View Metrics & Best Model
|
|
96
|
+
|
|
97
|
+
Generates a clean dataframe of metrics (Accuracy, Precision, Recall, F1, AUC) and prints the best recommendation.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
classifier.show_tabular_report(results)
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### Step 3: Visualize Confusion Matrices
|
|
105
|
+
|
|
106
|
+
Plots confusion matrices for every trained model with distinct color palettes.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
classifier.plot_confusion_matrices(results)
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
#### Step 4: Plot ROC Curves
|
|
114
|
+
|
|
115
|
+
Overlays ROC curves for all models to compare Area Under the Curve (AUC) performance.
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
classifier.plot_roc_curves(results)
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
#### Step 5: Compare All Metrics
|
|
123
|
+
|
|
124
|
+
Plots a grouped bar chart comparing Accuracy, Precision, Recall, and F1 Score.
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
classifier.plot_comparison(results)
|
|
128
|
+
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
### 2. Regression Analysis
|
|
134
|
+
|
|
135
|
+
Use `MultiModelRegressior` for continuous target variables. It compares Linear Regression, Lasso, Ridge, SVR, Random Forest, Gradient Boosting, etc.
|
|
136
|
+
|
|
137
|
+
#### Step 1: Initialize and Train
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from multimodel_analysis import MultiModelRegressior
|
|
141
|
+
|
|
142
|
+
# Load your dataset
|
|
143
|
+
df = pd.read_csv('your_regression_data.csv')
|
|
144
|
+
X = df.drop('price', axis=1)
|
|
145
|
+
y = df['price']
|
|
146
|
+
|
|
147
|
+
# Initialize the regressor
|
|
148
|
+
regressor = MultiModelRegressior(X, y, test_size=0.3, scaled_data=True)
|
|
149
|
+
|
|
150
|
+
# Train all models
|
|
151
|
+
results = regressor.run_all_models()
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
#### Step 2: View Metrics & Best Model
|
|
156
|
+
|
|
157
|
+
Generates a table of MAE, MSE, RMSE, and R2 Scores, and recommends the best model based on R2.
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
regressor.show_tabular_report(results)
|
|
161
|
+
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
#### Step 3: True vs. Predicted Plots
|
|
165
|
+
|
|
166
|
+
Visualizes the relationship between actual and predicted values with an ideal fit line.
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
regressor.plot_true_vs_predicted(results)
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
#### Step 4: Compare R2 Scores
|
|
174
|
+
|
|
175
|
+
Plots a bar chart to easily identify the model with the highest R2 score.
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
regressor.plot_comparison(results)
|
|
179
|
+
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Key Features
|
|
185
|
+
|
|
186
|
+
### 🔹 Intelligent Automation
|
|
187
|
+
|
|
188
|
+
* **Automatic Scaling**: Simply set `scaled_data=True` to standardize your features using `StandardScaler` before training.
|
|
189
|
+
* **Best Model Detection**: Automatically highlights the best performing model based on Accuracy (Classification) or R2 Score (Regression).
|
|
190
|
+
|
|
191
|
+
### 🔹 Professional Visualizations
|
|
192
|
+
|
|
193
|
+
* **Colorful Confusion Matrices**: Automatically cycles through color maps (Blues, Greens, Oranges, etc.) for distinct model visualization.
|
|
194
|
+
* **ROC Curve Overlays**: clean comparison of True Positive vs False Positive rates.
|
|
195
|
+
* **Regression Fit Plots**: Scatter plots with diagonal reference lines to visually assess regression performance.
|
|
196
|
+
|
|
197
|
+
### 🔹 Extensive Model Library
|
|
198
|
+
|
|
199
|
+
* **Classifiers**: Logistic Regression, SVM, Decision Tree, KNN, Naive Bayes, Random Forest, Gradient Boosting, AdaBoost.
|
|
200
|
+
* **Regressors**: Linear Regression, Lasso, Ridge, SVR, Decision Tree, Random Forest, Gradient Boosting.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## 👨💻 Author
|
|
205
|
+
|
|
206
|
+
**Uditya Narayan Tiwari**
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
## 📄 License
|
|
210
|
+
|
|
211
|
+
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# Multi-Model Analysis
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/multimodel_analysis/)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
**multimodel_analysis** is a comprehensive machine learning library created by **Uditya Narayan Tiwari**. It automates the process of training, evaluating, and visualizing multiple models for both Classification and Regression tasks.
|
|
7
|
+
|
|
8
|
+
Designed for data scientists and researchers, it streamlines model selection by providing automatic feature scaling, detailed performance metrics, and professional-grade visualizations in just a few lines of code.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 📦 Installation
|
|
13
|
+
|
|
14
|
+
### Install via PyPI
|
|
15
|
+
The easiest way to install the package is via pip:
|
|
16
|
+
```bash
|
|
17
|
+
pip install multimodel_analysis
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### Install from GitHub
|
|
22
|
+
|
|
23
|
+
To get the latest development version:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install git+[https://github.com/udityamerit/multimodel_analysis.git](https://github.com/udityamerit/Multimodel-Analysis-Pacakge.git) --upgrade --force-reinstall
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### 📋 Requirements
|
|
31
|
+
|
|
32
|
+
* `numpy`
|
|
33
|
+
* `pandas`
|
|
34
|
+
* `matplotlib`
|
|
35
|
+
* `seaborn`
|
|
36
|
+
* `scikit-learn`
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## How to Use
|
|
41
|
+
|
|
42
|
+
### 1. Classification Analysis
|
|
43
|
+
|
|
44
|
+
Use `MultiModelClassifier` for categorical target variables. It automatically compares models like Logistic Regression, SVM, Decision Trees, Random Forest, Gradient Boosting, and more.
|
|
45
|
+
|
|
46
|
+
#### Step 1: Initialize and Train
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import pandas as pd
|
|
50
|
+
from multimodel_analysis import MultiModelClassifier
|
|
51
|
+
|
|
52
|
+
# Load your dataset
|
|
53
|
+
df = pd.read_csv('your_classification_data.csv')
|
|
54
|
+
X = df.drop('target_column', axis=1)
|
|
55
|
+
y = df['target_column']
|
|
56
|
+
|
|
57
|
+
# Initialize the classifier
|
|
58
|
+
# scaled_data=True applies StandardScaler automatically
|
|
59
|
+
classifier = MultiModelClassifier(X, y, test_size=0.3, scaled_data=True)
|
|
60
|
+
|
|
61
|
+
# Train all models and get results
|
|
62
|
+
results = classifier.run_all_models()
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
#### Step 2: View Metrics & Best Model
|
|
67
|
+
|
|
68
|
+
Generates a clean dataframe of metrics (Accuracy, Precision, Recall, F1, AUC) and prints the best recommendation.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
classifier.show_tabular_report(results)
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
#### Step 3: Visualize Confusion Matrices
|
|
76
|
+
|
|
77
|
+
Plots confusion matrices for every trained model with distinct color palettes.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
classifier.plot_confusion_matrices(results)
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
#### Step 4: Plot ROC Curves
|
|
85
|
+
|
|
86
|
+
Overlays ROC curves for all models to compare Area Under the Curve (AUC) performance.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
classifier.plot_roc_curves(results)
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
#### Step 5: Compare All Metrics
|
|
94
|
+
|
|
95
|
+
Plots a grouped bar chart comparing Accuracy, Precision, Recall, and F1 Score.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
classifier.plot_comparison(results)
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
### 2. Regression Analysis
|
|
105
|
+
|
|
106
|
+
Use `MultiModelRegressior` for continuous target variables. It compares Linear Regression, Lasso, Ridge, SVR, Random Forest, Gradient Boosting, etc.
|
|
107
|
+
|
|
108
|
+
#### Step 1: Initialize and Train
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from multimodel_analysis import MultiModelRegressior
|
|
112
|
+
|
|
113
|
+
# Load your dataset
|
|
114
|
+
df = pd.read_csv('your_regression_data.csv')
|
|
115
|
+
X = df.drop('price', axis=1)
|
|
116
|
+
y = df['price']
|
|
117
|
+
|
|
118
|
+
# Initialize the regressor
|
|
119
|
+
regressor = MultiModelRegressior(X, y, test_size=0.3, scaled_data=True)
|
|
120
|
+
|
|
121
|
+
# Train all models
|
|
122
|
+
results = regressor.run_all_models()
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
#### Step 2: View Metrics & Best Model
|
|
127
|
+
|
|
128
|
+
Generates a table of MAE, MSE, RMSE, and R2 Scores, and recommends the best model based on R2.
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
regressor.show_tabular_report(results)
|
|
132
|
+
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
#### Step 3: True vs. Predicted Plots
|
|
136
|
+
|
|
137
|
+
Visualizes the relationship between actual and predicted values with an ideal fit line.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
regressor.plot_true_vs_predicted(results)
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
#### Step 4: Compare R2 Scores
|
|
145
|
+
|
|
146
|
+
Plots a bar chart to easily identify the model with the highest R2 score.
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
regressor.plot_comparison(results)
|
|
150
|
+
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Key Features
|
|
156
|
+
|
|
157
|
+
### 🔹 Intelligent Automation
|
|
158
|
+
|
|
159
|
+
* **Automatic Scaling**: Simply set `scaled_data=True` to standardize your features using `StandardScaler` before training.
|
|
160
|
+
* **Best Model Detection**: Automatically highlights the best performing model based on Accuracy (Classification) or R2 Score (Regression).
|
|
161
|
+
|
|
162
|
+
### 🔹 Professional Visualizations
|
|
163
|
+
|
|
164
|
+
* **Colorful Confusion Matrices**: Automatically cycles through color maps (Blues, Greens, Oranges, etc.) for distinct model visualization.
|
|
165
|
+
* **ROC Curve Overlays**: clean comparison of True Positive vs False Positive rates.
|
|
166
|
+
* **Regression Fit Plots**: Scatter plots with diagonal reference lines to visually assess regression performance.
|
|
167
|
+
|
|
168
|
+
### 🔹 Extensive Model Library
|
|
169
|
+
|
|
170
|
+
* **Classifiers**: Logistic Regression, SVM, Decision Tree, KNN, Naive Bayes, Random Forest, Gradient Boosting, AdaBoost.
|
|
171
|
+
* **Regressors**: Linear Regression, Lasso, Ridge, SVR, Decision Tree, Random Forest, Gradient Boosting.
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## 👨💻 Author
|
|
176
|
+
|
|
177
|
+
**Uditya Narayan Tiwari**
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
## 📄 License
|
|
181
|
+
|
|
182
|
+
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
import seaborn as sns
|
|
5
|
+
import warnings
|
|
6
|
+
warnings.filterwarnings('ignore')
|
|
7
|
+
from sklearn.model_selection import train_test_split
|
|
8
|
+
from sklearn.preprocessing import StandardScaler
|
|
9
|
+
from sklearn.utils.multiclass import type_of_target
|
|
10
|
+
|
|
11
|
+
# Classification Models
|
|
12
|
+
from sklearn.linear_model import LogisticRegression
|
|
13
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
14
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
15
|
+
from sklearn.naive_bayes import GaussianNB
|
|
16
|
+
from sklearn.svm import SVC
|
|
17
|
+
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier
|
|
18
|
+
|
|
19
|
+
# Regression Models
|
|
20
|
+
from sklearn.linear_model import LinearRegression, Lasso, Ridge
|
|
21
|
+
from sklearn.tree import DecisionTreeRegressor
|
|
22
|
+
from sklearn.neighbors import KNeighborsRegressor
|
|
23
|
+
from sklearn.svm import SVR
|
|
24
|
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
|
|
25
|
+
|
|
26
|
+
# Metrics
|
|
27
|
+
from sklearn.metrics import (
|
|
28
|
+
accuracy_score, classification_report, confusion_matrix,
|
|
29
|
+
mean_absolute_error, mean_squared_error, r2_score,
|
|
30
|
+
roc_auc_score, roc_curve, precision_score, recall_score, f1_score
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Set professional plotting style
|
|
34
|
+
sns.set_style("whitegrid")
|
|
35
|
+
plt.rcParams.update({'font.size': 12})
|
|
36
|
+
|
|
37
|
+
class MultiModelClassifier:
|
|
38
|
+
|
|
39
|
+
def __init__(self, X, y, test_size=0.3, scaled_data=False):
|
|
40
|
+
self.X = X
|
|
41
|
+
self.y = y
|
|
42
|
+
X_train, X_test, y_train, y_test = train_test_split(self.X, self.y, test_size=test_size, random_state=42)
|
|
43
|
+
|
|
44
|
+
# Initialize Scaler
|
|
45
|
+
self.scaler = StandardScaler()
|
|
46
|
+
|
|
47
|
+
# Logic updated to use 'scaled_data' flag
|
|
48
|
+
if scaled_data:
|
|
49
|
+
self.X_train_scaled = self.scaler.fit_transform(X_train)
|
|
50
|
+
self.X_test_scaled = self.scaler.transform(X_test)
|
|
51
|
+
else:
|
|
52
|
+
self.X_train_scaled = X_train
|
|
53
|
+
self.X_test_scaled = X_test
|
|
54
|
+
|
|
55
|
+
self.y_train = y_train
|
|
56
|
+
self.y_test = y_test
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def evaluate_model(model, X_test, y_true):
|
|
60
|
+
predicted = model.predict(X_test)
|
|
61
|
+
|
|
62
|
+
report = classification_report(y_true, predicted)
|
|
63
|
+
matrix = confusion_matrix(y_true, predicted)
|
|
64
|
+
accuracy = accuracy_score(y_true, predicted)
|
|
65
|
+
|
|
66
|
+
precision = precision_score(y_true, predicted, average='weighted')
|
|
67
|
+
recall = recall_score(y_true, predicted, average='weighted')
|
|
68
|
+
f1 = f1_score(y_true, predicted, average='weighted')
|
|
69
|
+
|
|
70
|
+
if hasattr(model, "predict_proba"):
|
|
71
|
+
y_pred_proba = model.predict_proba(X_test)[:, 1]
|
|
72
|
+
elif hasattr(model, "decision_function"):
|
|
73
|
+
y_pred_proba = model.decision_function(X_test)
|
|
74
|
+
else:
|
|
75
|
+
y_pred_proba = predicted
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
fpr, tpr, _ = roc_curve(y_true, y_pred_proba)
|
|
79
|
+
roc_auc = roc_auc_score(y_true, y_pred_proba)
|
|
80
|
+
except ValueError:
|
|
81
|
+
fpr, tpr, roc_auc = [0], [0], 0.5
|
|
82
|
+
|
|
83
|
+
return report, matrix, accuracy, precision, recall, f1, fpr, tpr, roc_auc
|
|
84
|
+
|
|
85
|
+
def Logistic_model(self):
|
|
86
|
+
model = LogisticRegression()
|
|
87
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
88
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
89
|
+
|
|
90
|
+
def Support_vector_model(self):
|
|
91
|
+
svc = SVC(kernel='linear', probability=True)
|
|
92
|
+
svc.fit(self.X_train_scaled, self.y_train)
|
|
93
|
+
return self.evaluate_model(svc, self.X_test_scaled, self.y_test)
|
|
94
|
+
|
|
95
|
+
def DecisionTree_model(self):
|
|
96
|
+
model = DecisionTreeClassifier()
|
|
97
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
98
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
99
|
+
|
|
100
|
+
def KNN_model(self):
|
|
101
|
+
model = KNeighborsClassifier(n_neighbors=10)
|
|
102
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
103
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
104
|
+
|
|
105
|
+
def Naive_Bayes_model(self):
|
|
106
|
+
model = GaussianNB()
|
|
107
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
108
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
109
|
+
|
|
110
|
+
def RandomForest_model(self):
|
|
111
|
+
model = RandomForestClassifier(n_estimators=100, random_state=42)
|
|
112
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
113
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
114
|
+
|
|
115
|
+
def GradientBoosting_model(self):
|
|
116
|
+
model = GradientBoostingClassifier(n_estimators=100, random_state=42)
|
|
117
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
118
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
119
|
+
|
|
120
|
+
def AdaBoost_model(self):
|
|
121
|
+
model = AdaBoostClassifier(n_estimators=50, random_state=42)
|
|
122
|
+
model.fit(self.X_train_scaled, self.y_train)
|
|
123
|
+
return self.evaluate_model(model, self.X_test_scaled, self.y_test)
|
|
124
|
+
|
|
125
|
+
def run_all_models(self):
|
|
126
|
+
models = [
|
|
127
|
+
('Logistic Regression', *self.Logistic_model()),
|
|
128
|
+
('SVM', *self.Support_vector_model()),
|
|
129
|
+
('Decision Tree', *self.DecisionTree_model()),
|
|
130
|
+
('KNN', *self.KNN_model()),
|
|
131
|
+
('Naive Bayes', *self.Naive_Bayes_model()),
|
|
132
|
+
('Random Forest', *self.RandomForest_model()),
|
|
133
|
+
('Gradient Boosting', *self.GradientBoosting_model()),
|
|
134
|
+
('AdaBoost', *self.AdaBoost_model())
|
|
135
|
+
]
|
|
136
|
+
return models
|
|
137
|
+
|
|
138
|
+
def show_tabular_report(self, models):
|
|
139
|
+
"""Displays all model metrics in a clean tabular format and recommends the best model."""
|
|
140
|
+
data = []
|
|
141
|
+
for name, report, matrix, accuracy, precision, recall, f1, fpr, tpr, roc_auc in models:
|
|
142
|
+
data.append({
|
|
143
|
+
'Model': name,
|
|
144
|
+
'Accuracy': accuracy,
|
|
145
|
+
'Precision': precision,
|
|
146
|
+
'Recall': recall,
|
|
147
|
+
'F1 Score': f1,
|
|
148
|
+
'ROC AUC': roc_auc
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
df = pd.DataFrame(data)
|
|
152
|
+
# Sort by Accuracy
|
|
153
|
+
df = df.sort_values(by='Accuracy', ascending=False).reset_index(drop=True)
|
|
154
|
+
|
|
155
|
+
print(f"\n{'='*60}\n 📊 MODEL COMPARISON TABLE \n{'='*60}")
|
|
156
|
+
print(df)
|
|
157
|
+
print(f"{'='*60}\n")
|
|
158
|
+
|
|
159
|
+
# Recommend Best Model
|
|
160
|
+
best_model = df.iloc[0]
|
|
161
|
+
print(f"⭐ BEST MODEL RECOMMENDATION: {best_model['Model']}")
|
|
162
|
+
print(f" Accuracy: {best_model['Accuracy']:.4f} | F1 Score: {best_model['F1 Score']:.4f}")
|
|
163
|
+
print(f"{'='*60}\n")
|
|
164
|
+
|
|
165
|
+
return df
|
|
166
|
+
|
|
167
|
+
def plot_confusion_matrices(self, models):
|
|
168
|
+
"""Plots confusion matrices for all models with different colors."""
|
|
169
|
+
num_models = len(models)
|
|
170
|
+
cols = 2
|
|
171
|
+
rows = (num_models + 1) // cols
|
|
172
|
+
|
|
173
|
+
# List of distinct colormaps to cycle through
|
|
174
|
+
colormaps = ['Blues', 'Greens', 'Oranges', 'Purples', 'Reds', 'YlOrBr', 'GnBu', 'PuBu']
|
|
175
|
+
|
|
176
|
+
fig, axes = plt.subplots(rows, cols, figsize=(15, 5 * rows))
|
|
177
|
+
fig.suptitle('Confusion Matrices', fontsize=20, fontweight='bold')
|
|
178
|
+
axes = axes.flatten()
|
|
179
|
+
|
|
180
|
+
for idx, (name, report, matrix, accuracy, precision, recall, f1, fpr, tpr, roc_auc) in enumerate(models):
|
|
181
|
+
# Select color based on index
|
|
182
|
+
cmap_choice = colormaps[idx % len(colormaps)]
|
|
183
|
+
|
|
184
|
+
sns.heatmap(matrix, annot=True, fmt='d', cmap=cmap_choice, ax=axes[idx], cbar=False)
|
|
185
|
+
axes[idx].set_title(f'{name}\nAcc: {accuracy:.2f}', fontsize=18, fontweight='bold')
|
|
186
|
+
axes[idx].set_xlabel('Predicted')
|
|
187
|
+
axes[idx].set_ylabel('True')
|
|
188
|
+
|
|
189
|
+
# Hide unused subplots
|
|
190
|
+
for i in range(idx + 1, len(axes)):
|
|
191
|
+
axes[i].axis('off')
|
|
192
|
+
|
|
193
|
+
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
|
|
194
|
+
plt.show()
|
|
195
|
+
|
|
196
|
+
def plot_roc_curves(self, models):
|
|
197
|
+
"""Plots ROC curves for all models in a single combined plot."""
|
|
198
|
+
plt.figure(figsize=(12, 8))
|
|
199
|
+
|
|
200
|
+
for name, report, matrix, accuracy, precision, recall, f1, fpr, tpr, roc_auc in models:
|
|
201
|
+
plt.plot(fpr, tpr, lw=2, label=f'{name} (AUC = {roc_auc:.2f})')
|
|
202
|
+
|
|
203
|
+
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
|
|
204
|
+
plt.xlim([0.0, 1.0])
|
|
205
|
+
plt.ylim([0.0, 1.05])
|
|
206
|
+
plt.xlabel('False Positive Rate')
|
|
207
|
+
plt.ylabel('True Positive Rate')
|
|
208
|
+
plt.title('ROC Curve Comparison', fontsize=16, fontweight='bold')
|
|
209
|
+
plt.legend(loc="lower right")
|
|
210
|
+
plt.grid(True)
|
|
211
|
+
plt.show()
|
|
212
|
+
|
|
213
|
+
def get_summary(self, models):
|
|
214
|
+
"""Legacy function to run full reporting pipeline."""
|
|
215
|
+
self.show_tabular_report(models)
|
|
216
|
+
self.plot_confusion_matrices(models)
|
|
217
|
+
self.plot_roc_curves(models)
|
|
218
|
+
self.plot_comparison(models)
|
|
219
|
+
|
|
220
|
+
def plot_comparison(self, models):
|
|
221
|
+
model_names = [m[0] for m in models]
|
|
222
|
+
accuracy = [m[3] for m in models]
|
|
223
|
+
precision = [m[4] for m in models]
|
|
224
|
+
recall = [m[5] for m in models]
|
|
225
|
+
f1 = [m[6] for m in models]
|
|
226
|
+
|
|
227
|
+
data = {
|
|
228
|
+
'Model': model_names * 4,
|
|
229
|
+
'Score': accuracy + precision + recall + f1,
|
|
230
|
+
'Metric': ['Accuracy']*len(models) + ['Precision']*len(models) + ['Recall']*len(models) + ['F1 Score']*len(models)
|
|
231
|
+
}
|
|
232
|
+
df_plot = pd.DataFrame(data)
|
|
233
|
+
|
|
234
|
+
plt.figure(figsize=(14, 8))
|
|
235
|
+
ax = sns.barplot(x='Model', y='Score', hue='Metric', data=df_plot, palette="viridis")
|
|
236
|
+
plt.title("Comprehensive Model Comparison", fontsize=18, pad=20)
|
|
237
|
+
plt.ylim(0, 1.1)
|
|
238
|
+
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
|
|
239
|
+
plt.xticks(rotation=45, ha='right')
|
|
240
|
+
for container in ax.containers:
|
|
241
|
+
ax.bar_label(container, fmt='%.2f', padding=3, fontsize=9)
|
|
242
|
+
plt.tight_layout()
|
|
243
|
+
plt.show()
|
|
244
|
+
|
|
245
|
+
class MultiModelRegressior:
|
|
246
|
+
def __init__(self, X, y, test_size=0.3, scaled_data=False):
|
|
247
|
+
self.X = X
|
|
248
|
+
self.y = y
|
|
249
|
+
X_train, X_test, y_train, y_test = train_test_split(self.X, self.y, test_size=test_size, random_state=42)
|
|
250
|
+
|
|
251
|
+
self.scaler = StandardScaler()
|
|
252
|
+
if scaled_data:
|
|
253
|
+
self.X_train_scaled = self.scaler.fit_transform(X_train)
|
|
254
|
+
self.X_test_scaled = self.scaler.transform(X_test)
|
|
255
|
+
else:
|
|
256
|
+
self.X_train_scaled = X_train
|
|
257
|
+
self.X_test_scaled = X_test
|
|
258
|
+
|
|
259
|
+
self.y_train = y_train
|
|
260
|
+
self.y_test = y_test
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def evaluate_model(model, X_test, y_true):
|
|
264
|
+
y_pred = model.predict(X_test)
|
|
265
|
+
mae = mean_absolute_error(y_true, y_pred)
|
|
266
|
+
mse = mean_squared_error(y_true, y_pred)
|
|
267
|
+
rmse = np.sqrt(mse)
|
|
268
|
+
r2 = r2_score(y_true, y_pred)
|
|
269
|
+
return mae, mse, rmse, r2, y_pred
|
|
270
|
+
|
|
271
|
+
def LinearRegression_model(self): return self.evaluate_model(LinearRegression().fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
272
|
+
def Lasso_model(self): return self.evaluate_model(Lasso(alpha=0.1).fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
273
|
+
def Ridge_model(self): return self.evaluate_model(Ridge(alpha=1.0).fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
274
|
+
def SVR_model(self): return self.evaluate_model(SVR(kernel='rbf').fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
275
|
+
def DecisionTree_model(self): return self.evaluate_model(DecisionTreeRegressor(random_state=42).fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
276
|
+
def RandomForest_model(self): return self.evaluate_model(RandomForestRegressor(n_estimators=100, random_state=42).fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
277
|
+
def GradientBoosting_model(self): return self.evaluate_model(GradientBoostingRegressor(n_estimators=100, random_state=42).fit(self.X_train_scaled, self.y_train), self.X_test_scaled, self.y_test)
|
|
278
|
+
|
|
279
|
+
def run_all_models(self):
|
|
280
|
+
return [
|
|
281
|
+
('Linear Regression', *self.LinearRegression_model()),
|
|
282
|
+
('Lasso Regression', *self.Lasso_model()),
|
|
283
|
+
('Ridge Regression', *self.Ridge_model()),
|
|
284
|
+
('SVR', *self.SVR_model()),
|
|
285
|
+
('Decision Tree Regressor', *self.DecisionTree_model()),
|
|
286
|
+
('Random Forest Regressor', *self.RandomForest_model()),
|
|
287
|
+
('Gradient Boosting Regressor', *self.GradientBoosting_model())
|
|
288
|
+
]
|
|
289
|
+
|
|
290
|
+
def show_tabular_report(self, models):
|
|
291
|
+
"""Displays all regression metrics in a clean tabular format and recommends the best model."""
|
|
292
|
+
data = []
|
|
293
|
+
for name, mae, mse, rmse, r2, y_pred in models:
|
|
294
|
+
data.append({
|
|
295
|
+
'Model': name,
|
|
296
|
+
'MAE': mae,
|
|
297
|
+
'MSE': mse,
|
|
298
|
+
'RMSE': rmse,
|
|
299
|
+
'R2 Score': r2
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
df = pd.DataFrame(data)
|
|
303
|
+
df = df.sort_values(by='R2 Score', ascending=False).reset_index(drop=True)
|
|
304
|
+
|
|
305
|
+
print(f"\n{'='*60}\n 📊 REGRESSION MODEL COMPARISON TABLE \n{'='*60}")
|
|
306
|
+
print(df)
|
|
307
|
+
print(f"{'='*60}\n")
|
|
308
|
+
|
|
309
|
+
# Recommend Best Model
|
|
310
|
+
best_model = df.iloc[0]
|
|
311
|
+
print(f"⭐ BEST MODEL RECOMMENDATION: {best_model['Model']}")
|
|
312
|
+
print(f" R2 Score: {best_model['R2 Score']:.4f} | RMSE: {best_model['RMSE']:.4f}")
|
|
313
|
+
print(f"{'='*60}\n")
|
|
314
|
+
|
|
315
|
+
return df
|
|
316
|
+
|
|
317
|
+
def plot_true_vs_predicted(self, models):
|
|
318
|
+
"""Plots True vs Predicted values for all models (Regression equivalent of Confusion Matrix)."""
|
|
319
|
+
num_models = len(models)
|
|
320
|
+
cols = 2
|
|
321
|
+
rows = (num_models + 1) // cols
|
|
322
|
+
|
|
323
|
+
# Colors to cycle through
|
|
324
|
+
colors = ['blue', 'green', 'orange', 'purple', 'red', 'cyan', 'magenta']
|
|
325
|
+
|
|
326
|
+
fig, axes = plt.subplots(rows, cols, figsize=(15, 5 * rows))
|
|
327
|
+
fig.suptitle('True vs Predicted Values', fontsize=20, fontweight='bold')
|
|
328
|
+
axes = axes.flatten()
|
|
329
|
+
|
|
330
|
+
for idx, (name, mae, mse, rmse, r2, y_pred) in enumerate(models):
|
|
331
|
+
color = colors[idx % len(colors)]
|
|
332
|
+
|
|
333
|
+
axes[idx].scatter(self.y_test, y_pred, alpha=0.6, color=color, label=name)
|
|
334
|
+
|
|
335
|
+
# Diagonal line for perfect prediction
|
|
336
|
+
p1 = max(max(y_pred), max(self.y_test))
|
|
337
|
+
p2 = min(min(y_pred), min(self.y_test))
|
|
338
|
+
axes[idx].plot([p1, p2], [p1, p2], 'k--', lw=2)
|
|
339
|
+
|
|
340
|
+
axes[idx].set_title(f'{name}\nR2: {r2:.2f} | RMSE: {rmse:.2f}', fontsize=14)
|
|
341
|
+
axes[idx].set_xlabel('True Values')
|
|
342
|
+
axes[idx].set_ylabel('Predicted Values')
|
|
343
|
+
axes[idx].legend()
|
|
344
|
+
|
|
345
|
+
# Hide unused subplots
|
|
346
|
+
for i in range(idx + 1, len(axes)):
|
|
347
|
+
axes[i].axis('off')
|
|
348
|
+
|
|
349
|
+
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
|
|
350
|
+
plt.show()
|
|
351
|
+
|
|
352
|
+
def get_summary(self, models):
|
|
353
|
+
self.show_tabular_report(models)
|
|
354
|
+
self.plot_true_vs_predicted(models)
|
|
355
|
+
self.plot_comparison(models)
|
|
356
|
+
|
|
357
|
+
def plot_comparison(self, models):
|
|
358
|
+
model_names = [m[0] for m in models]
|
|
359
|
+
r2_scores = [m[4] for m in models]
|
|
360
|
+
plt.figure(figsize=(10, 6))
|
|
361
|
+
sns.barplot(x=model_names, y=r2_scores, palette='viridis')
|
|
362
|
+
plt.title("Regressor R2 Score Comparison")
|
|
363
|
+
plt.ylabel("R2 Score")
|
|
364
|
+
plt.xticks(rotation=45)
|
|
365
|
+
plt.tight_layout()
|
|
366
|
+
plt.show()
|
|
367
|
+
|
|
368
|
+
# =============================================================================
|
|
369
|
+
# SMART MAIN BLOCK: AUTOMATIC DETECTION
|
|
370
|
+
# =============================================================================
|
|
371
|
+
if __name__ == '__main__':
|
|
372
|
+
print("Initializing Multi-Model Analysis...")
|
|
373
|
+
|
|
374
|
+
# NOTE: This block expects 'X' and 'y' to be defined in the namespace
|
|
375
|
+
if 'X' in locals() and 'y' in locals():
|
|
376
|
+
print(f"Data Loaded. X Shape: {X.shape}, y Shape: {y.shape}")
|
|
377
|
+
|
|
378
|
+
target_type = type_of_target(y)
|
|
379
|
+
unique_values = len(np.unique(y))
|
|
380
|
+
|
|
381
|
+
if 'continuous' in target_type or (unique_values > 20 and target_type != 'multiclass'):
|
|
382
|
+
print(f"\n[INFO] Detected REGRESSION problem (Target type: {target_type})")
|
|
383
|
+
print("Running MultiModelRegressior...")
|
|
384
|
+
|
|
385
|
+
regressor = MultiModelRegressior(X, y, scaled_data=True)
|
|
386
|
+
results = regressor.run_all_models()
|
|
387
|
+
|
|
388
|
+
# New modular functions for Regression
|
|
389
|
+
regressor.show_tabular_report(results)
|
|
390
|
+
regressor.plot_true_vs_predicted(results)
|
|
391
|
+
regressor.plot_comparison(results)
|
|
392
|
+
|
|
393
|
+
else:
|
|
394
|
+
print(f"\n[INFO] Detected CLASSIFICATION problem (Target type: {target_type})")
|
|
395
|
+
print("Running MultiModelClassifier...")
|
|
396
|
+
|
|
397
|
+
classifier = MultiModelClassifier(X, y, scaled_data=True)
|
|
398
|
+
results = classifier.run_all_models()
|
|
399
|
+
|
|
400
|
+
# Run all visualizations and reports
|
|
401
|
+
classifier.show_tabular_report(results)
|
|
402
|
+
classifier.plot_confusion_matrices(results)
|
|
403
|
+
classifier.plot_roc_curves(results)
|
|
404
|
+
classifier.plot_comparison(results)
|
|
405
|
+
|
|
406
|
+
else:
|
|
407
|
+
print("Error: X and y are not defined. Please define them.")
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: multimodel_analysis
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: A Python Package for Automatic Multi-Model Analysis (Classification & Regression)
|
|
5
|
+
Author: Uditya Narayan Tiwari
|
|
6
|
+
Author-email: tiwarimerit@gmail.com
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: pandas
|
|
17
|
+
Requires-Dist: matplotlib
|
|
18
|
+
Requires-Dist: seaborn
|
|
19
|
+
Requires-Dist: scikit-learn
|
|
20
|
+
Dynamic: author
|
|
21
|
+
Dynamic: author-email
|
|
22
|
+
Dynamic: classifier
|
|
23
|
+
Dynamic: description
|
|
24
|
+
Dynamic: description-content-type
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
Dynamic: requires-dist
|
|
27
|
+
Dynamic: requires-python
|
|
28
|
+
Dynamic: summary
|
|
29
|
+
|
|
30
|
+
# Multi-Model Analysis
|
|
31
|
+
|
|
32
|
+
[](https://pypi.org/project/multimodel_analysis/)
|
|
33
|
+
[](https://opensource.org/licenses/MIT)
|
|
34
|
+
|
|
35
|
+
**multimodel_analysis** is a comprehensive machine learning library created by **Uditya Narayan Tiwari**. It automates the process of training, evaluating, and visualizing multiple models for both Classification and Regression tasks.
|
|
36
|
+
|
|
37
|
+
Designed for data scientists and researchers, it streamlines model selection by providing automatic feature scaling, detailed performance metrics, and professional-grade visualizations in just a few lines of code.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 📦 Installation
|
|
42
|
+
|
|
43
|
+
### Install via PyPI
|
|
44
|
+
The easiest way to install the package is via pip:
|
|
45
|
+
```bash
|
|
46
|
+
pip install multimodel_analysis
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Install from GitHub
|
|
51
|
+
|
|
52
|
+
To get the latest development version:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install git+[https://github.com/udityamerit/multimodel_analysis.git](https://github.com/udityamerit/Multimodel-Analysis-Pacakge.git) --upgrade --force-reinstall
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 📋 Requirements
|
|
60
|
+
|
|
61
|
+
* `numpy`
|
|
62
|
+
* `pandas`
|
|
63
|
+
* `matplotlib`
|
|
64
|
+
* `seaborn`
|
|
65
|
+
* `scikit-learn`
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## How to Use
|
|
70
|
+
|
|
71
|
+
### 1. Classification Analysis
|
|
72
|
+
|
|
73
|
+
Use `MultiModelClassifier` for categorical target variables. It automatically compares models like Logistic Regression, SVM, Decision Trees, Random Forest, Gradient Boosting, and more.
|
|
74
|
+
|
|
75
|
+
#### Step 1: Initialize and Train
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import pandas as pd
|
|
79
|
+
from multimodel_analysis import MultiModelClassifier
|
|
80
|
+
|
|
81
|
+
# Load your dataset
|
|
82
|
+
df = pd.read_csv('your_classification_data.csv')
|
|
83
|
+
X = df.drop('target_column', axis=1)
|
|
84
|
+
y = df['target_column']
|
|
85
|
+
|
|
86
|
+
# Initialize the classifier
|
|
87
|
+
# scaled_data=True applies StandardScaler automatically
|
|
88
|
+
classifier = MultiModelClassifier(X, y, test_size=0.3, scaled_data=True)
|
|
89
|
+
|
|
90
|
+
# Train all models and get results
|
|
91
|
+
results = classifier.run_all_models()
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
#### Step 2: View Metrics & Best Model
|
|
96
|
+
|
|
97
|
+
Generates a clean dataframe of metrics (Accuracy, Precision, Recall, F1, AUC) and prints the best recommendation.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
classifier.show_tabular_report(results)
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### Step 3: Visualize Confusion Matrices
|
|
105
|
+
|
|
106
|
+
Plots confusion matrices for every trained model with distinct color palettes.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
classifier.plot_confusion_matrices(results)
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
#### Step 4: Plot ROC Curves
|
|
114
|
+
|
|
115
|
+
Overlays ROC curves for all models to compare Area Under the Curve (AUC) performance.
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
classifier.plot_roc_curves(results)
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
#### Step 5: Compare All Metrics
|
|
123
|
+
|
|
124
|
+
Plots a grouped bar chart comparing Accuracy, Precision, Recall, and F1 Score.
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
classifier.plot_comparison(results)
|
|
128
|
+
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
### 2. Regression Analysis
|
|
134
|
+
|
|
135
|
+
Use `MultiModelRegressior` for continuous target variables. It compares Linear Regression, Lasso, Ridge, SVR, Random Forest, Gradient Boosting, etc.
|
|
136
|
+
|
|
137
|
+
#### Step 1: Initialize and Train
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from multimodel_analysis import MultiModelRegressior
|
|
141
|
+
|
|
142
|
+
# Load your dataset
|
|
143
|
+
df = pd.read_csv('your_regression_data.csv')
|
|
144
|
+
X = df.drop('price', axis=1)
|
|
145
|
+
y = df['price']
|
|
146
|
+
|
|
147
|
+
# Initialize the regressor
|
|
148
|
+
regressor = MultiModelRegressior(X, y, test_size=0.3, scaled_data=True)
|
|
149
|
+
|
|
150
|
+
# Train all models
|
|
151
|
+
results = regressor.run_all_models()
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
#### Step 2: View Metrics & Best Model
|
|
156
|
+
|
|
157
|
+
Generates a table of MAE, MSE, RMSE, and R2 Scores, and recommends the best model based on R2.
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
regressor.show_tabular_report(results)
|
|
161
|
+
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
#### Step 3: True vs. Predicted Plots
|
|
165
|
+
|
|
166
|
+
Visualizes the relationship between actual and predicted values with an ideal fit line.
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
regressor.plot_true_vs_predicted(results)
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
#### Step 4: Compare R2 Scores
|
|
174
|
+
|
|
175
|
+
Plots a bar chart to easily identify the model with the highest R2 score.
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
regressor.plot_comparison(results)
|
|
179
|
+
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Key Features
|
|
185
|
+
|
|
186
|
+
### 🔹 Intelligent Automation
|
|
187
|
+
|
|
188
|
+
* **Automatic Scaling**: Simply set `scaled_data=True` to standardize your features using `StandardScaler` before training.
|
|
189
|
+
* **Best Model Detection**: Automatically highlights the best performing model based on Accuracy (Classification) or R2 Score (Regression).
|
|
190
|
+
|
|
191
|
+
### 🔹 Professional Visualizations
|
|
192
|
+
|
|
193
|
+
* **Colorful Confusion Matrices**: Automatically cycles through color maps (Blues, Greens, Oranges, etc.) for distinct model visualization.
|
|
194
|
+
* **ROC Curve Overlays**: clean comparison of True Positive vs False Positive rates.
|
|
195
|
+
* **Regression Fit Plots**: Scatter plots with diagonal reference lines to visually assess regression performance.
|
|
196
|
+
|
|
197
|
+
### 🔹 Extensive Model Library
|
|
198
|
+
|
|
199
|
+
* **Classifiers**: Logistic Regression, SVM, Decision Tree, KNN, Naive Bayes, Random Forest, Gradient Boosting, AdaBoost.
|
|
200
|
+
* **Regressors**: Linear Regression, Lasso, Ridge, SVR, Decision Tree, Random Forest, Gradient Boosting.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## 👨💻 Author
|
|
205
|
+
|
|
206
|
+
**Uditya Narayan Tiwari**
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
## 📄 License
|
|
210
|
+
|
|
211
|
+
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
requirements.txt
|
|
5
|
+
setup.py
|
|
6
|
+
multimodel_analysis/__init__.py
|
|
7
|
+
multimodel_analysis/multimodel.py
|
|
8
|
+
multimodel_analysis.egg-info/PKG-INFO
|
|
9
|
+
multimodel_analysis.egg-info/SOURCES.txt
|
|
10
|
+
multimodel_analysis.egg-info/dependency_links.txt
|
|
11
|
+
multimodel_analysis.egg-info/requires.txt
|
|
12
|
+
multimodel_analysis.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
multimodel_analysis
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import setuptools
|
|
2
|
+
|
|
3
|
+
with open('README.md', 'r', encoding='utf-8') as fp:
|
|
4
|
+
long_description = fp.read()
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
with open('requirements.txt') as fp:
|
|
8
|
+
requirements = fp.read().splitlines()
|
|
9
|
+
|
|
10
|
+
setuptools.setup(
|
|
11
|
+
name='multimodel_analysis', # Package name
|
|
12
|
+
version='0.0.1', # Initial version
|
|
13
|
+
author='Uditya Narayan Tiwari',
|
|
14
|
+
author_email='tiwarimerit@gmail.com',
|
|
15
|
+
description='A Python Package for Automatic Multi-Model Analysis (Classification & Regression)',
|
|
16
|
+
long_description=long_description,
|
|
17
|
+
long_description_content_type='text/markdown',
|
|
18
|
+
# url='https://github.com/udityamerit/multimodel_analysis', # Update with your actual repo URL
|
|
19
|
+
packages=setuptools.find_packages(),
|
|
20
|
+
classifiers=[
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"License :: OSI Approved :: Apache Software License",
|
|
23
|
+
"Operating System :: OS Independent",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Intended Audience :: Science/Research",
|
|
26
|
+
],
|
|
27
|
+
install_requires=requirements,
|
|
28
|
+
python_requires='>=3.8',
|
|
29
|
+
include_package_data=True,
|
|
30
|
+
)
|