-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_project.py
More file actions
721 lines (567 loc) ยท 17 KB
/
create_project.py
File metadata and controls
721 lines (567 loc) ยท 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
"""
ML Project Generator
Creates standardized project structure for production-ready ML projects.
Usage: python create_project.py <project-name>
"""
import os
import sys
from pathlib import Path
def create_project_structure(project_name: str, base_path: str = "projects"):
"""
Creates a standardized ML project structure.
Args:
project_name: Name of the project (will be slugified)
base_path: Base directory where projects are stored
"""
# Sanitize project name
project_slug = project_name.lower().replace(" ", "-")
project_path = Path(base_path) / project_slug
if project_path.exists():
print(f"โ Project '{project_slug}' already exists!")
return
# Define structure
structure = {
"data": ["raw", "processed"],
"notebooks": [],
"src": [],
"models": [],
"outputs": ["figures", "reports"],
}
print(f"๐ Creating project: {project_slug}")
# Create directories
for folder, subfolders in structure.items():
folder_path = project_path / folder
folder_path.mkdir(parents=True, exist_ok=True)
print(f" โ Created {folder}/")
for subfolder in subfolders:
subfolder_path = folder_path / subfolder
subfolder_path.mkdir(parents=True, exist_ok=True)
print(f" โ Created {folder}/{subfolder}/")
# Create .gitignore
gitignore_content = """# Data
data/raw/*
data/processed/*
!data/raw/.gitkeep
!data/processed/.gitkeep
# Models
models/*.pkl
models/*.h5
models/*.pt
models/*.joblib
!models/.gitkeep
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
.venv/
.env
# Jupyter
.ipynb_checkpoints/
*.ipynb_checkpoints
# IDEs
.vscode/
.idea/
# ML Artifacts
mlruns/
wandb/
.neptune/
# OS
.DS_Store
Thumbs.db
"""
(project_path / ".gitignore").write_text(gitignore_content)
print(f" โ Created .gitignore")
# Create .gitkeep files
(project_path / "data" / "raw" / ".gitkeep").touch()
(project_path / "data" / "processed" / ".gitkeep").touch()
(project_path / "models" / ".gitkeep").touch()
# Create requirements.txt
requirements_content = """# Core Data Science
pandas>=2.0.0
numpy>=1.24.0
scikit-learn>=1.3.0
# Visualization (Plotly First!)
plotly>=5.17.0
kaleido>=0.2.1 # For static image export
# Model Explainability
shap>=0.42.0
# Deployment
streamlit>=1.28.0
# Experiment Tracking (Optional - uncomment if needed)
# mlflow>=2.8.0
# wandb>=0.15.0
# Deep Learning (Optional - uncomment if needed)
# torch>=2.0.0
# tensorflow>=2.13.0
# Utilities
python-dotenv>=1.0.0
joblib>=1.3.0
"""
(project_path / "requirements.txt").write_text(requirements_content)
print(f" โ Created requirements.txt")
# Create starter notebook
notebook_content = """# %% [markdown]
# # {PROJECT_NAME} - Exploratory Data Analysis
#
# **Objective:** [Describe what you're trying to solve]
#
# **Dataset:** [Describe the dataset]
#
# ---
# %% [markdown]
# ## 1. Import Libraries
# %%
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from pathlib import Path
# Set Plotly as default renderer
import plotly.io as pio
pio.renderers.default = "browser"
# %%
# Path configuration
DATA_RAW = Path("../data/raw")
DATA_PROCESSED = Path("../data/processed")
OUTPUTS = Path("../outputs/figures")
# %% [markdown]
# ## 2. Load Data
# %%
# df = pd.read_csv(DATA_RAW / "your_dataset.csv")
# df.head()
# %% [markdown]
# ## 3. Initial Exploration
#
# Key questions:
# - What's the shape of the data?
# - Any missing values?
# - What are the data types?
# - Class balance (for classification)?
# %%
# Data shape and info
# print(f"Shape: {df.shape}")
# df.info()
# %%
# Missing values check
# missing = df.isnull().sum()
# missing[missing > 0]
# %% [markdown]
# ## 4. Visualization & Insights
#
# **Remember:** Every plot should tell a story!
# %%
# Example: Distribution of target variable
# fig = px.histogram(
# df,
# x="target_column",
# title="Distribution of Target Variable",
# color="target_column",
# labels={"target_column": "Target"}
# )
# fig.show()
# %% [markdown]
# ## 5. Key Insights
#
# **Findings:**
# 1. [Insight 1]
# 2. [Insight 2]
# 3. [Insight 3]
#
# **Next Steps:**
# - [ ] Feature engineering ideas
# - [ ] Models to try
# - [ ] Evaluation metrics to track
""".replace("{PROJECT_NAME}", project_name.title())
(project_path / "notebooks" / "01_eda.ipynb").write_text(
convert_percent_to_ipynb(notebook_content)
)
print(f" โ Created notebooks/01_eda.ipynb")
# Create src templates
preprocessing_content = '''"""
Data preprocessing utilities.
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from typing import Tuple
def load_and_split(
filepath: str,
target_col: str,
test_size: float = 0.2,
random_state: int = 42
) -> Tuple[pd.DataFrame, pd.DataFrame, pd.Series, pd.Series]:
"""
Load data and split into train/test sets.
Args:
filepath: Path to the CSV file
target_col: Name of the target column
test_size: Proportion of test set
random_state: Random seed for reproducibility
Returns:
X_train, X_test, y_train, y_test
"""
df = pd.read_csv(filepath)
X = df.drop(columns=[target_col])
y = df[target_col]
return train_test_split(X, y, test_size=test_size, random_state=random_state)
def handle_missing_values(df: pd.DataFrame, strategy: str = "mean") -> pd.DataFrame:
"""
Handle missing values in the dataset.
Args:
df: Input dataframe
strategy: Strategy for imputation ('mean', 'median', 'mode', 'drop')
Returns:
DataFrame with handled missing values
"""
if strategy == "drop":
return df.dropna()
elif strategy == "mean":
return df.fillna(df.mean(numeric_only=True))
elif strategy == "median":
return df.fillna(df.median(numeric_only=True))
elif strategy == "mode":
return df.fillna(df.mode().iloc[0])
else:
raise ValueError(f"Unknown strategy: {strategy}")
'''
(project_path / "src" / "preprocessing.py").write_text(preprocessing_content, encoding='utf-8')
print(f" โ Created src/preprocessing.py")
train_content = '''"""
Model training utilities.
"""
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix
import joblib
from pathlib import Path
def create_baseline_pipeline(estimator):
"""
Create a baseline sklearn pipeline.
Args:
estimator: Sklearn estimator (e.g., LogisticRegression())
Returns:
Configured pipeline
"""
return Pipeline([
('scaler', StandardScaler()),
('model', estimator)
])
def train_and_evaluate(pipeline, X_train, y_train, X_test, y_test):
"""
Train pipeline and print evaluation metrics.
Args:
pipeline: Sklearn pipeline
X_train, y_train: Training data
X_test, y_test: Test data
Returns:
Trained pipeline
"""
print("๐ Training model...")
pipeline.fit(X_train, y_train)
print("โ
Training complete!")
# Evaluate
train_score = pipeline.score(X_train, y_train)
test_score = pipeline.score(X_test, y_test)
print(f"\\nTrain Accuracy: {train_score:.4f}")
print(f"Test Accuracy: {test_score:.4f}")
# Predictions
y_pred = pipeline.predict(X_test)
print("\\n" + "="*50)
print("CLASSIFICATION REPORT")
print("="*50)
print(classification_report(y_test, y_pred))
return pipeline
def save_model(pipeline, filepath: str = "models/model.pkl"):
"""
Save trained model to disk.
Args:
pipeline: Trained pipeline
filepath: Output path
"""
Path(filepath).parent.mkdir(parents=True, exist_ok=True)
joblib.dump(pipeline, filepath)
print(f"๐พ Model saved to {filepath}")
'''
(project_path / "src" / "train.py").write_text(train_content, encoding='utf-8')
print(f" โ Created src/train.py")
visualization_content = '''"""
Visualization utilities using Plotly.
"""
import plotly.express as px
import plotly.graph_objects as go
from sklearn.metrics import confusion_matrix
import pandas as pd
def plot_confusion_matrix(y_true, y_pred, labels=None):
"""
Create an interactive confusion matrix using Plotly.
Args:
y_true: True labels
y_pred: Predicted labels
labels: Class labels (optional)
Returns:
Plotly figure
"""
cm = confusion_matrix(y_true, y_pred)
if labels is None:
labels = [f"Class {i}" for i in range(len(cm))]
fig = go.Figure(data=go.Heatmap(
z=cm,
x=labels,
y=labels,
colorscale='Blues',
text=cm,
texttemplate='%{text}',
textfont={"size": 16},
hovertemplate='Predicted: %{x}<br>Actual: %{y}<br>Count: %{z}<extra></extra>'
))
fig.update_layout(
title='Confusion Matrix',
xaxis_title='Predicted Label',
yaxis_title='True Label',
width=600,
height=600
)
return fig
def plot_feature_importance(model, feature_names, top_n=10):
"""
Plot feature importance from a trained model.
Args:
model: Trained sklearn model with feature_importances_
feature_names: List of feature names
top_n: Number of top features to display
Returns:
Plotly figure
"""
if not hasattr(model, 'feature_importances_'):
raise ValueError("Model doesn't have feature_importances_ attribute")
importance_df = pd.DataFrame({
'Feature': feature_names,
'Importance': model.feature_importances_
}).sort_values('Importance', ascending=False).head(top_n)
fig = px.bar(
importance_df,
x='Importance',
y='Feature',
orientation='h',
title=f'Top {top_n} Most Important Features',
labels={'Importance': 'Feature Importance', 'Feature': ''},
color='Importance',
color_continuous_scale='Viridis'
)
fig.update_layout(yaxis={'categoryorder': 'total ascending'})
return fig
'''
(project_path / "src" / "visualization.py").write_text(visualization_content, encoding='utf-8')
print(f" โ Created src/visualization.py")
# Create Streamlit app template
app_content = '''"""
Streamlit Deployment App
"""
import streamlit as st
import pandas as pd
import joblib
from pathlib import Path
# Page config
st.set_page_config(
page_title="{PROJECT_NAME}",
page_icon="๐ค",
layout="wide"
)
# Title
st.title("๐ค {PROJECT_NAME}")
st.markdown("---")
# Sidebar
st.sidebar.header("Configuration")
# Load model (cached)
@st.cache_resource
def load_model():
model_path = Path("models/model.pkl")
if model_path.exists():
return joblib.load(model_path)
else:
return None
model = load_model()
if model is None:
st.error("โ Model not found! Train a model first.")
st.stop()
# Main content
st.header("Make Predictions")
# TODO: Add input fields based on your features
# Example:
# col1, col2 = st.columns(2)
# with col1:
# feature1 = st.number_input("Feature 1", value=0.0)
# with col2:
# feature2 = st.number_input("Feature 2", value=0.0)
# if st.button("Predict", type="primary"):
# # Create input dataframe
# input_data = pd.DataFrame({
# 'feature1': [feature1],
# 'feature2': [feature2]
# })
#
# # Make prediction
# prediction = model.predict(input_data)[0]
# proba = model.predict_proba(input_data)[0]
#
# # Display results
# st.success(f"Prediction: {prediction}")
# st.write(f"Confidence: {max(proba):.2%}")
# Footer
st.markdown("---")
st.markdown("Built with โค๏ธ by Vihaan Kulkarni")
'''.replace("{PROJECT_NAME}", project_name.title())
(project_path / "app.py").write_text(app_content, encoding='utf-8')
print(f" โ Created app.py")
# Create README template
readme_content = f"""# {project_name.title()}
> **Status:** ๐ง In Progress | โ
Complete
## ๐ฏ Problem Statement
[Describe the problem you're solving. Why does this matter?]
## ๐ Dataset
- **Source:** [Link or description]
- **Size:** [Rows x Columns]
- **Target Variable:** [What are you predicting?]
## ๐ Key Insights
### Insight 1: [Title]
[Screenshot of Plotly visualization]
**Finding:** [Describe what the data reveals]
### Insight 2: [Title]
[Screenshot of Plotly visualization]
**Finding:** [Describe what the data reveals]
## ๐ค Modeling Approach
### Baseline Model
- **Algorithm:** [e.g., Logistic Regression]
- **Accuracy:** XX%
### Final Model
- **Algorithm:** [e.g., Random Forest]
- **Accuracy:** XX%
- **Key Metrics:**
- Precision: XX%
- Recall: XX%
- F1-Score: XX%
### Model Explainability
[SHAP summary plot or feature importance chart]
**Interpretation:** [Which features drove predictions?]
## ๐ Deployment
Live app: [Streamlit link if deployed]
Run locally:
```bash
streamlit run app.py
```
## ๐ ๏ธ Tech Stack
- **Data:** Pandas, NumPy
- **Visualization:** Plotly
- **Modeling:** Scikit-Learn
- **Explainability:** SHAP
- **Deployment:** Streamlit
## ๐ Project Structure
```
{project_slug}/
โโโ data/ # Raw and processed data
โโโ notebooks/ # EDA and experiments
โโโ src/ # Production code
โโโ models/ # Saved models
โโโ outputs/ # Figures and reports
โโโ app.py # Streamlit app
โโโ requirements.txt
```
## ๐งช Reproducibility
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run notebooks in order:
- `01_eda.ipynb` - Exploratory Data Analysis
- `02_modeling.ipynb` - Model Training
## ๐ก Lessons Learned
- [Lesson 1]
- [Lesson 2]
- [Lesson 3]
## ๐ฎ Future Improvements
- [ ] [Improvement 1]
- [ ] [Improvement 2]
- [ ] [Improvement 3]
---
**Author:** Vihaan Kulkarni
**Date:** {get_current_date()}
"""
(project_path / "README.md").write_text(readme_content, encoding='utf-8')
print(f" โ Created README.md")
# Success message
print(f"\nโจ Project '{project_slug}' created successfully!")
print(f"\n๐ Location: {project_path.absolute()}")
print(f"\n๐ Next steps:")
print(f" 1. cd {project_path}")
print(f" 2. python -m venv .venv")
print(f" 3. .venv\\Scripts\\activate (Windows)")
print(f" 4. pip install -r requirements.txt")
print(f" 5. jupyter notebook notebooks/01_eda.ipynb")
def convert_percent_to_ipynb(content: str) -> str:
"""Convert percent format to Jupyter notebook JSON."""
import json
cells = []
current_cell = {"lines": [], "type": "code"}
for line in content.split("\n"):
if line.startswith("# %% [markdown]"):
if current_cell["lines"]:
cells.append(current_cell)
current_cell = {"lines": [], "type": "markdown"}
elif line.startswith("# %%"):
if current_cell["lines"]:
cells.append(current_cell)
current_cell = {"lines": [], "type": "code"}
else:
if current_cell["type"] == "markdown" and line.startswith("# "):
current_cell["lines"].append(line[2:])
else:
current_cell["lines"].append(line)
if current_cell["lines"]:
cells.append(current_cell)
notebook_cells = []
for cell in cells:
source = [line + "\n" for line in cell["lines"]]
if source and not source[-1].endswith("\n"):
source[-1] += "\n"
notebook_cells.append({
"cell_type": cell["type"],
"metadata": {},
"source": source,
"outputs": [] if cell["type"] == "code" else None,
"execution_count": None if cell["type"] == "code" else None
})
if notebook_cells[-1]["outputs"] is None:
del notebook_cells[-1]["outputs"]
if notebook_cells[-1]["execution_count"] is None:
del notebook_cells[-1]["execution_count"]
notebook = {
"cells": notebook_cells,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
return json.dumps(notebook, indent=2)
def get_current_date():
"""Get current date in YYYY-MM-DD format."""
from datetime import datetime
return datetime.now().strftime("%Y-%m-%d")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python create_project.py <project-name>")
sys.exit(1)
project_name = " ".join(sys.argv[1:])
create_project_structure(project_name)