Machine Learning & Artificial Intelligence
Software automation uses Machine Learning (ML) and Artificial Intelligence (AI) to automate repetitive tasks, make predictions, and enable intelligent decision-making.
ML automates integration between software development and IT operations.
Example: GitHub Copilot uses ML to suggest code completions based on context.
Software "robots" automate repetitive, rule-based tasks.
Tools: UiPath, Automation Anywhere, Blue Prism
Automates complex business workflows involving multiple systems and decisions.
| Aspect | RPA | BPA |
|---|---|---|
| Scope | Individual repetitive tasks | End-to-end business processes |
| Complexity | Simple, rule-based | Complex workflows with decision logic |
| Example | Copy data from email to spreadsheet | Complete order fulfillment (order → payment → shipping → notification) |
| Integration | Surface-level (UI interaction) | Deep (API, database integration) |
Analogy: AI is the goal (intelligent machines), ML is the method (learning from data to achieve intelligence).
Visual Hierarchy: AI encompasses ML, which encompasses Deep Learning.
Source: Edureka
AI (broader category):
ML (specific technique within AI):
| Aspect | Traditional Programming | Machine Learning |
|---|---|---|
| Approach | Programmer writes explicit rules | Algorithm learns patterns from data |
| Adaptability | Fixed rules, must manually update | Adapts as new data arrives |
| Example | "If email contains 'FREE MONEY', mark as spam" | "Learn which patterns indicate spam from 10,000 examples" |
| Limitation | Cannot handle unpredictable inputs | Requires large datasets, may be biased |
ML models learn by analyzing data. Training method depends on data type and problem.
Learn from labeled data (input-output pairs). Model learns mapping from inputs to outputs.
Training Data (labeled):
Process:
Common Applications: Image classification, fraud detection, medical diagnosis, price prediction
Learn from unlabeled data. Model finds hidden patterns without being told what to look for.
Training Data (unlabeled):
Process:
Common Applications: Market segmentation, anomaly detection, data compression, recommendation systems
Mix of labeled (small amount) and unlabeled (large amount) data.
Labeling data is expensive and time-consuming. Semi-supervised uses small labeled dataset to guide learning on large unlabeled dataset.
Example: You have 100 labeled medical images (cancer/not cancer) and 10,000 unlabeled images. Model uses the 100 labeled to learn patterns, then applies to 10,000 unlabeled.
Learn through trial and error with rewards/penalties. Agent takes actions in environment, receives feedback.
Scenario: Training AI to play chess
Process:
Real-World Applications: Self-driving cars, robotics, game AI (AlphaGo), resource management
| Learning Type | Data Type | Use Case | Example |
|---|---|---|---|
| Supervised | Labeled (input + output) | Prediction, classification | Email spam filter |
| Unsupervised | Unlabeled (input only) | Pattern discovery, clustering | Customer segmentation |
| Semi-Supervised | Small labeled + large unlabeled | When labeling is expensive | Medical image analysis |
| Reinforcement | Feedback from actions | Sequential decision-making | Game AI, robotics |
Combines multiple ML techniques:
Companies: Tesla, Waymo, Cruise
Flowchart-like structure for making decisions based on feature values.
Is it raining?
├── Yes → Don't play tennis
└── No → Is it windy?
├── Yes → Is temperature > 25°C?
│ ├── Yes → Play tennis
│ └── No → Don't play tennis
└── No → Play tennis
How it works:
Advantages: Easy to understand, visualize, explain to non-technical people
Disadvantages: Can overfit (memorize training data), unstable (small data changes = big tree changes)
Brain-inspired networks of interconnected nodes (neurons) that process information in layers.
Layers:
How it learns:
Use Cases: Image recognition, speech recognition, language translation, game AI (AlphaGo), autonomous vehicles
Advantage: Can learn extremely complex patterns
Disadvantage: Requires massive data and computing power, "black box" (hard to explain why it made a decision)
| Model | Best For | Pros | Cons |
|---|---|---|---|
| Decision Trees | Simple classification, interpretable decisions | Easy to understand, fast, works with small data | Overfits, unstable, limited accuracy on complex problems |
| Neural Networks | Complex patterns (images, speech, text) | Highly accurate, handles complex data | Needs large data, slow to train, black box |
Predicts numeric values assuming linear relationship between input and output.
from sklearn.linear_model import LinearRegression
import numpy as np
# Training data: house size (sqft) → price ($)
sizes = np.array([[1000], [1500], [2000], [2500], [3000]])
prices = np.array([200000, 300000, 400000, 500000, 600000])
# Create and train model
model = LinearRegression()
model.fit(sizes, prices)
# Predict price for 1800 sqft house
prediction = model.predict([[1800]])
print(f"Predicted price: ${prediction[0]:,.0f}") # Output: ~$360,000
Limitation: Only works when relationship is linear (straight line). Real-world data often nonlinear.
Binary classification (yes/no, true/false, 0/1 predictions).
from sklearn.linear_model import LogisticRegression
import numpy as np
# Training data: study hours → pass/fail
hours = np.array([[1], [2], [3], [4], [5], [6], [7], [8]])
passed = np.array([0, 0, 0, 1, 1, 1, 1, 1]) # 0=fail, 1=pass
# Create and train model
model = LogisticRegression()
model.fit(hours, passed)
# Predict: Will student pass if they study 3.5 hours?
prediction = model.predict([[3.5]])
probability = model.predict_proba([[3.5]])[0][1]
print(f"Prediction: {'Pass' if prediction[0] == 1 else 'Fail'}")
print(f"Probability of passing: {probability:.2%}") # e.g., 67%
Classifies based on proximity to training data. "You are the average of your K closest neighbors."
Scenario: Recommend movies based on what similar users liked
Process (K=3):
How K affects results:
| Algorithm | Problem Type | Output | Example |
|---|---|---|---|
| Linear Regression | Regression (numeric prediction) | Continuous number | Predict house price: $350,000 |
| Logistic Regression | Binary classification | 0 or 1 (yes/no) | Email is spam: Yes (1) |
| K-Nearest Neighbors | Classification or regression | Category or number | Movie genre: Action |
Object-oriented design makes ML code reusable, maintainable, and testable.
1. Encapsulation
train() and predict() exposed2. Inheritance
HousePricePredictor inherits from base MLModel class3. Polymorphism
LinearRegression and RandomForest have predict() method4. Abstraction
predict() without knowing internal math calculationsThese principles were covered in detail in Lesson 3. Here we apply them to machine learning!
class HousePricePredictor:
"""Predicts house prices using linear regression."""
def __init__(self):
from sklearn.linear_model import LinearRegression
self.model = LinearRegression()
self.is_trained = False
def train(self, sizes, prices):
"""Train model on house sizes and prices."""
self.model.fit(sizes, prices)
self.is_trained = True
print(f"Model trained on {len(sizes)} examples")
def predict(self, size):
"""Predict price for given house size."""
if not self.is_trained:
raise ValueError("Model not trained yet!")
prediction = self.model.predict([[size]])[0]
return round(prediction, 2)
def evaluate(self, test_sizes, test_prices):
"""Calculate model accuracy on test data."""
from sklearn.metrics import r2_score
predictions = [self.predict(size[0]) for size in test_sizes]
score = r2_score(test_prices, predictions)
return score
# Usage
predictor = HousePricePredictor()
# Training data
train_sizes = [[1000], [1500], [2000], [2500]]
train_prices = [200000, 300000, 400000, 500000]
predictor.train(train_sizes, train_prices)
# Make predictions
price = predictor.predict(1800)
print(f"Predicted price for 1800 sqft: ${price:,.0f}")
# Evaluate on test data
test_sizes = [[1200], [2200]]
test_prices = [240000, 440000]
accuracy = predictor.evaluate(test_sizes, test_prices)
print(f"Model accuracy (R²): {accuracy:.2%}")
Self-driving trucks threaten 3.5 million truck driver jobs in the US. While safer and more efficient, massive retraining needed for displaced workers.
Question: Who pays for retraining? What happens to small towns dependent on trucking?
| Impact Area | Positive | Negative |
|---|---|---|
| Employment | New tech jobs, safer working conditions | Job displacement, skill mismatch |
| Economy | Increased productivity, lower costs | Income inequality, wealth concentration |
| Accessibility | Tools for disabled, elderly, remote areas | Digital divide (access gap) |
| Environment | Optimized resource use, reduced waste | Energy consumption, e-waste |
ML models learn from data. If training data is biased, the model will be biased.
Fundamental Rule: Machine learning models reflect the data they're trained on. Biased data → biased decisions.
Data reflects historical discrimination and inequalities.
Scenario: Company trains ML model to screen job applicants
Training Data: Resumes of past successful hires (mostly men in tech roles)
Result: Model learns to favor male applicants, penalizes female applicants
Why: Historical data reflects past discrimination, model amplifies it
Real Case: Amazon scrapped hiring AI in 2018 for gender bias
Training data doesn't represent population diversity.
Problem: Facial recognition models trained mostly on white faces
Result: Higher error rates for people of color (false positives in security systems)
Study: MIT found some systems had 0.8% error for white males, 34% error for dark-skinned females
Solution: Diverse, representative training datasets
Features used for training are poor proxies for what we want to measure.
System: COMPAS (predicts if criminal will reoffend)
Problem: Uses arrest history as proxy for criminality
Bias: Black defendants flagged as high-risk twice as often as white defendants (similar crimes)
Why: Arrest rates reflect policing bias, not actual crime rates
Impact: Longer sentences, denied parole for biased predictions
ML is a powerful tool, but not neutral. Developers must actively work to identify and mitigate bias. Data scientists have ethical responsibility to build fair, transparent, accountable systems.
You've completed all 8 theory lessons. Focus now on coding practice and review. Good luck on the HSC exam!