What is Machine Learning?
Machine Learning is a subset of Artificial Intelligence that enables computers to learn from data and make decisions without being explicitly programmed. Instead of writing rules, we feed data to algorithms that find patterns automatically.
Key Concept
Traditional programming: Rules + Data → Output
Machine Learning: Data + Output → Rules (Model)
Real-World Applications
Email Spam Detection
Classify emails as spam or not spam based on content patterns.
Product Recommendations
Netflix, Amazon suggest items based on your behavior.
Self-Driving Cars
Recognize objects, predict movements, make driving decisions.
Medical Diagnosis
Detect diseases from medical images and patient data.
Types of Machine Learning
Machine Learning is broadly categorized into three main types based on how the algorithm learns from data:
Supervised Learning
Learn from labeled data. The algorithm knows the correct answers during training.
Unsupervised Learning
Find hidden patterns in unlabeled data. No correct answers provided.
Reinforcement Learning
Learn by trial and error. Agent receives rewards for good actions.
Your First ML Model
Let's build your first machine learning model! We'll create a simple Linear Regression model that predicts house prices based on size.
# Step 1: Import libraries
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Step 2: Prepare your data
# House sizes (in sq ft) and prices (in $1000s)
X = np.array([[1000], [1500], [2000], [2500], [3000]])
y = np.array([200, 300, 400, 500, 600])
# Step 3: Split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Step 4: Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Step 5: Make predictions
new_house = [[1800]] # 1800 sq ft house
predicted_price = model.predict(new_house)
print(f"Predicted price: ${predicted_price[0]:.0f},000")
# Step 6: Evaluate the model
score = model.score(X_test, y_test)
print(f"Model accuracy: {score * 100:.1f}%")
Predicted price: $360,000 Model accuracy: 100.0%
Understanding the Code
- Step 1: Import NumPy for data handling and scikit-learn for ML
- Step 2: Create sample data (features X and labels y)
- Step 3: Split data - 80% for training, 20% for testing
- Step 4: Create model and fit it to training data
- Step 5: Use trained model to predict new values
- Step 6: Evaluate how well the model performs
Common ML Algorithms
Now that you understand the basics, let's explore the most commonly used algorithms in machine learning:
Linear Regression
Predicts continuous values by finding the best-fit line through data points.
Logistic Regression
Classifies data into categories. Despite the name, it's used for classification.
Decision Trees
Makes decisions by splitting data based on feature values. Highly interpretable.
Random Forest
Ensemble of decision trees that vote together. More accurate, less overfitting.
Example: Multiple Algorithms Comparison
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
# Load famous Iris dataset
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3
)
# Compare different algorithms
models = {
"Logistic Regression": LogisticRegression(max_iter=200),
"Decision Tree": DecisionTreeClassifier(),
"Random Forest": RandomForestClassifier(n_estimators=100)
}
for name, model in models.items():
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f"{name}: {accuracy * 100:.1f}% accuracy")
Model Evaluation Metrics
How do we know if our model is good? We use evaluation metrics to measure performance:
Classification Metrics
-
Accuracy
% of correct predictions
-
Precision
Of predicted positives, how many are actually positive?
-
Recall
Of actual positives, how many did we catch?
-
F1 Score
Harmonic mean of precision and recall
Regression Metrics
-
MAE
Mean Absolute Error - average error magnitude
-
MSE
Mean Squared Error - penalizes large errors
-
RMSE
Root MSE - interpretable in original units
-
R² Score
How much variance is explained (0 to 1)
Feature Engineering
Feature engineering is the art of creating new features or transforming existing ones to improve model performance. It's often what separates good models from great ones.
Pro Tip
"Applied machine learning is basically feature engineering" - Andrew Ng. Spending time on features often yields better results than tuning algorithms.
import pandas as pd
from sklearn.preprocessing import StandardScaler, OneHotEncoder
# Example: Feature engineering for house prices
df = pd.DataFrame({
'bedrooms': [2, 3, 4, 3],
'sqft': [1000, 1500, 2000, 1800],
'year_built': [1990, 2005, 2020, 2015]
})
# Create new features
df['sqft_per_bedroom'] = df['sqft'] / df['bedrooms']
df['age'] = 2024 - df['year_built']
df['is_new'] = (df['age'] < 5).astype(int)
# Scale numerical features
scaler = StandardScaler()
df[['sqft_scaled', 'age_scaled']] = scaler.fit_transform(
df[['sqft', 'age']]
)
print(df)
Hyperparameter Tuning
Hyperparameters are settings you configure before training (unlike parameters that the model learns). Finding the optimal combination is crucial for best performance.
Grid Search
Exhaustively tries all combinations. Thorough but slow.
GridSearchCV
Random Search
Randomly samples combinations. Faster, often just as good.
RandomizedSearchCV
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
# Load data
X, y = load_iris(return_X_y=True)
# Define parameter grid
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [3, 5, 10, None],
'min_samples_split': [2, 5, 10]
}
# Grid search with cross-validation
grid_search = GridSearchCV(
RandomForestClassifier(random_state=42),
param_grid,
cv=5, # 5-fold cross-validation
scoring='accuracy',
n_jobs=-1 # Use all CPU cores
)
grid_search.fit(X, y)
print(f"Best params: {grid_search.best_params_}")
print(f"Best score: {grid_search.best_score_:.3f}")
ML Pipelines
Pipelines chain together multiple preprocessing steps and the model into a single object. This ensures consistent data transformation and prevents data leakage.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
# Create a pipeline: Scale → PCA → Classify
pipeline = Pipeline([
('scaler', StandardScaler()), # Step 1: Normalize
('pca', PCA(n_components=2)), # Step 2: Reduce dims
('classifier', RandomForestClassifier()) # Step 3: Classify
])
# Fit and predict in one line!
pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)
accuracy = pipeline.score(X_test, y_test)
print(f"Pipeline accuracy: {accuracy * 100:.1f}%")
Model Deployment
Once your model is trained and tested, you need to deploy it so others can use it. Here are the key steps:
Save the Model
Use joblib or pickle to serialize your trained model to a file.
Create an API
Use Flask or FastAPI to create endpoints that accept data and return predictions.
Containerize
Package everything in Docker for consistent deployment across environments.
Deploy to Cloud
Deploy to AWS, GCP, Azure, or platforms like Heroku, Railway.
# Save the model
import joblib
joblib.dump(model, 'model.pkl')
# Create a simple Flask API
from flask import Flask, request, jsonify
app = Flask(__name__)
model = joblib.load('model.pkl')
@app.route('/predict', methods=['POST'])
def predict():
data = request.json
features = [data['features']]
prediction = model.predict(features)
return jsonify({
'prediction': prediction[0].tolist()
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
🎉 Congratulations!
You've completed the Machine Learning fundamentals. Ready to dive deeper into specific algorithms or explore Deep Learning?