E & Ai Lab Manual
E & Ai Lab Manual
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
V SEMESTER
NAME
REG NO
BATCH
…
TITLE
CMS COLLEGE OF ENGINEERING AND TECHNOLOGY
COIMBATORE – 641032
Mr. / Ms.
PLACE: COIMBATORE.
DATE:
Held on:
def identify_unauthorized_entry(official_id):
if official_id in officials_database:
return officials_database[official_id]["authorized"]
return False
def identify_official_rank(official_id):
if official_id in officials_database:
return officials_database[official_id]["role"]
return None
Output:
Enter your official ID to check entry status: official1
Access granted.
Your rank: manager
HEALTH CARE:
Algorithm:
Define the Doctor class with attributes: name and specialization.
Define the Room class with attributes: room_number, capacity, and a list of patients.
Define the Pharmacy class to manage medicine stock with a dictionary of medicine_stock.
Implement the allocate_room method in the Hospital class:
a. Accept the room_type as input.
b. Iterate through available rooms and assign the patient to the first room with capacity.
c. Return the allocated room number or None if no rooms are available.
Implement the get_available_doctors method in the Hospital class:
a. Accept specialization (optional) as input.
b. Retrieve the list of doctors with a matching specialization (if provided) or return all
doctors.
c. Return the list of available doctor names.
Create an instance of the Hospital class and simulate the following scenarios:
a. Emergency situation:
Call allocate_room for emergency room allocation.
b. Ambulance arrangement:
Simulate ambulance arrangement (boolean flag).
c. Check available doctors by specialization:
Call get_available_doctors with a specific specialization if needed.
d. Check pharmacy medicine stock:
Use the Pharmacy class to check the availability of a medicine in stock.
e. Update pharmacy medicine stock:
Use the Pharmacy class to update the medicine stock.
Display appropriate output messages for each scenario.
Program:
class Doctor:
def init (self, name, specialization):
self.name = name
self.specialization = specialization
class Room:
def init (self, room_number, capacity):
self.room_number = room_number
self.capacity = capacity
self.patients = []
class Pharmacy:
def init (self):
self.medicine_stock = {"paracetamol": 100, "ibuprofen": 50, "aspirin": 75}
def check_stock(self, medicine_name):
return self.medicine_stock.get(medicine_name, 0)
def update_stock(self, medicine_name, quantity):
if medicine_name in self.medicine_stock:
self.medicine_stock[medicine_name] += quantity
else:
self.medicine_stock[medicine_name] = quantity
class Hospital:
def init (self):
self.rooms = [Room(101, 2), Room(102, 1), Room(103, 3)]
self.doctors = [
Doctor("Dr. Smith", "Cardiologist"),
Doctor("Dr. Johnson", "Pediatrician"),
Doctor("Dr. Lee", "Orthopedic"),
]
self.pharmacy = Pharmacy()
def allocate_room(self, room_type):
for room in self.rooms:
if len(room.patients) < room.capacity:
room.patients.append(room_type)
return room.room_number
return None
def get_available_doctors(self, specialization=None):
available_doctors = []
for doctor in self.doctors:
if specialization is None or doctor.specialization == specialization:
available_doctors.append(doctor.name)
return available_doctors
if ambulance_arranged:
print("Ambulance arranged.")
else:
print("Ambulance not available.")
Output:
Emergency room allocated: 101
Ambulance arranged.
Available Cardiologist doctors:
Dr. Smith
Medicine stock updated.
AUTONOMOUS VEHICLE:
Algorithm:
Define the AutonomousVehicle class with attributes: route, current_location,
battery_capacity, and battery_level.
Implement the plan_route(destination) method in the AutonomousVehicle class:
a. Accept the destination as input.
b. Replace this with a proper route planning algorithm to create a route from the current
location to the destination.
c. Store the planned route in the route attribute.
Implement the drive() method in the AutonomousVehicle class:
a. Check if a route is planned.
b. Simulate driving to each location in the planned route (from current location to the
destination).
c. Update the current_location after reaching each location.
Implement the sense_abnormal_situation() method in the AutonomousVehicle class:
a. Replace this with actual sensor data processing and detection of abnormal situations.
b. Return True if an abnormal situation is detected, otherwise False.
Implement the monitor_battery_level() method in the AutonomousVehicle class:
a. Display the current battery_level and the total battery_capacity.
Create an instance of the AutonomousVehicle class with a given battery capacity.
Set the current_location to the starting point and plan a route to the destination using the
plan_route(destination) method.
Implement the main function:
Drive the vehicle to each location in the route using the drive() method.
Simulate sensing of an abnormal situation using the sense_abnormal_situation() method.
If an abnormal situation is detected:
a. Display a message indicating the situation is detected.
b. Implement actions to handle the abnormal situation (not implemented in the simplified
code).
Monitor the battery level after the trip using the monitor_battery_level() method.
Program:
class AutonomousVehicle:
def init (self, battery_capacity):
self.route = [] # Stores the planned route
self.current_location = None
self.battery_capacity = battery_capacity
self.battery_level = battery_capacity
def sense_abnormal_situation(self):
# Replace this with actual sensor data processing and detection of abnormal situations
return False
def monitor_battery_level(self):
print(f"Battery level: {self.battery_level}/{self.battery_capacity}")
if abnormal_situation_detected:
print("Abnormal situation detected. Taking necessary action.")
# Implement actions to handle abnormal situations (e.g., emergency braking, rerouting,
etc.)
Result:
Thus the program to implement the case study of defence, health care and autonomous
vehicles has been executed and verified successfully.
Ex.no:2 Exploratory data analysis on a 2 variable linear regression model
DATE:
Aim:
The aim of this program is to perform simple linear regression on the provided
dataset and
visualize the relationship between the variables 'X' and 'Y'. It includes creating a scatter plot to
visualize the data points and fitting a linear regression model to find the best-fitting line that
represents the relationship between 'X' and 'Y'.
Algorithm:
1. Import the necessary libraries: pandas, matplotlib, and
LinearRegression from sklearn.linear_model.
2. Prepare sample data (you can replace this with your dataset).
3. Create a DataFrame using pandas to store the sample data.
4. Visualize the relationship between 'X' and 'Y' using a scatter plot with matplotlib.
5. Fit a linear regression model using the LinearRegression class from sklearn.linear_model.
6. Obtain the coefficients (slope) and the intercept of the linear regression model.
7. Predict the 'Y' values using the fitted model based on the 'X' values.
8. Plot the regression line on top of the scatter plot to visualize the linear relationship.
Program:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import
LinearRegression data = {
'x': [160, 100, 200, 140,
160,150,174,189,185,195,149,189,147,154,174,169,195,159,192,155,191],
#x represents the height
'y': [65, 40, 80, 95, 15,174,189,185,149,189,147,154,174,169,195,159,192,155,191,200,120]
#y represents the weight
}
# Create a DataFrame
df = pd.DataFrame(data)
Inference
Overall, this program aims to help you understand the relationship between the two
variables 'X' and 'Y' and how well they can be represented using a linear regression model.
Result:
Thus the given python program on exploratory data analysis on a 2 variable linear
regression model has be executed successfully.
Ex.no:3 Experiment the regression model without a bias and with bias
DATE:
The aim of this regression experiment is to compare the performance of a linear regression
model with a bias term (intercept) and without a bias term (forcing intercept to zero). We will
generate synthetic data with a known linear relationship and train two linear regression
models—one with bias and one without—to evaluate their accuracy and understand the impact
of including a bias term in the model.
CODE:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import
LinearRegression from sklearn.metrics import
mean_squared_error
# Make predictions
y_pred_with_bias = model_with_bias.predict(X)
y_pred_without_bias =
model_without_bias.predict(X)q
# Calculate mean squared error
mse_with_bias = mean_squared_error(y,
y_pred_with_bias) mse_without_bias =
mean_squared_error(y, y_pred_without_bias)
Coefficients: 3.4145240061684874
RESULT:
Thus the regression experiment with and without bias has been executed successfully
Ex. No. 04 Classification of a dataset from the UCI repository using a perceptron with and
DATE: without bias
Aim:
To classify the data set from an UCI repository for a perceptron network with and
without bias using python.
With BIAS:
Algorithm:
1. Initialize the weights and bias to random values.
2. Iterate over the training data:
* For each data point, calculate the dot product of the weights and the features.
* Add the bias to the dot product.
* If the result is greater than or equal to 0, then the label is 1. Otherwise, the label is -
1.
* If the predicted label is different from the actual label, then update the weights and
bias.
3. Repeat step 2 until the model converges.
4. Use the trained model to predict the labels of new data points.
Perceptron Architecture:
Code:
import numpy as np
Args:
x: The data
point. w: The
weights. b:
The bias.
Returns:
The predicted table
"""
y = np.dot(x, w)
+ b if y >= 0:
return
1 else:
return -1
def train_perceptron(x, y, w, b,
epochs): """
Trains the perceptron model.
Args:
x: The training
data. y: The
training labels. w:
The weights.
b: The bias.
epochs: The number of epochs to train for.
Returns:
The trained weights and
bias. """
for epoch in range(epochs):
for i, (x_i, y_i) in enumerate(zip(x,
y)): y_pred = perceptron(x_i, w,
b)
if y_pred != y_i:
w += x_i *
y_i b += y_i
return w, b
def main():
"""
The main
function. """
# Load the data
set. x, y =
load_data()
def load_data():
"""
Loads the data set from the UCI repository.
Returns:
The training data and
labels. """
# Get the data set URL.
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
return x, y
Sample Output:
Weights: [ 1.63357258 -1.45158675 1.77910474]
Bias: -1.04949195
Without BIAS:
Algorithm:
1. Initialize the weights to random values.
2. Iterate over the training data:
* For each data point, calculate the dot product of the weights and the features.
* If the result is greater than or equal to 0, then the label is 1. Otherwise, the label is -
1.
* If the predicted label is different from the actual label, then update the weights.
3. Repeat step 2 until the model converges.
4. Use the trained model to predict the labels of new data points.
Perceptron Architecture:
Code:
import numpy as
np def
perceptron(x, w):
"""
Performs perceptron classification on a single data point.
Args:
x: The data
point. w: The
weights.
Returns:
The predicted
label. """
y = np.dot(x,
w) if y >= 0:
return
1 else:
return -1
def train_perceptron(x, y, w,
epochs): """
Trains the perceptron model.
Args:
x: The training
data. y: The
training labels. w:
The weights.
epochs: The number of epochs to train for.
Returns:
The trained
weights. """
for epoch in
range(epochs): for i,
x_i in enumerate(x):
y_pred =
perceptron(x_i, w) if
y_pred != y[i]:
w += x_i *
y[i] return w
def main():
"""
The main
function. """
# Load the data
set. x, y =
load_data()
# Initialize the
weights. w =
np.zeros(len(x[0]))
# Print the
weights.
print("Weights:",
w)
def load_data():
"""
Loads the data set from the UCI repository.
Returns:
The training data and
labels. """
# Get the data set URL.
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
Sample Output:
Weights: [ 1.63357258 -1.45158675 1.77910474]
Result:
Thus the implement the classification of the data set from an UCI repository for a
perceptron network with and without bias using python is executed and output is
verified.
Ex No: 05 Case study on ontology where ethics is stake
DATE:
Aim:
To write python code ontology in autonomous driving, with ethical considerations
Algorithm:
1. Identify the key concepts and relationships that need to be represented in the ontology.
2. Define the ontology using a standard ontology language, such as OWL or RDF.
3. Develop ethical guidelines for the ontology, such as how to balance the safety of the vehicle
and its passengers with the safety of other road users.
4. Implement the ethical guidelines in the ontology using rules and other constraints.
5. Verify and test the ontology to ensure that it meets the ethical guidelines and that it can be
used to make safe and ethical decisions in complex and uncertain situations
Code:
import rdflib
CollisionAvoidance_CausalRelationship_PassengerSafety =
rdflib.Statement(CollisionAvoidance, CausalRelationship, PassengerSafety)
ontology.add(Car_InstanceOf_Object)
ontology.add(Pedestrian_InstanceOf_Object)
ontology.add(TrafficLight_InstanceOf_Object)
ontology.add(CollisionAvoidance_CausalRelationship_PassengerSafety)
Output:
@prefix ontology: <http://example.org/autonomous-driving-ontology#> .
Result:
Thus the python code ontology in autonomous driving, with ethical considerations has been
executed successfully
Ex No: 06 Identification on optimization in AI affecting ethics
DATE:
Aim:
To write python code for optimizing AI systems in an ethical way
Algorithm:
Code:
import numpy as np
from sklearn.linear_model import LogisticRegression
biased_features = np.argsort(bias_scores)[-10:]
Accuracy: 0.85
Accuracy after removing biased features: 0.83
Result:
Thus the python code for optimizing AI systems in an ethical way has been executed
successfully