Session 3: Core Concepts of AI

What is Machine Learning (ML)?

Machine Learning (ML) is a subset of Artificial Intelligence (AI) that focuses on creating systems that can learn and improve from experience without being explicitly programmed. At its core, ML involves using data and algorithms to identify patterns and make predictions or decisions. ????

Real-World Example:

  • Think of Netflix recommending shows or movies based on your past viewing habits. Netflix doesn’t “know” you, but it analyzes patterns in your preferences to suggest content.

Types of Machine Learning

Machine Learning is broadly categorized into three types:

  1. Supervised Learning:
    • The model is trained on a labeled dataset, meaning that the input data is paired with the correct output.
    • The goal is to learn a mapping function from inputs to outputs.
    Examples:
    • Predicting house prices based on features like location and size.
    • Classifying emails as spam or not spam.
    How It Works:
    • Input: Training data (e.g., features and labels).
    • Output: Predictions on unseen data.
    Python Example:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# Sample Data
X = [[1], [2], [3], [4]]  # Features (e.g., hours studied)
y = [2, 4, 6, 8]  # Labels (e.g., test scores)

# Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

# Model Training
model = LinearRegression()
model.fit(X_train, y_train)

# Prediction
predictions = model.predict(X_test)
print("Predictions:", predictions)
  1. Unsupervised Learning:
    • The model works with unlabeled data and tries to find hidden patterns or structures in the data.
    Examples:
    • Customer segmentation for targeted marketing.
    • Detecting anomalies in network traffic.
    How It Works:
    • Input: Unlabeled data (e.g., only features).
    • Output: Groupings or insights from the data.
    Python Example:
from sklearn.cluster import KMeans

# Sample Data
X = [[1], [2], [10], [12], [30]]

# KMeans Clustering
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)
print("Cluster Centers:", kmeans.cluster_centers_)
print("Labels:", kmeans.labels_)
  1. Reinforcement Learning:
    • The model learns by interacting with an environment, receiving feedback in the form of rewards or penalties, and improving its actions over time.
    Examples:
    • Training robots to walk or play games like chess.
    • Self-driving cars learning optimal routes.
    How It Works:
    • The agent takes actions in an environment.
    • It receives rewards based on the outcomes of its actions.
    • It learns to maximize cumulative rewards over time.
    Visualization:
    Imagine teaching a dog tricks. When the dog performs correctly, it gets a treat (reward). Over time, the dog learns to repeat actions that result in treats.

Hands-On Activity: Classifying Images with Google’s Teachable Machine

Let’s train a simple ML model to classify images! Follow these steps:

  1. Visit Teachable Machine: Go to Teachable Machine.
  2. Select Image Project: Choose the Image Project option.
  3. Add Classes: Create classes for the images you want to classify, e.g., Cats and Dogs.
  4. Upload Images: Upload a few images for each class.
  5. Train the Model: Click on Train Model. ????
  6. Test Your Model: Use new images to see how well the model classifies them.

Sample Code for Image Classification (Advanced)

If you’re comfortable coding, here’s a Python snippet using TensorFlow for a similar task:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Load and preprocess data
data_gen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
train_data = data_gen.flow_from_directory('dataset_path', target_size=(150, 150), batch_size=32, class_mode='binary', subset='training')
val_data = data_gen.flow_from_directory('dataset_path', target_size=(150, 150), batch_size=32, class_mode='binary', subset='validation')

# Build the model
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
MaxPooling2D((2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])

# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(train_data, validation_data=val_data, epochs=10)

# Save the model
model.save('image_classifier_model.h5')

---------------------------------------------------------------------------


FileNotFoundError Traceback (most recent call last)


<ipython-input-163-517940ec4145> in <cell line: 0>()
6 # Load and preprocess data
7 data_gen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
----> 8 train_data = data_gen.flow_from_directory('dataset_path', target_size=(150, 150), batch_size=32, class_mode='binary', subset='training')
9 val_data = data_gen.flow_from_directory('dataset_path', target_size=(150, 150), batch_size=32, class_mode='binary', subset='validation')
10


1 frames


/usr/local/lib/python3.11/dist-packages/keras/src/legacy/preprocessing/image.py in __init__(self, directory, image_data_generator, target_size, color_mode, classes, class_mode, batch_size, shuffle, seed, data_format, save_to_dir, save_prefix, save_format, follow_links, subset, interpolation, keep_aspect_ratio, dtype)
451 if not classes:
452 classes = []
--> 453 for subdir in sorted(os.listdir(directory)):
454 if os.path.isdir(os.path.join(directory, subdir)):
455 classes.append(subdir)



FileNotFoundError: [Errno 2] No such file or directory: 'dataset_path'

This code helps train a basic image classification model using TensorFlow.


Key Takeaways

  1. Machine Learning involves training machines to learn from data and make predictions.
  2. Supervised, unsupervised, and reinforcement learning are the three main types of ML.
  3. Tools like Teachable Machine make it easy to build ML models without coding.