Types of ML
Welcome to the ML fundamentals section of the course. We haven’t been shy in this course about exploring ML/AI concepts, but in this section we’ll cover the fundamentals of ML from start to finish.
In this lesson, we’ll explore the three primary types of machine learning: supervised learning, unsupervised learning, and reinforcement learning.
This Lesson Will Cover
- 🎯 Supervised Learning Fundamentals
- 🔍 Unsupervised Learning Methods
- 🎮 Reinforcement Learning Basics
- 🌍 Real-World ML Applications
- 🚀 Key ML Use Cases
Supervised Learning
Supervised learning involves training a model on labeled data, where the input data comes with the correct output.
There are two main types of supervised learning:
- Regression: Predicts continuous numerical values (like prices, temperatures, etc.)
- Classification: Predicts discrete categories or classes (like spam/not spam, dog/cat/bird, etc.)
Key Characteristics:
- Labeled Data: Each training example has input-output pairs.
- Goal: Learn a mapping function from inputs to outputs.
Example 1: Regression—Predicting House Prices
The example below demonstrates regression by predicting continuous house prices based on features:
from sklearn.linear_model import LinearRegression
import numpy as np
# Training data: square footage and bedrooms (input) and price (output)
X = np.array([[1200, 2], [1500, 3], [1800, 3], [2000, 4]]) # Square footage, bedrooms
y = np.array([240000, 300000, 360000, 400000]) # Prices
# Create and train the model
model = LinearRegression()
model.fit(X, y)
# Predict the price of a 1700 sqft house with 3 bedrooms
predicted_price = model.predict([[1700, 3]])
print(f"Predicted Price: ${predicted_price[0]:,.2f}")
# Output:
# Predicted Price: $340,000.00
Example 2: Classification—Email Spam Detection
This example shows classification by predicting if an email is spam or not:
from sklearn.tree import DecisionTreeClassifier
import numpy as np
# Training data: [email_length, contains_urgent, contains_money]
X = np.array([
[100, 0, 0], # Normal email
[850, 1, 1], # Spam email
[300, 0, 0], # Normal email
[600, 1, 1], # Spam email
[400, 0, 0], # Normal email
])
y = np.array(['normal', 'spam', 'normal', 'spam', 'normal']) # Labels
# Create and train the model
classifier = DecisionTreeClassifier()
classifier.fit(X, y)
# Predict if a new email is spam
new_email = [[500, 1, 1]] # Length: 500, contains "urgent" and "money"
prediction = classifier.predict(new_email)
print(f"Email Classification: {prediction[0]}")
# Output:
# Email Classification: normal
Use Cases
Here are some problems that supervised learning can be used for:
| Use Case | Category | Example |
|---|---|---|
| Spam detection | Classification | Identifying spam vs. legitimate emails |
| Image recognition | Classification | Detecting objects like cats and dogs in photos |
| Sentiment analysis | Classification | Determining if a product review is positive or negative |
| Price prediction | Regression | Forecasting house prices based on features |
| Stock prediction | Regression | Predicting stock market trends |
Unsupervised Learning
Unsupervised learning discovers patterns in data without predefined labels.
Key Characteristics:
- Unlabeled Data: No predefined outputs.
- Goal: Identify hidden structures or groupings.
Python Example: Customer Segmentation
This example demonstrates clustering customers into two groups based on their spending habits.
from sklearn.cluster import KMeans
import numpy as np
# Customer data (standardized): [annual income, spending score, loyalty years]
data = np.array([
[0.0, 0.42, 0.17], [0.13, 0.95, 0.67], [0.25, 0.0, 0.0], [0.38, 0.90, 0.50], [0.50, 0.43, 0.33],
[0.63, 0.89, 0.83], [0.75, 0.05, 0.17], [0.88, 1.0, 1.0], [1.0, 0.37, 0.33]
])
# Create and train the model
kmeans = KMeans(n_clusters=2, random_state=0)
kmeans.fit(data)
# Assign clusters to customers
clusters = kmeans.labels_
print(f"Cluster assignments: {clusters}")
# Output:
# Cluster assignments: [0 1 0 1 0 1 0 1 0]
Use Cases
Here are some problems that unsupervised learning can be used for:
| Use Case | Category | Example |
|---|---|---|
| Customer segmentation | Clustering | Grouping customers by purchasing habits |
| Document categorization | Clustering | Organizing news articles by topic |
| Image segmentation | Clustering | Identifying regions in medical scans |
| Data visualization | Dimensionality Reduction | Using PCA to visualize complex datasets |
| Feature extraction | Dimensionality Reduction | Simplifying data for downstream tasks |
| Fraud detection | Anomaly Detection | Identifying unusual transactions in banking |
| Manufacturing defect detection | Anomaly Detection | Spotting defective products on assembly lines |
Reinforcement Learning
Reinforcement learning trains an agent to make decisions by interacting with an environment[1] and receiving rewards or penalties.
Key Characteristics:
- Trial and Error: The agent explores and learns from outcomes.
- Goal: Maximize cumulative reward over time.
Python Example: A Simple Game
This simplified example simulates an agent choosing actions randomly and receiving feedback based on predefined rewards. In real reinforcement learning, the agent would learn to maximize rewards over time.
import random
# Define environment and rewards
actions = ["left", "right", "up", "down"]
rewards = {"left": -1, "right": 1, "up": 0, "down": -1}
# Simulate an agent taking random actions
for _ in range(5): # Five moves
action = random.choice(actions)
reward = rewards[action]
print(f"Action: {action}, Reward: {reward}")
# Output:
# Action: left, Reward: -1
# Action: up, Reward: 0
# Action: down, Reward: -1
# Action: left, Reward: -1
# Action: up, Reward: 0
Use Cases
Here are some problems that reinforcement learning can be used for:
| Use Case | Category | Example |
|---|---|---|
| Training AI to play games | Gaming | AlphaGo mastering Go, or AI agents in video games |
| Robot learning | Robotics | Teaching robots to walk, grasp, or interact with objects |
| Driving decision-making | Autonomous Vehicles | Learning to navigate and respond to traffic conditions |
| Power grid management | Dynamic Optimization | Optimizing electricity distribution across grids |
| Supply chain optimization | Dynamic Optimization | Managing inventory and logistics efficiently |
| Adaptive learning | Personalized Recommendations | Tailoring educational content dynamically based on user progress |
Conclusion
Supervised learning dominates practical ML applications in business, accounting for the majority of commercial ML implementations. But it’s often used in tandem with unsupervised learning.
For example, techniques like dimensionality reduction or clustering are frequently done as preprocessing steps in the feature engineering stage, before training supervised learning models.
Key Takeaways
🎯 Supervised learning uses labeled data to learn mappings between inputs and outputs.
📊 Regression predicts continuous numerical values like prices or temperatures.
🏷️ Classification predicts discrete categories like spam/not-spam or dog/cat.
🔍 Unsupervised learning finds hidden patterns in unlabeled data through techniques like clustering and dimensionality reduction.
🤖 Reinforcement learning trains agents through trial and error interactions with an environment using rewards and penalties.
Next: Key ML Algorithms
In the next lesson, we’ll look at how some of the key ML algorithms work, including the ones that we demonstrated above.
Footnotes:
What does “interact with an environment” bring to mind, in the context of AI? If you said agentic systems then I’d say, heck yeah it does. You could skip ahead to the AI Engineering > Agents > Architectures lesson if you want to learn more about them now. ↩︎
Comments (0)
No comments yet.