What is Scikit-learn?
Scikit-learn (sklearn) is one of the most popular Python libraries for Machine Learning. It provides easy-to-use implementations of various ML algorithms for:- Classification
- Regression
- Clustering
- Dimensionality Reduction
- Model Selection
- Data Preprocessing
- Evaluation
Installation
Scikit-learn Workflow
Almost every ML model in sklearn follows the same workflow.Built-in Datasets
Scikit-learn provides several datasets for learning and experimentation.Common Datasets
Example: Iris Dataset
Example: California Housing Dataset
Train-Test Split
Machine Learning models should never be evaluated using the same data they were trained on. Instead:- Training Data → Learn patterns
- Testing Data → Evaluate performance
Syntax
Parameters
Example
Model Workflow
All sklearn models have the same interface.fit()
Used to train the model.predict()
Predicts outputs for unseen data.predict_proba()
Returns prediction probabilities.- Confidence scores
- ROC Curve
- Threshold tuning
score()
Returns the default evaluation metric. ClassificationComplete Example
Data Preprocessing
Preprocessing improves model performance. Common preprocessing includes:- Scaling
- Encoding
- Missing values
- Feature engineering
StandardScaler
Standardizes features. Formula- Mean = 0
- Standard Deviation = 1
- Logistic Regression
- SVM
- KNN
- Neural Networks
Example
MinMaxScaler
Scales values between 0 and 1. Formula- Neural Networks
- Distance-based algorithms
StandardScaler vs MinMaxScaler
LabelEncoder
Encodes target labels. ExampleNote: UseLabelEncodermainly for the target (y), not feature columns.
OneHotEncoder
Converts categorical features into binary columns. ExampleModel Persistence with joblib
Instead of training every time, save the trained model. InstallSave Model
Load Model
Complete Example
Important Missing Topics
Pipelines (Highly Recommended)
Instead of manually scaling and training:- Prevents data leakage
- Cleaner code
- Easy deployment
Model Evaluation
Accuracy
Confusion Matrix
Classification Report
- Precision
- Recall
- F1 Score
- Accuracy
Regression Metrics
Cross Validation
Instead of a single train-test split:- More reliable evaluation
- Less variance
- Better performance estimate
Random State
- Every run gives a different split.
Common Mistakes
❌ Scaling before splitting data❌ Fitting scaler on test data
❌ Training and testing on the same dataset