Tuesday, March 10, 2026

AI NOTE FROM BASIC TO ADVANCE

 

Module 1: Introduction to Artificial Intelligence (AI)

1. What is Artificial Intelligence (AI)?

Artificial Intelligence (AI) means teaching computers to think and make decisions like humans.

Normally, computers only follow instructions we give them.
But with AI, computers can:

  • Learn from data

  • Recognize patterns

  • Make decisions

  • Solve problems

📌 Simple Definition:
AI is when computers are trained to perform tasks that normally require human intelligence.

Examples of human intelligence tasks:

  • Recognizing faces

  • Understanding speech

  • Making recommendations

  • Driving cars

2. Real-World Applications of AI

AI is already used in many things we use every day.

1. Smartphones

Examples:

  • Voice assistants like Siri

  • Google Assistant

What they do:

  • Answer questions

  • Set alarms

  • Send messages using voice

2. Video Recommendations

Platforms like YouTube use AI.

AI studies:

  • Videos you watch

  • Videos you like

  • Videos you search

Then it recommends videos you may like.

3. Online Shopping

Companies like Amazon use AI.

AI can:

  • Recommend products

  • Detect fraud

  • Suggest what customers should buy

4. Maps and Navigation

Apps like Google Maps use AI to:

  • Predict traffic

  • Suggest fastest routes

  • Estimate arrival time

5. Banking and Fraud Detection

Banks use AI to detect:

  • Suspicious transactions

  • Fraud

  • Unusual account activity

3. Difference Between AI, Machine Learning, and Data Science

Many people confuse these three terms. Let us understand them simply.

FieldMeaningExample
Artificial Intelligence (AI)Making computers behave intelligentlyA robot answering questions
Machine Learning (ML)A way computers learn from data automaticallyEmail spam detection
Data ScienceStudying data to find useful information and insightsAnalyzing sales data

Simple Way to Understand

Think of it like this:

AI = The big goal
Make computers intelligent.

Machine Learning = The method
Teach computers using data.

Data Science = The analysis
Study data to find useful information.

📌 Example:

A company wants to know which product will sell most.

  • Data Scientist → studies past sales data

  • Machine Learning → builds a model that learns patterns

  • AI System → predicts future sales

4. Main Tool Used in AI: Python

The main programming language used in AI is Python.

Why Python is popular for AI:

  1. Easy to learn

  2. Simple syntax

  3. Many AI libraries

  4. Large community support

Examples of AI libraries in Python:

  • TensorFlow

  • PyTorch

  • Scikit-learn

These tools help developers build AI systems faster.

5. Goal of This Module

After this module, students should:

✅ Understand what AI is
✅ Know where AI is used in real life
✅ Understand the difference between AI, Machine Learning, and Data Science
✅ Know that Python is the main language used in AI

Quick Summary

  • AI → Computers performing intelligent tasks

  • Machine Learning → Teaching computers using data

  • Data Science → Finding useful information from data

  • Python → The main programming language used to build AI systems

Absolutely! Let’s build Module 2: Python Programming for AI in a very simple, classroom-friendly way, using what it is, why it works, example, and line-by-line explanation of code.

Module 2: Python Programming for AI

Introduction

In this module, you will learn Python basics that are essential for AI. Python is easy to read and write, making it perfect for beginners.

We will focus on:

  • Variables – to store information

  • Loops – to repeat actions

  • Functions – to organize code

  • Lists and dictionaries – to store multiple pieces of data

By the end, you’ll create a small program that calculates the average score of students.

1. Variables

What it is:
A variable is a container that stores data (like numbers or text).

Why it works:
Variables let you reuse data in your program without typing it again.

Example:

score = 90
name = "Raheem"

Line by line explanation:

  • score = 90 → stores the number 90 in the variable called score

  • name = "Raheem" → stores the text "Raheem" in the variable called name

2. Loops

What it is:
A loop repeats a task multiple times.

Why it works:
Loops save time when you want to do the same action for many items.

Example:

for i in range(3):
    print("Hello AI student!")

Line by line explanation:

  • for i in range(3): → repeat the next block 3 times, i counts from 0 to 2

  • print("Hello AI student!") → shows the text "Hello AI student!" on the screen

Output:

Hello AI student!
Hello AI student!
Hello AI student!

3. Functions

What it is:
A function is a block of code that does a specific job and can be reused.

Why it works:
Functions help organize your code so it’s easier to read and use again.

Example:

def greet_student(name):
    print("Hello, " + name + "!")
    
greet_student("Raheem")

Line by line explanation:

  • def greet_student(name): → defines a function called greet_student that takes a variable name

  • print("Hello, " + name + "!") → combines "Hello, " with the value of name and prints it

  • greet_student("Raheem") → calls the function with "Raheem", output: Hello, Raheem!

4. Lists and Dictionaries

What it is:

  • List → a collection of items in order

  • Dictionary → a collection of items with keys and values

Why it works:
Lists and dictionaries store multiple pieces of information that can be easily used.

Example – List:

scores = [80, 90, 70]
print(scores[0])  # first score

Line by line explanation:

  • scores = [80, 90, 70] → creates a list of 3 numbers

  • print(scores[0]) → prints the first number in the list, 80

Example – Dictionary:

student = {"name": "Raheem", "score": 90}
print(student["name"])

Line by line explanation:

  • student = {"name": "Raheem", "score": 90} → creates a dictionary with keys name and score

  • print(student["name"]) → prints the value of key "name", output: Raheem

5. Small Exercise: Average Score of Students

Problem: Calculate the average score of 3 students.

Python Code:

# Step 1: Store student scores in a list
scores = [80, 90, 70]

# Step 2: Calculate the total
total = 0
for score in scores:
    total += score  # Add each score to total

# Step 3: Calculate average
average = total / len(scores)

# Step 4: Show the result
print("The average score is:", average)

Line by line explanation:

  1. scores = [80, 90, 70] → stores all students' scores in a list

  2. total = 0 → prepares a variable total to hold the sum

  3. for score in scores: → loop through each score in the list

  4. total += score → adds the current score to total

  5. average = total / len(scores) → divides the total by the number of scores to find the average

  6. print("The average score is:", average) → prints the average score

Output:

The average score is: 80.0

6. Goal of This Module

By completing this module, you should be able to:

✅ Use variables to store data
✅ Write loops to repeat tasks
✅ Create functions to organize code
✅ Use lists and dictionaries to store multiple data
✅ Write a small Python program that solves a real problem



Module 3: Data Analysis for AI

Introduction

Data is the fuel of AI. Before AI can make predictions, we need to collect, clean, and analyze data.

In this module, students will learn to:

  • Load datasets

  • Clean and filter data

  • Analyze data to get useful insights

Main Tools:

  • Pandas → for working with tables (like Excel)

  • NumPy → for calculations and arrays

1. Loading Datasets

What it is:
Loading a dataset means reading data from a file into Python so we can work with it.

Why it works:
Python cannot automatically understand files; we need tools like Pandas to turn data into tables we can analyze.

Example:

import pandas as pd

# Load CSV file
data = pd.read_csv("student_scores.csv")

# Show first 5 rows
print(data.head())

Line by line explanation:

  1. import pandas as pd → imports the Pandas library and gives it the shortcut name pd

  2. data = pd.read_csv("student_scores.csv") → reads the CSV file student_scores.csv into a variable data

  3. print(data.head()) → shows the first 5 rows of the dataset so we can see what it looks like

2. Cleaning Data

What it is:
Cleaning data means fixing or removing wrong, missing, or messy data.

Why it works:
AI cannot learn properly if the data is dirty. Clean data makes analysis accurate.

Example:

# Check for missing values
print(data.isnull().sum())

# Fill missing scores with 0
data['score'] = data['score'].fillna(0)

Line by line explanation:

  1. data.isnull().sum() → checks each column for missing values and counts them

  2. data['score'] = data['score'].fillna(0) → replaces missing values in the score column with 0

3. Filtering Data

What it is:
Filtering means selecting only the data you want to analyze.

Why it works:
Sometimes we want to focus on specific students, scores, or conditions.

Example:

# Filter students who scored more than 80
high_scores = data[data['score'] > 80]

print(high_scores)

Line by line explanation:

  1. data['score'] > 80 → creates a condition for scores greater than 80

  2. data[data['score'] > 80] → selects only rows that meet the condition

  3. high_scores = ... → stores the filtered data in high_scores

  4. print(high_scores) → displays the filtered students

4. Analyzing Data

What it is:
Analyzing data means finding patterns, trends, or summaries.

Why it works:
This helps us understand the dataset and make decisions or predictions.

Example: Calculate average score using Pandas and NumPy

import numpy as np

# Average using Pandas
avg_score_pd = data['score'].mean()
print("Average score (Pandas):", avg_score_pd)

# Average using NumPy
scores_array = np.array(data['score'])
avg_score_np = np.mean(scores_array)
print("Average score (NumPy):", avg_score_np)

Line by line explanation:

  1. import numpy as np → imports NumPy library

  2. data['score'].mean() → Pandas function to calculate mean (average) of score column

  3. np.array(data['score']) → converts the scores column to a NumPy array

  4. np.mean(scores_array) → NumPy function to calculate the average

  5. print(...) → shows the results

5. Mini Project: Analyze Student Exam Scores

Problem:
You have a dataset student_scores.csv with name and score.

Tasks:

  1. Load the dataset

  2. Clean missing data (fill with 0)

  3. Filter students with scores above 75

  4. Calculate the average score

  5. Show top 3 students

Python Code:

import pandas as pd
import numpy as np

# Load dataset
data = pd.read_csv("student_scores.csv")

# Clean data
data['score'] = data['score'].fillna(0)

# Filter students scoring above 75
top_students = data[data['score'] > 75]

# Calculate average
average_score = data['score'].mean()

# Show results
print("Top students:\n", top_students)
print("Average score:", average_score)

# Show top 3 students
print("Top 3 students:\n", top_students.sort_values(by='score', ascending=False).head(3))

Line by line explanation:

  • data['score'] = data['score'].fillna(0) → replaces missing scores with 0

  • top_students = data[data['score'] > 75] → filters students with scores above 75

  • average_score = data['score'].mean() → calculates the average score

  • top_students.sort_values(by='score', ascending=False).head(3) → sorts students by score in descending order and shows top 3

6. Goal of This Module

By completing this module, students will be able to:

✅ Load and explore datasets using Pandas
✅ Clean data and handle missing values
✅ Filter and analyze data to get meaningful insights
✅ Calculate averages and identify top performers using Python


Module 4: Data Visualization for AI

Introduction

After analyzing data, the next step is visualizing it. Visualization helps us see patterns, trends, and relationships that numbers alone can’t show.

Tool Used:

  • Matplotlib → a Python library to create charts and plots

Students will learn:

  • Line charts

  • Bar charts

  • Scatter plots

1. Line Charts

What it is:
A line chart shows how values change over time or order.

Why it works:
It helps us see trends clearly, like scores improving over weeks.

Example:

import matplotlib.pyplot as plt

# Study hours for 5 students
hours = [1, 2, 3, 4, 5]
scores = [50, 60, 70, 80, 90]

# Create line chart
plt.plot(hours, scores, marker='o')
plt.title("Study Hours vs Exam Scores")
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.show()

Line by line explanation:

  1. import matplotlib.pyplot as plt → imports Matplotlib library with shortcut plt

  2. hours = [1, 2, 3, 4, 5] → creates a list of study hours

  3. scores = [50, 60, 70, 80, 90] → creates a list of exam scores

  4. plt.plot(hours, scores, marker='o') → draws a line connecting hours to scores, with circle markers

  5. plt.title(...) → sets the chart title

  6. plt.xlabel(...) → labels the X-axis

  7. plt.ylabel(...) → labels the Y-axis

  8. plt.show() → displays the chart

2. Bar Charts

What it is:
A bar chart shows comparisons between categories using bars.

Why it works:
It’s easier to compare values visually.

Example:

students = ["Ali", "Bola", "Chioma", "David"]
scores = [75, 88, 90, 60]

plt.bar(students, scores, color='green')
plt.title("Exam Scores of Students")
plt.xlabel("Students")
plt.ylabel("Scores")
plt.show()

Line by line explanation:

  1. students = ["Ali", "Bola", "Chioma", "David"] → list of student names

  2. scores = [75, 88, 90, 60] → their scores

  3. plt.bar(students, scores, color='green') → creates a vertical bar chart, bars are green

  4. plt.title(...) → sets chart title

  5. plt.xlabel(...) → labels X-axis (students)

  6. plt.ylabel(...) → labels Y-axis (scores)

  7. plt.show() → displays the chart

3. Scatter Plots

What it is:
A scatter plot shows the relationship between two sets of numbers.

Why it works:
It helps us see correlations, for example, whether more study hours lead to higher scores.

Example:

hours = [1, 2, 3, 4, 5]
scores = [50, 60, 70, 80, 90]

plt.scatter(hours, scores, color='red')
plt.title("Study Hours vs Exam Scores")
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.show()

Line by line explanation:

  1. plt.scatter(hours, scores, color='red') → plots each pair of hours and scores as a red dot

  2. plt.title(...) → chart title

  3. plt.xlabel(...) → X-axis label

  4. plt.ylabel(...) → Y-axis label

  5. plt.show() → displays the scatter plot

4. Mini Project: Study Hours vs Exam Scores

Goal: Show how study hours relate to exam scores for 6 students.

Python Code:

import matplotlib.pyplot as plt

# Data
students = ["Ali", "Bola", "Chioma", "David", "Emeka", "Fatima"]
hours = [1, 2, 3, 4, 5, 6]
scores = [55, 60, 70, 80, 85, 95]

# Line chart
plt.plot(hours, scores, marker='o', color='blue', label='Scores')
plt.title("Study Hours vs Exam Scores")
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.legend()
plt.show()

# Scatter chart
plt.scatter(hours, scores, color='red')
plt.title("Study Hours vs Exam Scores (Scatter Plot)")
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.show()

Line by line explanation:

  1. students = [...] → list of students

  2. hours = [...] → number of hours each student studied

  3. scores = [...] → exam scores

  4. plt.plot(hours, scores, marker='o', color='blue', label='Scores') → line chart with markers

  5. plt.legend() → shows the label "Scores" on the chart

  6. plt.scatter(hours, scores, color='red') → scatter plot to see correlation

  7. plt.show() → displays each chart

What students learn:

  • How to plot line and scatter charts

  • How to add titles, labels, and legends

  • How to visualize relationships in data

5. Goal of This Module

By the end of this module, students should be able to:

✅ Create line, bar, and scatter charts
✅ Label charts for clarity
✅ Visualize relationships between variables
✅ Use Python to turn raw data into visual insights

Here’s Module 5: Machine Learning, structured for beginners with what it is, why it works, examples, and line-by-line explanation of code.

Module 5: Machine Learning for AI

Introduction

Machine Learning (ML) is a way for computers to learn from data and make predictions without being explicitly programmed.

In this module, students will:

  • Learn regression and classification

  • Train ML models

  • Evaluate model performance

  • Apply ML to predict student performance

Tool Used:

  • Scikit-learn → library for building ML models easily

1. What is Regression

What it is:
Regression predicts a continuous value, like predicting a student’s exam score.

Why it works:
It finds the relationship between input (study hours) and output (scores).

Example: Predict score based on hours studied.

from sklearn.linear_model import LinearRegression
import numpy as np

# Data
hours = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)  # input feature
scores = np.array([50, 60, 70, 80, 90])          # target output

# Create model
model = LinearRegression()

# Train model
model.fit(hours, scores)

# Predict
predicted = model.predict([[6]])
print("Predicted score for 6 hours:", predicted[0])

Line by line explanation:

  1. from sklearn.linear_model import LinearRegression → imports linear regression model

  2. hours = np.array([...]).reshape(-1, 1) → converts list of hours to correct shape for the model

  3. scores = np.array([...]) → target scores to predict

  4. model = LinearRegression() → creates a linear regression model

  5. model.fit(hours, scores) → trains the model on the data

  6. predicted = model.predict([[6]]) → predicts score for 6 study hours

  7. print(...) → shows the predicted value

Output:

Predicted score for 6 hours: 100.0

2. What is Classification

What it is:
Classification predicts a category instead of a number.

Why it works:
It helps us group data, for example, labeling students as “Pass” or “Fail”.

Example: Predict if a student passed (score ≥ 60).

from sklearn.tree import DecisionTreeClassifier

# Data
hours = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
labels = ["Fail", "Fail", "Pass", "Pass", "Pass"]

# Create model
clf = DecisionTreeClassifier()

# Train model
clf.fit(hours, labels)

# Predict
result = clf.predict([[2.5]])
print("Prediction for 2.5 hours:", result[0])

Line by line explanation:

  1. from sklearn.tree import DecisionTreeClassifier → imports a classifier

  2. hours = np.array([...]).reshape(-1, 1) → input features

  3. labels = [...] → target categories (“Pass” or “Fail”)

  4. clf = DecisionTreeClassifier() → creates the decision tree model

  5. clf.fit(hours, labels) → trains the model

  6. result = clf.predict([[2.5]]) → predicts category for 2.5 hours

  7. print(...) → shows the predicted category

Output:

Prediction for 2.5 hours: Fail

3. Model Training

What it is:
Training is the process of teaching the ML model using data so it can make predictions.

Why it works:
The model learns patterns from input-output pairs.

Key Steps:

  1. Prepare data

  2. Choose model (regression/classification)

  3. Train model using .fit()

4. Model Evaluation

What it is:
Evaluation measures how accurate the model is.

Why it works:
Even after training, models can make mistakes. Evaluation tells us if it’s reliable.

Example – Regression evaluation:

from sklearn.metrics import mean_squared_error

# True scores
y_true = [50, 60, 70, 80, 90]
# Predicted scores
y_pred = model.predict(hours)

# Calculate error
mse = mean_squared_error(y_true, y_pred)
print("Mean Squared Error:", mse)

Line by line explanation:

  1. from sklearn.metrics import mean_squared_error → import function to measure error

  2. y_pred = model.predict(hours) → predicted scores

  3. mean_squared_error(y_true, y_pred) → calculates average squared difference

  4. print(...) → shows how far predictions are from actual scores

5. Project: Predict Student Performance

Problem: Predict exam scores of students based on study hours.

Python Code:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Data
hours = np.array([1, 2, 3, 4, 5, 6, 7]).reshape(-1, 1)
scores = np.array([50, 55, 65, 70, 75, 85, 90])

# Create and train model
model = LinearRegression()
model.fit(hours, scores)

# Predict scores
predicted_scores = model.predict(hours)
print("Predicted scores:", predicted_scores)

# Evaluate model
mse = mean_squared_error(scores, predicted_scores)
print("Mean Squared Error:", mse)

# Predict score for a new student who studies 8 hours
new_score = model.predict([[8]])
print("Predicted score for 8 hours:", new_score[0])

Line by line explanation:

  1. hours = np.array([...]).reshape(-1,1) → input study hours

  2. scores = np.array([...]) → actual exam scores

  3. model = LinearRegression() → create regression model

  4. model.fit(hours, scores) → train the model

  5. predicted_scores = model.predict(hours) → get predictions for existing data

  6. mse = mean_squared_error(scores, predicted_scores) → check accuracy

  7. new_score = model.predict([[8]]) → predict new student score

6. Goal of This Module

By completing this module, students should be able to:

✅ Understand regression and classification
✅ Train ML models using Scikit-learn
✅ Evaluate predictions using error metrics
✅ Build a simple AI model to predict student performance



Module 6: Deep Learning for AI

Introduction

Deep Learning is a type of AI that uses neural networks to learn patterns from data, just like the human brain. It is used in advanced AI systems like:

  • Image recognition

  • Speech recognition

  • Self-driving cars

Tool Used:

  • TensorFlow → a library for building and training neural networks

In this module, students will:

  • Understand neural networks

  • Train AI models

  • Make predictions

1. What is a Neural Network

What it is:
A neural network is a model made of layers of “neurons” (nodes) that learn patterns from data.

Why it works:
It can learn complex relationships between input and output data, much better than simple regression.

Example Concept:

  • Input layer → features (e.g., study hours)

  • Hidden layers → neurons process data

  • Output layer → prediction (e.g., exam score)

2. Setting Up TensorFlow

Why it works:
TensorFlow allows us to easily define layers, train networks, and make predictions.

Example: Importing TensorFlow

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np

Line by line explanation:

  1. import tensorflow as tf → imports TensorFlow library

  2. from tensorflow.keras.models import Sequential → model type with layers in order

  3. from tensorflow.keras.layers import Dense → layer type where each neuron connects to all neurons in previous layer

  4. import numpy as np → for handling input data as arrays

3. Creating a Basic Neural Network

Mini Exercise: Predict student exam scores based on study hours

# Input (hours studied) and output (scores)
hours = np.array([1, 2, 3, 4, 5, 6, 7], dtype=float)
scores = np.array([50, 55, 65, 70, 75, 85, 90], dtype=float)

# Build the model
model = Sequential([
    Dense(5, input_shape=[1], activation='relu'),  # hidden layer with 5 neurons
    Dense(1)  # output layer with 1 neuron
])

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model
model.fit(hours, scores, epochs=500, verbose=0)

# Make a prediction
new_score = model.predict([8.0])
print("Predicted score for 8 hours:", new_score[0][0])

Line by Line Explanation

  1. hours = np.array([...], dtype=float) → input data (hours studied) as float

  2. scores = np.array([...], dtype=float) → output data (exam scores) as float

  3. model = Sequential([...]) → creates a neural network with layers:

    • Dense(5, input_shape=[1], activation='relu') → hidden layer with 5 neurons, ReLU activation

    • Dense(1) → output layer with 1 neuron for prediction

  4. model.compile(optimizer='adam', loss='mean_squared_error') → prepares the model with:

    • Optimizer (adam) → helps the model learn efficiently

    • Loss function (mean_squared_error) → measures how far predictions are from real scores

  5. model.fit(hours, scores, epochs=500, verbose=0) → trains the model on data for 500 cycles (epochs)

  6. model.predict([8.0]) → predicts score for a student who studies 8 hours

  7. print(...) → displays the predicted score

Output Example:

Predicted score for 8 hours: 97.5

4. Goal of This Module

By the end of this module, students should be able to:

✅ Understand neural networks and how they work
✅ Build a basic neural network model in TensorFlow
✅ Train a model using data
✅ Make predictions for new inputs


Module 7: AI Projects

Introduction

This is the capstone module where students apply everything they learned:

  • Python programming

  • Data analysis

  • Data visualization

  • Machine learning

  • Deep learning

Students will build real-world applications to see how AI solves real problems.

Project 1: Student Performance Prediction

Goal: Predict a student’s exam score based on study hours.

Tools Used: Python, Pandas, NumPy, Scikit-learn, Matplotlib

Steps:

  1. Load Data

import pandas as pd

data = pd.read_csv("student_scores.csv")
print(data.head())
  1. Clean Data

data['score'] = data['score'].fillna(0)
  1. Visualize Data

import matplotlib.pyplot as plt

plt.scatter(data['hours'], data['score'])
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.title("Study Hours vs Exam Score")
plt.show()
  1. Train Model

from sklearn.linear_model import LinearRegression
import numpy as np

X = np.array(data['hours']).reshape(-1,1)
y = np.array(data['score'])

model = LinearRegression()
model.fit(X, y)
  1. Predict Scores

predicted_score = model.predict([[8]])
print("Predicted score for 8 hours:", predicted_score[0])

What students learn:

  • How to combine data cleaning, visualization, and machine learning

  • Predict future student performance

Project 2: Bank Fraud Detection System

Goal: Detect fraudulent transactions using AI.

Tools Used: Python, Pandas, NumPy, Scikit-learn

Steps:

  1. Load Data

data = pd.read_csv("bank_transactions.csv")
print(data.head())
  1. Clean Data

data = data.dropna()  # remove missing values
  1. Prepare Features & Labels

X = data[['amount', 'time', 'location']]
y = data['fraud']  # 0 = no fraud, 1 = fraud
  1. Train Classification Model

from sklearn.tree import DecisionTreeClassifier

model = DecisionTreeClassifier()
model.fit(X, y)
  1. Predict Fraud

new_transaction = [[5000, 12, 3]]  # amount, time, location
prediction = model.predict(new_transaction)
print("Fraudulent?" , "Yes" if prediction[0]==1 else "No")

What students learn:

  • How AI can classify transactions

  • Train models to detect patterns in real-world data

Project 3: Simple Chatbot

Goal: Build a chatbot that answers basic questions.

Tools Used: Python, TensorFlow / basic AI logic

Steps:

  1. Create Questions and Answers

qa_pairs = {
    "Hello": "Hi there!",
    "How are you?": "I'm fine, thank you!",
    "What is AI?": "AI is when computers can think and learn like humans."
}
  1. Create Simple Chat Loop

while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        break
    response = qa_pairs.get(user_input, "Sorry, I don't understand.")
    print("Bot:", response)
  1. Test the Chatbot

  • Input: "Hello" → Output: "Hi there!"

  • Input: "What is AI?" → Output: "AI is when computers can think and learn like humans."

What students learn:

  • How to use Python dictionaries for AI responses

  • Build interactive AI applications

Module Goal

By completing Module 7, students will:

✅ Apply Python programming, data analysis, and visualization in projects
✅ Build predictive AI models using machine learning
✅ Create real-world AI applications
✅ Gain hands-on experience that can be used for portfolios or jobs



Final Module: Deployment – AI Web Applications

Introduction

After building AI projects, the next step is deployment – sharing your AI project online so others can use it through a web browser.

Tool Used:

  • Flask → a simple Python framework to create web applications

Goal: Create a simple AI web app that predicts student scores.

1. What is Flask

What it is:
Flask is a Python library that lets you build web apps quickly.

Why it works:
It handles web requests and displays your AI output in a browser, without complex setup.

2. Creating a Simple AI Web App

Mini Exercise: Use your student performance prediction model online.

Steps:

Step 1: Install Flask

pip install flask

Step 2: Create Flask App

from flask import Flask, request, render_template
import numpy as np
from sklearn.linear_model import LinearRegression

app = Flask(__name__)

# Simple model
X = np.array([1,2,3,4,5,6,7]).reshape(-1,1)
y = np.array([50,55,65,70,75,85,90])
model = LinearRegression()
model.fit(X, y)

# Home route
@app.route('/')
def home():
    return render_template("index.html")  # simple HTML page

# Prediction route
@app.route('/predict', methods=['POST'])
def predict():
    hours = float(request.form['hours'])
    prediction = model.predict([[hours]])
    return f"Predicted score for {hours} hours: {prediction[0]:.2f}"

if __name__ == '__main__':
    app.run(debug=True)

Line by Line Explanation

  1. from flask import Flask, request, render_template → imports Flask and tools for handling web forms and HTML

  2. app = Flask(__name__) → creates a Flask app instance

  3. model = LinearRegression(); model.fit(X, y) → trains your ML model as before

  4. @app.route('/') → sets up the home page URL

  5. render_template("index.html") → shows an HTML page (you create a form to enter hours)

  6. @app.route('/predict', methods=['POST']) → creates a route to handle form submission

  7. hours = float(request.form['hours']) → gets user input from the web form

  8. model.predict([[hours]]) → predicts the score using ML model

  9. app.run(debug=True) → runs the app locally so you can see it in a browser

3. Creating HTML Form

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Student Score Prediction</title>
</head>
<body>
    <h2>Predict Student Score</h2>
    <form action="/predict" method="post">
        Enter study hours: <input type="text" name="hours">
        <input type="submit" value="Predict">
    </form>
</body>
</html>

Explanation:

  • <form action="/predict" method="post"> → sends input to /predict route

  • <input type="text" name="hours"> → user enters hours studied

  • <input type="submit" value="Predict"> → submit button

4. Testing the App

  1. Run the Flask app:

python app.py
  1. Open browser → go to http://127.0.0.1:5000/

  2. Enter study hours → see predicted score

✅ Result of This Course

After completing all modules, students will be able to:

  • Analyze data using Python, Pandas, NumPy

  • Build machine learning models with Scikit-learn

  • Create AI applications using deep learning with TensorFlow

  • Visualize data with Matplotlib

  • Deploy AI projects online using Flask

  • Work on real-world AI projects like student performance prediction, fraud detection, and chatbots



0 comments:

Post a Comment

 

BEST COMPUTER GUIDE Written by Abigail Odenigbo, Published @ 2014 by NOBIGDEAL(Ipietoon)