0% found this document useful (0 votes)
55 views

Ai Labs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Ai Labs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Artificial Intelligence Vacuum-Cleaner Agent in Two Rooms (A And B) IIEE

7th Semester Institute of Industrial Electronics Engineering LAB 1

OBJECTIVE:
The objective of this lab is to design an intelligent vacuum cleaner agent using artificial intelligence
techniques. The agent will be responsible for cleaning two rooms, labeled as Room A and Room B. The
goal is to implement a rational agent that can effectively navigate, perceive its environment, and make
decisions to keep both rooms clean.
LAB DESCRIPTION:

1. Environment Setup:
Define a simulation environment with two rooms (Room A and Room B).
Initialize the rooms with dirt in random locations.
2. Agent Characteris�cs:
Design a rational vacuum-cleaner agent that can:
Perceive the current state of the environment.
Decide the next action based on the perceived state.
Perform actions to clean the rooms.
3. Sensing and Ac�ng:
Implement sensing functions for the agent to detect the presence of dirt in a room.
Develop actions for the agent to move left or right, clean the current location, or stay idle.
4. Decision-Making:
Use AI concepts such as simple rule-based systems or state-space search to make decisions.
Define rules for the agent to determine its actions based on the current state.
5. Learning (Op�onal):
Implement a learning mechanism for the agent to adapt its behavior over time.
Utilize reinforcement learning or other learning algorithms to improve the cleaning efficiency.
6. Visualiza�on:
Create a graphical representation of the environment and agent's actions.
Display the rooms, the current location of the agent, and the cleanliness status.
Step 1: Import Necessary Modules
python
import random
We import the `random` module to generate random values, which will be useful for ini�alizing the environment
and making random decisions.

Step 2: Define the Vacuum Cleaner Agent Class


python
class VacuumCleanerAgent:
def __init__(self, environment):
self.environment = environment
self.loca�on = random.choice(list(environment.keys()))
Here, we define a class `VacuumCleanerAgent`. The `__init__` method ini�alizes the agent with a reference to
the environment and places the agent in a random loca�on within the environment.

Step 3: Define Sensing and Ac�ng Methods


python
def sense(self):
return self.environment[self.loca�on]
def act(self, ac�on):
if ac�on == "le�":
self.loca�on = "A"
elif ac�on == "right":
self.loca�on = "B"
elif ac�on == "clean":
self.environment[self.loca�on] = 0

We define `sense` to get the dirt status of the current loca�on and `act` to perform ac�ons based on the input
argument. The agent can move le�, right, or clean the current loca�on.

Step 4: Simulate the Environment


python
def simulate_environment():
return {"A": random.randint(0, 1), "B": random.randint(0, 1)}
The `simulate_environment` func�on ini�alizes the environment with dirt randomly placed in rooms A and B.

Step 5: Main Simula�on


python
def main():
environment = simulate_environment()
agent = VacuumCleanerAgent(environment)
for _ in range(10): # Simulate 10 steps
print(f"Current State: {environment}")
print(f"Agent Loca�on: {agent.loca�on}")
dirt_status = agent.sense()

if dirt_status == 1:
print("Agent cleaning...")
agent.act("clean")
else:
ac�on = random.choice(["le�", "right"])
print(f"Agent moving {ac�on}...")
agent.act(ac�on)
print("---------")
if __name__ == "__main__":
main()

In the `main` func�on, we simulate the environment and the agent's ac�ons for 10 steps. The agent senses the
dirt status, makes decisions based on the dirt status, and performs ac�ons accordingly. The current state of the
environment and the agent's loca�on are printed at each step.
PYTHON CODE:
import random

class VacuumCleanerAgent:
def __init__(self, environment):
self.environment = environment
self.location = random.choice(list(environment.keys()))

def sense(self):
return self.environment[self.location]

def act(self, action):


if action == "left":
self.location = "A"
elif action == "right":
self.location = "B"
elif action == "clean":
self.environment[self.location] = 0

def decide_action(self):
is_dirty = self.sense()
if is_dirty:
return "clean"
else:
# Implement a decision-making rule here (e.g., move to
the other room if both are clean)
if self.location == "A":
return "right"
else:
return "left"

def simulate_environment():
return {"A": random.randint(0, 1), "B": random.randint(0, 1)}

def main():
environment = simulate_environment()
agent = VacuumCleanerAgent(environment)

for _ in range(10):
print(f"Current State: {environment}")
print(f"Agent Location: {agent.location}")

dirt_status = agent.sense()
action = agent.decide_action() # Use the agent's decision-
making logic
if dirt_status == 1:
print("Agent cleaning...")
else:
print(f"Agent moving {action}...")
agent.act(action)
print("---------")

if __name__ == "__main__":
main()
PYTHON OUTPUT:
To Implement The Breadth-First Search (BFS)
Artificial Intelligence IIEE
Algorithm
7th Semester Institute of Industrial Electronics Engineering LAB 2

OBJECTIVE:
The objective of this AI Design Lab is to implement the Breadth-First Search (BFS) algorithm. Breadth-
First Search is a fundamental graph traversal algorithm used in various applications, such as pathfinding,
network analysis, and puzzle solving. This lab aims to provide a hands-on experience in understanding
and implementing BFS, demonstrating its application in graph traversal.

Description:
Breadth-First Search is an algorithm used to traverse or search through the nodes of a graph in breadth
ward motion. Starting at the root (selecting some arbitrary node as the starting point), the algorithm
explores the neighbor nodes at the present depth prior to moving on to nodes at the next level of depth.
This lab will guide you through the process of implementing BFS step by step.

Working Steps:

1. Understanding Breadth-First Search:


• Familiarize yourself with the BFS algorithm, its principles, and its application in graph
traversal.
2. Graph Representation:
• Choose a suitable representation for the graph (e.g., adjacency matrix, adjacency list).
• Create a sample graph to test the BFS algorithm.
3. Queue Implementation:
• Implement a queue data structure (FIFO) that will be used to keep track of the nodes during
the BFS traversal.
4. Breadth-First Search Algorithm:
• Create a function to perform BFS on the graph.
• Start from a specified node (usually the root).
• Use the queue to keep track of the nodes to be visited.
• Mark visited nodes to avoid revisiting.
5. Visualization (Optional):
• Implement a visualization component to illustrate the BFS traversal process. This could
include graph rendering and highlighting nodes in the order they are visited.
6. Testing:
• Test the BFS algorithm on different graphs, including graphs with cycles and disconnected
components.
• Validate the correctness of the algorithm by comparing the results with manual calculations.
7. Optimizations (Optional):
• Explore possible optimizations to the basic BFS algorithm, such as early termination
conditions or memory optimizations.
PYTHON CODE:
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)

def bfs(self, start):


visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node, end=' ')

for neighbor in self.graph[node]:


if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
# Example usage:
if __name__ == "__main__":
# Create a sample graph
graph = Graph()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
# Perform BFS starting from node 2
print("BFS starting from node 2:")
graph.bfs(2)

PYTHON OUTPUT:
To Implement the Depth-First Search (DFS)
Artificial Intelligence IIEE
Algorithm
7th Semester Institute of Industrial Electronics Engineering LAB 3

OBJECTIVE:
The objective of this AI Design Lab is to implement the Depth-First Search (DFS) algorithm. Depth-First
Search is a fundamental graph traversal algorithm that explores as far as possible along each branch before
backtracking. This lab aims to provide hands-on experience in understanding and implementing DFS,
demonstrating its application in graph traversal.

DESCRIPTION:
Depth-First Search is an algorithm used to traverse or search through the nodes of a graph in a depthward
motion. Starting at the root (selecting some arbitrary node as the starting point), the algorithm explores as
far as possible along each branch before backtracking. This lab will guide you through the process of
implementing DFS step by step.

Working Steps:
1. Understanding Depth-First Search:
• Familiarize yourself with the DFS algorithm, its principles, and its application in graph
traversal.
2. Graph Representation:
• Choose a suitable representation for the graph (e.g., adjacency matrix, adjacency list).
• Create a sample graph to test the DFS algorithm.
3. Depth-First Search Algorithm:
• Create a function to perform DFS on the graph.
• Start from a specified node (usually the root).
• Use recursion or a stack to keep track of the nodes to be visited.
• Mark visited nodes to avoid revisiting.
4. Visualization (Optional):
• Implement a visualization component to illustrate the DFS traversal process. This could
include graph rendering and highlighting nodes in the order they are visited.
5. Testing:
• Test the DFS algorithm on different graphs, including graphs with cycles and disconnected
components.
• Validate the correctness of the algorithm by comparing the results with manual calculations.
6. Optimizations (Optional):
• Explore possible optimizations to the basic DFS algorithm, such as early termination
conditions or memory optimizations.
PYTHON CODE:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)

def dfs_util(self, node, visited):


visited.add(node)
print(node, end=' ')
for neighbor in self.graph[node]:
if neighbor not in visited:
self.dfs_util(neighbor, visited)
def dfs(self, start):
visited = set()
self.dfs_util(start, visited)
# Example usage:
if __name__ == "__main__":
# Create a sample graph
graph = Graph()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
# Perform DFS starting from node 2
print("DFS starting from node 2:")
graph.dfs(2)

PYTHON OUTPUT:
Artificial Intelligence To implement the A* (A-star) algorithm IIEE
7th Semester Institute of Industrial Electronics Engineering LAB 4

OBJECTIVE:
The objective of this AI Design Lab is to implement the A* (A-star) algorithm. A* is a widely used
pathfinding algorithm in artificial intelligence and robotics. It efficiently finds the shortest path in a graph
while considering both the cost of the path and an estimate of the remaining cost to reach the goal. This
lab aims to provide hands-on experience in understanding and implementing the A* algorithm,
demonstrating its application in pathfinding.

DESCRIPTION:
The A* algorithm combines the principles of Dijkstra's algorithm and greedy best-first search. It maintains
a priority queue of nodes to explore, selecting the node that minimizes the sum of the cost to reach it and
a heuristic estimate of the remaining cost to reach the goal. This lab will guide you through the process of
implementing A* step by step.

Working Steps:
1. Understanding A* Algorithm:
• Familiarize yourself with the A* algorithm, its heuristic function, and its application in
pathfinding.
1. Graph Representation:
• Choose a suitable representation for the graph (e.g., adjacency matrix, adjacency list).
• Create a sample graph to test the A* algorithm.
2. Heuristic Function:
• Design a heuristic function that estimates the remaining cost from a given node to the goal.
This function should be admissible, meaning it never overestimates the true cost.
3. A* Algorithm Implementation:
• Create a function to perform A* on the graph.
• Use a priority queue (usually implemented with a min-heap) to efficiently select nodes with
the lowest combined cost and heuristic estimate.
• Maintain a record of the actual cost to reach each node.
4. Visualization (Optional):
• Implement a visualization component to illustrate the A* search process. This could include
graph rendering and highlighting nodes in the order they are visited.
5. Testing:
• Test the A* algorithm on different graphs, including graphs with varying terrain costs.
• Validate the correctness and optimality of the algorithm by comparing results with manual
calculations and other pathfinding algorithms.
6. Optimizations (Optional):
• Explore possible optimizations to the basic A* algorithm, such as early termination
conditions or memory optimizations.
PYTHON CODE:
import heapq
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, u, v, cost):
if u not in self.graph:
self.graph[u] = []
self.graph[u].append((v, cost))
def astar(self, start, goal, heuristic):
priority_queue = [(0, start, [])]
visited = set()
while priority_queue:
(current_cost, current_node, path) =
heapq.heappop(priority_queue)
if current_node in visited:
continue
path = path + [current_node]
if current_node == goal:
return path
visited.add(current_node)
for neighbor, cost in self.graph.get(current_node,
[]):
if neighbor not in visited:
total_cost = current_cost + cost +
heuristic(neighbor, goal)
heapq.heappush(priority_queue, (total_cost,
neighbor, path))
return None
# Example usage:
if __name__ == "__main__":
# Create a sample graph
graph = Graph()
graph.add_edge('A', 'B', 4)
graph.add_edge('A', 'C', 2)
graph.add_edge('B', 'C', 5)
graph.add_edge('B', 'D', 10)
graph.add_edge('C', 'D', 3)
graph.add_edge('D', 'E', 7)
graph.add_edge('E', 'A', 8)

# Define a heuristic function (Euclidean distance)


def heuristic(node, goal):
heuristic_cost = {
'A': 10,
'B': 6,
'C': 4,
'D': 2,
'E': 0
}
return heuristic_cost[node]
# Perform A* from 'A' to 'E'
result_path = graph.astar('A', 'E', heuristic)

if result_path:
print("A* Path:", result_path)
else:
print("No path found.")

PYTHON OUTPUT:
Artificial Intelligence To implement the classic Tic-Tac-Toe game IIEE
7th Semester Institute of Industrial Electronics Engineering LAB 5

OBJECTIVE:
The objective of this AI Design Lab is to implement the classic Tic-Tac-Toe game. This lab aims to provide
hands-on experience in designing and implementing a simple game, fostering an understanding of game
logic and user interaction.

DESCRIPTION:
Tic-Tac-Toe is a two-player game played on a 3x3 grid. Players take turns marking a cell with their symbol
('X' or 'O') with the goal of getting three of their symbols in a row, either horizontally, vertically, or
diagonally. This lab will guide you through the process of implementing the Tic-Tac-Toe game,
considering user input, game state, and end conditions.

Working Steps:
1. Game Board Representation:
• Choose a suitable representation for the Tic-Tac-Toe game board (e.g., a 2D list).
2. Displaying the Game Board:
• Create a function to display the current state of the game board.
3. Player Input:
• Implement a function to take input from the players, allowing them to place their 'X' or 'O' on
the board.

4. Validating Moves:
• Ensure that the input moves are valid (i.e., the selected cell is empty).
5. Checking for Win or Draw:
• Implement a function to check for a win or a draw after each move.
6. Switching Players:
• Create a mechanism to switch between 'X' and 'O' for each turn.
7. Game Loop:
• Develop a game loop that continues until there is a winner or a draw.
8. User Interface (Optional):
• If desired, implement a simple graphical user interface to enhance the user experience.
9. Testing:
• Test the Tic-Tac-Toe game with various scenarios, ensuring that the win and draw conditions
are correctly identified.
PYTHON CODE:
def display_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)

def check_winner(board, player):


# Check rows, columns, and diagonals
for i in range(3):
if all(board[i][j] == player for j in range(3)) or
all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or
all(board[i][2 - i] == player for i in range(3)):
return True
return False

def is_board_full(board):
return all(board[i][j] != ' ' for i in range(3) for j in
range(3))

def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'
while True:
display_board(board)
print(f"Player {current_player}'s turn")
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
if board[row][col] == ' ':
board[row][col] = current_player
if check_winner(board, current_player):
display_board(board)
print(f"Player {current_player} wins!")
break
elif is_board_full(board):
display_board(board)
print("It's a draw!")
break
current_player = 'O' if current_player == 'X' else
'X'
else:
print("Invalid move. Try again.")

if __name__ == "__main__":
tic_tac_toe()
PYTHON OUTPUT:
To explore and implement basic functionalities of Python
Artificial Intelligence IIEE
libraries such as `math`, `numpy`, and `scipy
7th Semester Institute of Industrial Electronics Engineering LAB 6

OBJECTIVE:
The objec�ve of this AI Design Lab is to explore and implement basic func�onali�es of Python libraries such as
`math`, `numpy`, and `scipy`. These libraries provide powerful tools for mathema�cal and scien�fic compu�ng,
offering a wide range of func�ons for numerical opera�ons, linear algebra, and scien�fic tasks.

DESCRIPTION:
This lab aims to introduce you to the usage and capabili�es of three fundamental Python libraries: `math`,
`numpy`, and `scipy`. Through this lab, you will gain prac�cal experience in performing mathema�cal opera�ons,
working with arrays, and leveraging advanced scien�fic func�onali�es.

Working Steps:
1. Exploration of Math Library:
• Explore the basic func�onali�es of the `math` library, which provides mathema�cal func�ons.
• Experiment with func�ons such as `sqrt`, `sin`, `cos`, `tan`, `log`, etc.
• Understand the usage of constants like `pi` and `e`.

2. Introduction to NumPy:
• Learn about the NumPy library, a powerful library for numerical compu�ng in Python.
• Explore the crea�on and manipula�on of NumPy arrays.
• Perform basic mathema�cal opera�ons on arrays.

3. NumPy Array Operations:


• Inves�gate various array opera�ons, such as element-wise opera�ons, array slicing, and reshaping.
• Understand the difference between NumPy arrays and Python lists.

4. Linear Algebra with NumPy:


• U�lize NumPy for linear algebra opera�ons, including matrix mul�plica�on, determinant calcula�on,
and solving linear equa�ons.

5. Introduction to SciPy:
• Familiarize yourself with the SciPy library, which builds on NumPy and provides addi�onal
func�onali�es for scien�fic compu�ng.

6. SciPy Statistical Operations:


• Explore sta�s�cal opera�ons available in SciPy, including mean, median, standard devia�on, and
correla�on.

7. SciPy Optimization:
• Understand how to use SciPy for op�miza�on tasks, such as minimizing or maximizing func�ons.

8. SciPy Integration:
• Explore integra�on func�ons in SciPy for numerical integra�on.

9. Practical Application:
• Apply the learned concepts to a prac�cal problem, such as data analysis, simula�on, or op�miza�on.
PYTHON CODE:

MATH LIBRARY:
import math
# Basic math operations
print("Square root of 36:", math.sqrt(36))
print("Sine of 45 degrees:", math.sin(math.radians(45)))
print("Cosine of 60 degrees:", math.cos(math.radians(60)))
# Constants
print("Value of pi:", math.pi)
print("Value of e:", math.e)

PYTHON OUTPUT:

NUMPY:
import numpy as np
# Creating NumPy arrays
arr1 = np.array([2, 4, 6])
arr2 = np.array([[1, 3, 5], [7, 8, 9]])
# Basic array operations
print("Sum of arrays:", np.add(arr1, arr2))
print("Element-wise multiplication:", np.multiply(arr1, arr2))
# Linear algebra operations
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
print("Matrix multiplication:", np.dot(matrix1, matrix2))
print("Determinant of matrix1:", np.linalg.det(matrix1))

PYTHON OUTPUT:
SCIPY:
import scipy.stats as stats
from scipy.optimize import minimize
from scipy.integrate import quad
import numpy as np
# Statistical operations
data = np.array([1, 3, 5, 7, 9])
print("Mean:", np.mean(data))
print("Standard deviation:", np.std(data))
# Optimization
def objective_function(x):
return x**3 + 5*x + 6
result = minimize(objective_function, x0=0)
print("Optimal value:", result.fun)
# Integration
def integrand(x):
return x**2
result, _ = quad(integrand, 0, 1)
print("Integral of x^2 from 0 to 1:", result)

PYTHON OUTPUT:
IMPLEMENTATION OF PYTHON LIBRARIES FOR ML
Artificial Intelligence IIEE
APPLICATION SUCH AS PANDAS AND MATPLOTLIB
7th Semester Institute of Industrial Electronics Engineering LAB 7

OBJECTIVE:
The objective of this lab task is to demonstrate the practical implementation of essential Python
libraries for machine learning applications, specifically using Pandas and Matplotlib.
Through this task, participants should gain hands-on experience in:
• Loading a dataset into a Pandas DataFrame.
• Conducting data cleaning and exploration, including identifying and handling missing
values.
• Utilizing Pandas for data manipulation, such as converting date columns to datetime format
and creating new columns based on existing data.
• Performing basic data analysis, in this case, calculating and visualizing total sales trends
over different months using Matplotlib.
LAB DESCRIPTION:
Step 1: Import Required Libraries:

import pandas as pd
import matplotlib.pyplot as plt
Step 2: Load The Dataset

# Assuming the dataset is in the same directory as your Python script or Jupyter notebook or VS
Code or Pycharm
file_path = 'sales_data.csv'
sales_data = pd.read_csv(file_path)
# Display the first few rows of the dataset to get an overview
print(sales_data.head())
Step 3: Data Cleaning And Exploration

# Check for missing values


print(sales_data.isnull().sum())
# Summary sta�s�cs
print(sales_data.describe())
# Unique values in the 'Product' column
print(sales_data['Product'].unique())
Step 4: Data Manipulation

# Convert 'Date' column to date�me format


sales_data['Date'] = pd.to_date�me(sales_data['Date'])
# Extract month and year from the 'Date' column
sales_data['Month'] = sales_data['Date'].dt.month
sales_data['Year'] = sales_data['Date'].dt.year
# Create a new column for total sales (Quan�ty * Revenue)
sales_data['TotalSales'] = sales_data['Quan�ty'] * sales_data['Revenue']
Step 5: Data Analysis

# Total sales per month


monthly_sales = sales_data.groupby(['Year', 'Month'])['TotalSales'].sum()
# Plo�ng total sales per month
plt.figure(figsize=(10, 6))
monthly_sales.plot(kind='bar', color='skyblue')
plt.�tle('Total Sales per Month')
plt.xlabel('Year-Month')
plt.ylabel('Total Sales ($)')
plt.show()
Step 6: Conclusion

This example successfully loads the sales dataset, performs basic data cleaning and explora�on,
manipulates the data to extract useful informa�on (like total sales), and creates a bar chart that
displays the total sales for each month.
• The dataset contains no missing values. The numerical columns for quan�ty and revenue
are detailed in the summary sta�s�cs.
• The various values in the 'Product' column indicate the various product types.
• There are now addi�onal columns showing the month, year, and total sales.
• The bar chart effec�vely illustrates the overall sales trends over the course of several
months.
PYTHON CODE:
LOAD THE DATASET:

import pandas as pd
import matplotlib.pyplot as plt
# Assuming the dataset is in the same directory as your
Python script or Jupyter notebook or VS Code or Pycharm
file_path = 'sales_data.csv'
sales_data = pd.read_csv(file_path)
# Display the first few rows of the dataset to get an
overview
print(sales_data.head())
OUTPUT:

DATA CLEANING AND EXPLORATION:


import pandas as pd
import matplotlib.pyplot as plt
# Assuming the dataset is in the same directory as your
Python script or Jupyter notebook or VS Code or Pycharm
file_path = 'sales_data.csv'
sales_data = pd.read_csv(file_path)
# Display the first few rows of the dataset to get an
overview
print(sales_data.head())
# Check for missing values
print(sales_data.isnull().sum())
# Summary statistics
print(sales_data.describe())
# Unique values in the 'Product' column
print(sales_data['Product'].unique())
OUTPUT:
DATA MANIPULATION:
import pandas as pd
import matplotlib.pyplot as plt
# Assuming the dataset is in the same directory as your
Python script or Jupyter notebook or VS Code or Pycharm
file_path = 'sales_data.csv'
sales_data = pd.read_csv(file_path)
# Display the first few rows of the dataset to get an
overview
print(sales_data.head())
# Check for missing values
print(sales_data.isnull().sum())
# Summary statistics
print(sales_data.describe())
# Unique values in the 'Product' column
print(sales_data['Product'].unique())
# Convert 'Date' column to datetime format with
dayfirst=True
sales_data['Date'] = pd.to_datetime(sales_data['Date'],
dayfirst=True)
# Extract month and year from the 'Date' column
sales_data['Month'] = sales_data['Date'].dt.month
sales_data['Year'] = sales_data['Date'].dt.year
# Create a new column for total sales (Quantity * Revenue)
sales_data['TotalSales'] = sales_data['Quantity'] *
sales_data['Revenue']
OUTPUT:
DATA ANALYSIS:
import pandas as pd
import matplotlib.pyplot as plt
# Assuming the dataset is in the same directory as your Python
script or Jupyter notebook or VS Code or Pycharm
file_path = 'sales_data.csv'
sales_data = pd.read_csv(file_path)
# Display the first few rows of the dataset to get an overview
print(sales_data.head())
# Check for missing values
print(sales_data.isnull().sum())
# Summary statistics
print(sales_data.describe())
# Unique values in the 'Product' column
print(sales_data['Product'].unique())
# Convert 'Date' column to datetime format with dayfirst=True
sales_data['Date'] = pd.to_datetime(sales_data['Date'],
dayfirst=True)
# Extract month and year from the 'Date' column
sales_data['Month'] = sales_data['Date'].dt.month
sales_data['Year'] = sales_data['Date'].dt.year
# Create a new column for total sales (Quantity * Revenue)
sales_data['TotalSales'] = sales_data['Quantity'] *
sales_data['Revenue']
# Total sales per month
monthly_sales = sales_data.groupby(['Year',
'Month'])['TotalSales'].sum()
# Plotting total sales per month
plt.figure(figsize=(10, 6))
monthly_sales.plot(kind='bar', color='skyblue')
plt.title('Total Sales per Month')
plt.xlabel('Year-Month')
plt.ylabel('Total Sales ($)')
plt.show()

OUTPUT
Artificial Intelligence Creation and Loading different datasets in Python. IIEE
7th Semester Institute of Industrial Electronics Engineering LAB 8

OBJECTIVE:
The objec�ve of this AI Design Lab is to gain hands-on experience in crea�ng and loading different
types of datasets in Python. Datasets serve as the founda�on for various data-driven tasks,
including machine learning, data analysis, and visualiza�on. This lab will guide you through the
process of genera�ng synthe�c datasets and loading exis�ng datasets from different sources.

DESCRIPTION:
This lab focuses on the prac�cal aspects of dataset crea�on and loading using Python. It will
cover both synthe�c data genera�on and impor�ng datasets from various formats, such as CSV,
JSON, and built-in libraries. The goal is to provide you with a versa�le set of skills for working
with different types of data in Python.

Working Steps:
1. Synthetic Dataset Generation:
• Use libraries like `numpy` and `pandas` to create synthe�c datasets with random
or structured data.
• Generate datasets with varying sizes, features, and data types.
2. CSV Dataset Creation:
• Create a dataset manually using a spreadsheet tool (e.g., Microso� Excel or
Google Sheets).
• Save the dataset as a CSV (Comma-Separated Values) file.
3. Loading CSV Dataset in Python:
• Use the `pandas` library to read and load a CSV dataset into a DataFrame.
• Explore the loaded dataset using `head()`, `info()`, and other DataFrame methods.
4. JSON Dataset Creation:
• Manually create a dataset in JSON (JavaScript Object Nota�on) format.
• Save the dataset as a JSON file.
5. Loading JSON Dataset in Python:
• U�lize the `pandas` library to read and load a JSON dataset into a DataFrame.
• Examine the structure of the loaded data.
6. Built-in Dataset Loading:
• Explore built-in datasets available in Python libraries like `scikit-learn` or `seaborn`.
• Load a built-in dataset and examine its features.
7. SQL Dataset Creation:
• Create a simple dataset and store it in a SQL database using SQLite or another
database management system.
8. Loading SQL Dataset in Python:
• Use the `pandas` library to connect to the SQL database and load a dataset into a
DataFrame.
• Execute SQL queries to explore the loaded data.
9. Image Dataset Loading:
• Explore loading image datasets using libraries like `PIL` or `OpenCV`.
• Load individual images and analyze their proper�es.
10. Time Series Dataset Creation:
• Generate a synthe�c �me series dataset with �mestamps using `pandas`.
• Save the �me series data as a CSV file.
11. Loading Time Series Dataset in Python:
Load the �me series dataset into a `pandas` DataFrame.
• Explore the temporal aspects of the loaded data.
PYTHON CODE:
import numpy as np
import pandas as pd

csv_file_path = 'sales_data.csv' # Replace with your CSV


file path
loaded_csv_df = pd.read_csv(csv_file_path)

print("Loaded CSV sales_data.csv:")


print(loaded_csv_df.head())

DATA SETT:
Save in the same location where project is created: C:\Users\mirxa\AI LABS\AI LAB 8
PYTHON OUTPUT:
To compute Mean, Median, Mode, Variance and Standard
Artificial Intelligence IIEE
Deviation using Datasets
7th Semester Institute of Industrial Electronics Engineering LAB 9

OBJECTIVE:
The objec�ve of this lab is to create a Python program that computes sta�s�cal measures,
including Mean, Median, Mode, Variance, and Standard Devia�on, using a given dataset. This
lab aims to provide hands-on experience in data analysis and sta�s�cal computa�on using
Python.

DESCRIPTION:
Sta�s�cal measures are fundamental tools in data analysis and provide insights into the central
tendencies and variability of a dataset. In this lab, you will develop a Python program that takes
a dataset as input and calculates Mean, Median, Mode, Variance, and Standard Devia�on. The
program will leverage the `sta�s�cs` module for mean, median, and mode, and the `numpy`
library for variance and standard devia�on calcula�ons.

Working Steps:
1. Understanding Statistical Measures:
• Familiarize yourself with the concepts of Mean, Median, Mode, Variance, and
Standard Devia�on.
• Understand their significance in data analysis.
2. Dataset Selection:
• Choose or create a dataset for analysis. The dataset can be a list of numeric values.
3. Implementation of Mean, Median, Mode:
• Write func�ons or code snippets to calculate Mean, Median, and Mode using the
`sta�s�cs` module.
4. Handling Mode Exceptions:
• Implement error handling to deal with cases where there is no unique mode in the
dataset.
5. Implementation of Variance and Standard Deviation:
• Use the `numpy` library to calculate Variance and Standard Devia�on for the given
dataset.
6. Input Validation:
• Implement input valida�on to ensure the provided dataset is valid (e.g., non-empty list
of numeric values).
7. Program Testing:
• Test the program with different datasets to ensure accurate and reliable results.
UNDERSTANDING STATISTICAL MEASURES:
Before we start coding, it's essential to have a basic understanding of each statistical
measure:
• Mean: The average of all numbers in the dataset.
• Median: The middle value when the numbers are sorted in ascending or
descending order. If there's an even number of observations, the median is the
average of the two middle numbers.
• Mode: The value that appears most frequently in the dataset. There can be more
than one mode if two or more values appear with the same highest frequency.
• Variance: A measure of how much the numbers in the dataset vary from the
mean.
• Standard Deviation: The square root of the variance, representing the
dispersion of the dataset relative to its mean.
PYTHON CODE:
import statistics
import numpy as np
# Dataset validation
def validate_dataset(dataset):
if not dataset or not all(isinstance(i, (int, float))
for i in dataset):
raise ValueError("Dataset must be a non-empty list
of numeric values.")
# Calculation of Mean, Median, Mode
def calculate_mean_median_mode(dataset):
mean = statistics.mean(dataset)
median = statistics.median(dataset)
try:
mode = statistics.mode(dataset)
except statistics.StatisticsError:
mode = 'No unique mode found'
return mean, median, mode
# Calculation of Variance and Standard Deviation
def calculate_variance_std(dataset):
variance = np.var(dataset, ddof=1) # ddof=1 for sample
variance
std_deviation = np.sqrt(variance)
return variance, std_deviation
# Main function to run the program
def main():
# Example dataset
dataset = [12, 14, 16, 18, 20, 32, 34, 36, 38, 40]
try:
validate_dataset(dataset)
mean, median, mode =
calculate_mean_median_mode(dataset)
variance, std_deviation =
calculate_variance_std(dataset)
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
print("Variance:", variance)
print("Standard Deviation:", std_deviation)

except ValueError as e:
print(e)
if __name__ == "__main__":
main()
DATA SETT:
dataset = [12, 14, 16, 18, 20, 32, 34, 36, 38, 40]

PYTHON OUTPUT:
Artificial Intelligence Implementation of Find S Algorithm IIEE
th
7 Semester Institute of Industrial Electronics Engineering LAB 10

OBJECTIVE:
The objec�ve of this lab is to implement the Find-S algorithm, a concept learning algorithm used
in machine learning. The Find-S algorithm is par�cularly useful for learning hypotheses from a
set of posi�ve training examples. This lab aims to provide hands-on experience in understanding
and implemen�ng the basic concepts of the Find-S algorithm.

DESCRIPTION:
The Find-S algorithm is a basic algorithm in machine learning that seeks to find the most specific
hypothesis that is consistent with a given set of posi�ve training examples. The hypothesis is
represented as a conjunc�on of atribute values. In this lab, you will implement the Find-S
algorithm and apply it to a simple dataset.

Working Steps:
1. Understanding Find-S Algorithm:
• Familiarize yourself with the Find-S algorithm and its applica�on in concept learning.
2. Dataset Selection:
• Choose a simple dataset for which you want to learn a hypothesis.
• Define posi�ve training examples for the selected dataset.
3. Hypothesis Representation:
• Decide on a representa�on for the hypothesis. The hypothesis is typically represented
as a conjunc�on of atribute values.
4. Implementation of Find-S Algorithm:
• Write a Python func�on to implement the Find-S algorithm.
• The algorithm should take posi�ve training examples as input and output the most
specific hypothesis consistent with the examples.
5. Testing the Algorithm:
• Test the implemented Find-S algorithm on the chosen dataset.
• Ensure that the generated hypothesis correctly classifies the posi�ve training examples.
6. Visualization (Optional):
• Op�onally, visualize the dataset and the learned hypothesis to gain a beter
understanding of the algorithm's performance.
7. Handling Noise (Optional):
• Consider how the algorithm might be adapted or extended to handle noise or conflic�ng
examples in the dataset.
UNDERSTANDING THE FIND-S ALGORITHM:
The Find-S algorithm is one of the simplest concept learning algorithms. It starts with
the most specific hypothesis possible (in a hypothesis space that matches no
examples) and generalizes this hypothesis each time it fails to cover a positive
example. Negative examples are ignored during this process. The final hypothesis is
the most specific one that fits all the positive examples
PYTHON CODE:
def initialize_hypothesis(attributes):
hypothesis = [None for _ in attributes] # Use None to
represent unassigned values
return hypothesis
def update_hypothesis(hypothesis, example):
for i in range(len(hypothesis)):
if hypothesis[i] is None: # If the hypothesis
attribute is unassigned, adopt the example's value
hypothesis[i] = example[i]
elif example[i] != hypothesis[i]: # If the current
example differs, generalize the attribute
hypothesis[i] = '?'
return hypothesis
def attribute_to_words(attribute):
# Add mappings for attribute values to their
corresponding words (including 'Unknown' for unassigned)
attribute_map = {'Sunny': 'Weather: Sunny',
'Warm': 'Temperature: Warm',
'Normal,High': ['Humidity: Normal',
'Humidity:High'],
'Strong': 'Wind: Strong',
'Same': 'Change: Same',
'Change': 'Change: Change',
'?': '?'}
# Use get with a default value (replace 'Unknown
Attribute Value' with your preference)
return attribute_map.get(attribute)
def hypothesis_to_words(hypothesis):
return [attribute_to_words(attr) for attr in
hypothesis]
def find_s_algorithm(positive_examples):
attributes = positive_examples[0][0:-1] # Exclude the
class label
hypothesis = initialize_hypothesis(attributes)
for example in positive_examples:
if example[-1] == '1': # Ensure we only consider
positive examples
hypothesis = update_hypothesis(hypothesis,
example[0:-1]) # Exclude the class label from the example
return hypothesis_to_words(hypothesis)
# Test function (unmodified)
def test_find_s_algorithm():
positive_examples = [
['Sunny', 'Warm', 'Normal', 'Strong', 'Same', '1'],
['Sunny', 'Warm', 'High', 'Strong', 'Same', '1'],
['Sunny', 'Warm', 'High', 'Weak', 'Change', '1']
]
hypothesis = find_s_algorithm(positive_examples)
print("\nFind-S Algorithm Results:")
print("Final Hypothesis:", hypothesis)

if __name__ == "__main__":
test_find_s_algorithm()

DATA SETT:
positive_examples = [
['Sunny', 'Warm', 'Normal', 'Strong', 'Same', '1'],
['Sunny', 'Warm', 'High', 'Strong', 'Same', '1'],
['Sunny', 'Warm', 'High', 'Weak', 'Change', '1']
]

PYTHON OUTPUT:

This output means that according to the Find-S algorithm and based on the positive
examples provided:
• The “Weather” should be “Sunny”.
• The “Temperature” should be “Warm”.
• The “Humidity” can be anything (“?” signi�ies that any value is acceptable based
on the given positive examples).
• The “Wind” can also be anything (“?” signi�ies that any value is acceptable based
on the given positive examples).
Artificial Intelligence Implementation of Candidate elimination Algorithm IIEE
7th Semester Institute of Industrial Electronics Engineering LAB 11

OBJECTIVE:
The objec�ve of this lab is to implement the Candidate Elimina�on algorithm, a concept learning
algorithm used in machine learning. The Candidate Elimina�on algorithm is designed to handle both
posi�ve and nega�ve training examples and refine the hypothesis space based on the observed
examples. This lab aims to provide hands-on experience in understanding and implemen�ng the basic
concepts of the Candidate Elimina�on algorithm.

DESCRIPTION:
The Candidate Elimina�on algorithm maintains a version space, which represents the set of all
hypotheses that are consistent with the observed examples. It updates the version space as new
examples are encountered, elimina�ng hypotheses that are inconsistent with the data. In this lab, you
will implement the Candidate Elimina�on algorithm and apply it to a simple dataset with both posi�ve
and nega�ve examples.

WORKING STEPS:
1. Understanding Candidate Elimination Algorithm:
• Familiarize yourself with the Candidate Elimina�on algorithm and its applica�on in concept
learning.
• Understand how the algorithm maintains a version space and updates it based on observed
examples.
2. Dataset Selection:
• Choose a simple dataset for which you want to learn a hypothesis.
• Define posi�ve and nega�ve training examples for the selected dataset.
3. Hypothesis Representation:
• Decide on a representa�on for the hypothesis. The hypothesis is typically represented as a
conjunc�on of atribute values.
4. Implementation of Candidate Elimination Algorithm:
• Write a Python func�on to implement the Candidate Elimina�on algorithm.
• The algorithm should take posi�ve and nega�ve training examples as input and
maintain/update the version space.
5. Testing the Algorithm:
• Test the implemented Candidate Elimina�on algorithm on the chosen dataset.
• Ensure that the version space correctly represents hypotheses consistent with the observed
examples.
6. 6. Visualization (Optional):
• Op�onally, visualize the dataset, the version space, and the learned hypothesis to gain a beter
understanding of the algorithm's performance.
7. Handling Noise (Optional):
• Consider how the algorithm might be adapted or extended to handle noise or conflic�ng
examples in the dataset.
Understanding The Candidate Elimination Algorithm:
The Candidate Elimination algorithm works by maintaining two sets of hypotheses:
• General boundary (G): The set of the most general hypotheses that are
consistent with the positive examples.
• Specific boundary (S): The set of the most speci�ic hypotheses that are
consistent with the positive examples.
PYTHON CODE:
def initialize_hypotheses(attributes):
specific_hypothesis = ['0'] * len(attributes) # All
attributes unknown ('0') for specific hypothesis
general_hypothesis = ['?'] * len(attributes) # All
attributes unknown ('?') for general hypothesis
return specific_hypothesis, general_hypothesis

def update_hypotheses(specific_hypothesis,
general_hypothesis, example):
label = example[-1] # Extract the class label
for i in range(len(specific_hypothesis)):
if label == '1': # Update for positive examples
only
specific_hypothesis[i] = example[i]
general_hypothesis[i] = '?' if
specific_hypothesis[i] != general_hypothesis[i] else
general_hypothesis[i]
elif label == '0': # Update for negative examples
general_hypothesis[i] = specific_hypothesis[i]
if specific_hypothesis[i] != general_hypothesis[i] else
general_hypothesis[i]

return specific_hypothesis, general_hypothesis

def candidate_elimination_algorithm(training_examples):
attributes = training_examples[0][0:-1] # Extract
attribute names
specific_hypothesis, general_hypothesis =
initialize_hypotheses(attributes)

for example in training_examples:


specific_hypothesis, general_hypothesis =
update_hypotheses(specific_hypothesis, general_hypothesis,
example)

return specific_hypothesis, general_hypothesis

def test_candidate_elimination_algorithm():
# Training examples
training_examples = [
['Sunny', 'Warm', 'Normal', 'Strong', 'Warm',
'Same', '1'],
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same',
'1'],
['Rainy', 'Cold', 'High', 'Weak', 'Warm', 'Change',
'0'],
['Sunny', 'Cold', 'High', 'Strong', 'Cool',
'Change', '1']
]
# Run Candidate Elimination algorithm
specific_hypothesis, general_hypothesis =
candidate_elimination_algorithm(training_examples)
# Display results
print("\nCandidate Elimination Algorithm Results:")
print("Specific Hypothesis:", specific_hypothesis)
print("General Hypothesis:", general_hypothesis)

if __name__ == "__main__":
test_candidate_elimination_algorithm()

PYTHON OUTPUT:
Artificial Intelligence To implement simple Linear Regression and Plot the graph IIEE
th
7 Semester Institute of Industrial Electronics Engineering LAB 12

OBJECTIVE:
The objec�ve of this lab is to implement simple linear regression in Python and visualize the linear
regression line on a scater plot. Simple linear regression is a method to model the rela�onship between
a single independent variable and a dependent variable. This lab aims to provide hands-on experience
in understanding and implemen�ng basic linear regression.

DESCRIPTION:
Simple linear regression involves fi�ng a linear model to observed data. The model assumes a linear
rela�onship between the independent variable (X) and the dependent variable (Y). The objec�ve is to
find the best-fi�ng line (regression line) that minimizes the sum of squared differences between the
observed and predicted values. In this lab, you will implement simple linear regression and visualize the
regression line on a scater plot.

Working Steps:
1. Understanding Simple Linear Regression:
• Familiarize yourself with the concept of simple linear regression and its mathema�cal formula�on.
2. Dataset Selection:
• Choose a dataset with two variables: an independent variable (X) and a dependent variable (Y).
• Ensure that the dataset exhibits a trend that can be approximated by a linear model.
3. Data Exploration:
• Explore the dataset to understand the rela�onship between the independent and dependent
variables.
• Plot a scater plot to visualize the data points.
4. Implementation of Simple Linear Regression:
• Write a Python program to implement simple linear regression.
• U�lize mathema�cal formulas to calculate the slope and intercept of the regression line.
5. Training the Model:
• Split the dataset into training and tes�ng sets.
• Train the simple linear regression model on the training set.
6. Prediction:
• Use the trained model to make predic�ons on the tes�ng set.
7. Plotting the Regression Line:
• Plot the scater plot of the dataset.
• Plot the regression line on the same graph to visualize the linear fit.
8. Evaluation:
• Evaluate the performance of the model by analyzing the residuals (differences between observed
and predicted values).
UNDERSTANDING SIMPLE LINEAR REGRESSION
Simple linear regression models the relationship between two variables by �itting a
linear equation to observed data. The equation of a line is:
Y=b0+b1X
where:
• Y is the dependent variable,
• X is the independent variable,
• b0 is the intercept, and
• b1 is the slope of the line.
The goal is to �ind the values of b0 and b1 that best �it the data.

PYTHON CODE:
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# For illustration purposes, let's generate a simple


dataset
np.random.seed(42)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)

plt.scatter(X, y, color='blue')
plt.title('Scatter Plot of the Dataset')
plt.xlabel('Independent Variable (X)')
plt.ylabel('Dependent Variable (y)')
plt.show()

X_train, X_test, y_train, y_test = train_test_split(X, y,


test_size=0.2, random_state=42)

linear_reg_model = LinearRegression()
linear_reg_model.fit(X_train, y_train)

y_pred = linear_reg_model.predict(X_test)

plt.scatter(X_test, y_test, color='blue', label='Actual


Data')
plt.plot(X_test, y_pred, color='red', linewidth=3,
label='Linear Regression Line')
plt.title('Simple Linear Regression')
plt.xlabel('Independent Variable (X)')
plt.ylabel('Dependent Variable (y)')
plt.legend()
plt.show()

PYTHON OUTPUT:
Artificial Intelligence To Implement Basic Image Processing Application IIEE
7th Semester Institute of Industrial Electronics Engineering LAB 13

OBJECTIVE:
The objec�ve of this lab is to introduce undergraduate students to image processing techniques
using Python and OpenCV. Students will learn to perform tasks such as image loading, resizing,
and applying basic filters. By the end of the lab, students should be able to understand the
fundamentals of image processing and build a simple image processing applica�on.

DESCRIPTION:
Image processing is a crucial aspect of computer vision. In this lab, students will develop an image
processing applica�on that allows them to load images, resize them, and apply basic filters such
as grayscale conversion and edge detec�on.

STEPS:
1. Introduction to Image Processing:
• Brief overview of image processing and its applica�ons.
• Introduc�on to the OpenCV library.
2. Setting Up the Environment:
• Install OpenCV library.
• Provide sample images for tes�ng.
3. Image Loading and Display:
• Load an image using OpenCV.
• Display the original image.
4. Resizing Images:
• Learn to resize images using OpenCV.
• Discuss the importance of image resizing in various applica�ons.
5. Grayscale Conversion:
• Implement grayscale conversion of the loaded image.
• Discuss the advantages of working with grayscale images.
6. Edge Detection:
• Apply edge detec�on filters to iden�fy prominent edges in the image.
• Discuss the significance of edge detec�on in image analysis.
7. Interactive Application:
• Create a simple interface allowing users to load an image, resize it, convert it to
grayscale, and apply edge detec�on.
8. Discussion and Analysis:
• Discuss the impact of various image processing techniques on the visual appearance
of the image.
• Explore poten�al real-world applica�ons of the developed image processing skills.
PYTHON CODE:
import cv2
import matplotlib.pyplot as plt

# Function to load and display an image


def load_and_display_image(image_path):
img = cv2.imread('image.jpg')
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.title("Original Image")
plt.axis('off')
plt.show()

# Function to resize an image


def resize_image(image_path, scale_percent):
img = cv2.imread('image.jpg')
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
resized_img = cv2.resize(img, (width, height))
plt.imshow(resized_img)
plt.title("Resized Image")
plt.axis('off')
plt.show()

# Function to convert an image to grayscale


def convert_to_grayscale(image_path):
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap='gray')
plt.title("Grayscale Image")
plt.axis('off')
plt.show()

# Function to apply edge detection


def edge_detection(image_path):
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
edges = cv2.Canny(img, 100, 200)
plt.imshow(edges, cmap='gray')
plt.title("Edge Detection")
plt.axis('off')
plt.show()

# Example usage with raw string


image_path = r'C:\Users\mirxa\AI LABS\AI LAB 13' # Full
path with extension
load_and_display_image(image_path)
resize_image(image_path,50)
convert_to_grayscale(image_path)
edge_detection(image_path)
OUTPUT:

You might also like