0% found this document useful (0 votes)
29 views31 pages

E & Ai Lab Manual

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)
29 views31 pages

E & Ai Lab Manual

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/ 31

C.M.S.

COLLEGE OF ENGINEERING AND


TECHNOLOGY
COIMBATORE-641032

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

CCS345- ETHICS AND AI LABORATORY

V SEMESTER

(As per AU, Chennai Syllabus – R2021)

NAME
REG NO
BATCH

TITLE
CMS COLLEGE OF ENGINEERING AND TECHNOLOGY
COIMBATORE – 641032

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CCS345 - ETHICS AND AI LABORATORY

NAME : CLASS: III BE. CSE

ROLL NO: SEMESTER : V


Certified Bonafide Record of Work done by

Mr. / Ms.

University Register No:______________________________

PLACE: COIMBATORE.

DATE:

Faculty in charge. HOD


Submitted for the University Practical Examination

Held on:

Internal Examiner External Examiner


INDEX

Exp. Date Experiment Name Page No Marks Signature


no
Ex.No.1 Recent case study of ethical initiatives in Healthcare, Autonomous Vehicle
and Defence
DEFENCE:
Algorithm:
Initialize the officials_database with the details of officials, including their roles and
authorized status.
Define the identify_unauthorized_entry(official_id) function:
a. Accept an official_id as input.
b. Check if the official_id exists in the officials_database.
c. If found, retrieve the authorized status for that official.
d. Return True if the official is authorized, otherwise return False.
Define the identify_official_rank(official_id) function:
a. Accept an official_id as input.
b. Check if the official_id exists in the officials_database.
c. If found, retrieve the role for that official.
d. Return the role if available, otherwise return None.
Implement the main code:
a. Prompt the user to enter their official ID.
b. Call identify_unauthorized_entry(official_id) to check if the entry is authorized.
c. If authorized:
Display "Access granted."
Call identify_official_rank(official_id) to get the official's role.
Display the official's rank if available.
d. If unauthorized:
Display "Unauthorized entry detected. Access denied."
Repeat the main code in a loop (using while True) to allow multiple officials to check their
entry status until the program is terminated.
Program:
# Simulated database of officials and their roles (replace this with a real database in a real-
world scenario)
officials_database = {
"official1": {"role": "manager", "authorized": True},
"official2": {"role": "security_guard", "authorized": True},
"official3": {"role": "staff", "authorized": False},
}

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

if name == " main ":


# Simulating the security threat detection process
while True:
official_id = input("Enter your official ID to check entry status: ")
authorized = identify_unauthorized_entry(official_id)
if authorized:
print("Access granted.")
role = identify_official_rank(official_id)
if role:
print(f"Your rank: {role}")
else:
print("Your rank information is not available.")
else:
print("Unauthorized entry detected. Access denied.")

Output:
Enter your official ID to check entry status: official1
Access granted.
Your rank: manager

Enter your official ID to check entry status: official2


Access granted.
Your rank: security_guard
Enter your official ID to check entry status: official3
Unauthorized entry detected. Access denied.
Enter your official ID to check entry status: official4
Unauthorized entry detected. Access denied.

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 name == " main ":


hospital = Hospital()
# Simulating an emergency situation
emergency_room_number = hospital.allocate_room("Emergency")
if emergency_room_number is not None:
print(f"Emergency room allocated: {emergency_room_number}")
else:
print("No available rooms for emergency.")

# Simulating ambulance arrangement


ambulance_arranged = True # Replace this with proper ambulance management logic

if ambulance_arranged:
print("Ambulance arranged.")
else:
print("Ambulance not available.")

# Check available doctors by specialization


specialization_needed = "Cardiologist"
available_doctors = hospital.get_available_doctors(specialization_needed)
if available_doctors:
print(f"Available {specialization_needed} doctors:")
for doctor_name in available_doctors:
print(doctor_name)
else:
print(f"No {specialization_needed} doctors available.")

# Check pharmacy medicine stock


medicine_needed = "ibuprofen"
medicine_quantity = 10
current_stock = hospital.pharmacy.check_stock(medicine_needed)
if current_stock >= medicine_quantity:
print(f"{medicine_needed} available in stock.")
else:
print(f"{medicine_needed} not available in stock. Please reorder.")

# Update pharmacy medicine stock


hospital.pharmacy.update_stock("ibuprofen", 20)
print("Medicine stock updated.")

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 plan_route(self, destination):


# Replace this with a proper route planning algorithm (e.g., A* or Dijkstra's)
# For simplicity, we're directly setting a linear route from the current location to the
destination.
self.route = [self.current_location, destination]
def drive(self):
if not self.route:
print("No route planned. Cannot drive.")
return

# Simulating driving to the destination


for i in range(len(self.route) - 1):
current_location, next_location = self.route[i], self.route[i + 1]
print(f"Driving from {current_location} to {next_location}")
self.current_location = next_location

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 name == " main ":


# Create an instance of the autonomous vehicle with a battery capacity of 100 units
autonomous_vehicle = AutonomousVehicle(battery_capacity=100)

# Set the current location and plan a route to the destination


autonomous_vehicle.current_location = "Location A"
destination = "Location B"
autonomous_vehicle.plan_route(destination)

# Drive the autonomous vehicle


autonomous_vehicle.drive()
# Simulate sensing of an abnormal situation (true or false)
abnormal_situation_detected = autonomous_vehicle.sense_abnormal_situation()

if abnormal_situation_detected:
print("Abnormal situation detected. Taking necessary action.")
# Implement actions to handle abnormal situations (e.g., emergency braking, rerouting,
etc.)

# Monitor battery level after the trip


autonomous_vehicle.monitor_battery_level()
Output:
Driving from Location A to Location B
Driving from Location B to Location C
Abnormal situation detected. Taking necessary action.
Battery level: 80/100

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)

# Scatter plot to visualize the relationship between variables


plt.scatter(df['x'], df['y'])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter plot of X vs Y')
plt.show()

# Fit the linear regression


model model =
LinearRegression()
model.fit(df[['x']], df['y'])

# Coefficients and intercept of the linear regression


model slope = model.coef_[0]
intercept = model.intercept_

print(f'Coefficient (slope): {slope}')


print(f'Intercept: {intercept}')

# Predictions using the linear regression


model predictions = model.predict(df[['x']])

# Plot the regression line


plt.scatter(df['x'], df['y'])
plt.plot(df['x'], predictions,
color='red') plt.xlabel('X')
plt.ylabel('Y')
plt.title('Linear Regression Model')
plt.show()
Output:

Coefficient (slope): 0.8786884068953968


Intercept: -2.958762434288815

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:

Aim of the Experiment:

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

# Generate synthetic data


np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1) # y = 4 + 3X + noise

# Train the model with bias


(intercept) model_with_bias =
LinearRegression()
model_with_bias.fit(X, y)

# Train the model without bias (forcing intercept to zero)


model_without_bias = LinearRegression(fit_intercept=False)
model_without_bias.fit(X, y)

# 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)

# Print the results


print("Model with bias (intercept):")
print("Coefficients:", model_with_bias.coef_[0][0], "Intercept:",
model_with_bias.intercept_[0]) print("Mean Squared Error:", mse_with_bias)

print("\nModel without bias (intercept forced to


zero):") print("Coefficients:",
model_without_bias.coef_[0][0]) print("Mean
Squared Error:", mse_without_bias)

# Plot the data and regression


lines plt.scatter(X, y, color='b',
label='Data')
plt.plot(X, y_pred_with_bias, color='r', label='With
Bias') plt.plot(X, y_pred_without_bias, color='g',
label='Without Bias') plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.title('Linear Regression with and
without Bias') plt.show()
OUTPUT:

Model with bias (intercept):

Coefficients: 3.049126297656954 Intercept: 4.223235163402666

Mean Squared Error: 0.9598794929965263

Model without bias (intercept forced to zero):

Coefficients: 3.4145240061684874

Mean Squared Error: 1.3209592025753712

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

def perceptron(x, w, b):


"""
Performs perceptron classification on a single data point.

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()

# Initialize the weights and


bias. w =
np.zeros(len(x[0]))
b=0

# Train the perceptron model.


w, b = train_perceptron(x, y, w, b, 100)
# Print the weights and bias.
print("Weights:", w)
print("Bias:", b)

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"

# Load the data set into a NumPy


array. data = np.genfromtxt(url,
delimiter=",")

# Split the data into the features and


labels. x = data[:, :-1]
y = data[:, -1]

return x, y

if name == " main ":


main()

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]))

# Train the perceptron model.


w = train_perceptron(x, y, w, 100)

# 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"

# Load the data set into a NumPy


array. data = np.genfromtxt(url,
delimiter=",")

# Split the data into the features and


labels. x = data[:, :-1]
y = data[:, -1]
return x, y

if name == " main ":


main()

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

# Define the ontology


ontology = rdflib.Namespace("http://example.org/autonomous-driving-ontology#")

# Define the key concepts


Object = ontology["Object"]
Event = ontology["Event"]
Relationship = ontology["Relationship"]
Rule = ontology["Rule"]

# Define some specific concepts


Car = ontology["Car"]
Pedestrian = ontology["Pedestrian"]
TrafficLight = ontology["TrafficLight"]
CollisionAvoidance = ontology["CollisionAvoidance"]
PassengerSafety = ontology["PassengerSafety"]

# Define some relationships


SubClassOf = ontology["SubClassOf"]
InstanceOf = ontology["InstanceOf"]
CausalRelationship = ontology["CausalRelationship"]

# Define some rules


Car_SubClassOf_Object = rdflib.Statement(Car, SubClassOf, Object)
Pedestrian_SubClassOf_Object = rdflib.Statement(Pedestrian, SubClassOf, Object)
TrafficLight_SubClassOf_Object = rdflib.Statement(TrafficLight, SubClassOf, Object)
CollisionAvoidance_SubClassOf_Event = rdflib.Statement(CollisionAvoidance, SubClassOf,
Event)
PassengerSafety_SubClassOf_Event = rdflib.Statement(PassengerSafety, SubClassOf, Event)

Car_InstanceOf_Object = rdflib.Statement(ontology.Car, InstanceOf, Object)


Pedestrian_InstanceOf_Object = rdflib.Statement(ontology.Pedestrian, InstanceOf, Object)
TrafficLight_InstanceOf_Object = rdflib.Statement(ontology.TrafficLight, InstanceOf,
Object)

CollisionAvoidance_CausalRelationship_PassengerSafety =
rdflib.Statement(CollisionAvoidance, CausalRelationship, PassengerSafety)

# Add the statements to the ontology


ontology.add(Car_SubClassOf_Object)
ontology.add(Pedestrian_SubClassOf_Object)
ontology.add(TrafficLight_SubClassOf_Object)
ontology.add(CollisionAvoidance_SubClassOf_Event)
ontology.add(PassengerSafety_SubClassOf_Event)

ontology.add(Car_InstanceOf_Object)
ontology.add(Pedestrian_InstanceOf_Object)
ontology.add(TrafficLight_InstanceOf_Object)

ontology.add(CollisionAvoidance_CausalRelationship_PassengerSafety)

# Print the ontology


print(ontology.serialize(format="turtle"))

Output:
@prefix ontology: <http://example.org/autonomous-driving-ontology#> .

ontology:Car SubClassOf ontology:Object .


ontology:Pedestrian SubClassOf ontology:Object .
ontology:TrafficLight SubClassOf ontology:Object .
ontology:CollisionAvoidance SubClassOf ontology:Event .
ontology:PassengerSafety SubClassOf ontology:Event .

ontology:Car InstanceOf ontology:Object .


ontology:Pedestrian InstanceOf ontology:Object .
ontology:TrafficLight InstanceOf ontology:Object .

ontology:CollisionAvoidance CausalRelationship ontology:PassengerSafety .

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:

1. Train the AI model on a high-quality dataset.


2. Evaluate the model on a held-out test dataset to assess its performance.
3. Identify biased features in the model. This can be done using a variety of methods, such as
correlation analysis or bias detection tools.
4. Remove biased features from the model.
5. Retrain the model on the data without biased features.
6. Evaluate the model on the test dataset again to assess its performance after removing biased
features.
7. Repeat steps 3-6 until the model is no longer biased and meets your performance
requirements.

Code:
import numpy as np
from sklearn.linear_model import LogisticRegression

# Load the data


X_train = np.loadtxt("train_data.csv", delimiter=",")
y_train = np.loadtxt("train_labels.csv", delimiter=",")

# Define the AI model


model = LogisticRegression()

# Train the model


model.fit(X_train, y_train)
# Evaluate the model on the test data
X_test = np.loadtxt("test_data.csv", delimiter=",")
y_test = np.loadtxt("test_labels.csv", delimiter=",")
y_pred = model.predict(X_test)

accuracy = np.sum(y_pred == y_test) / len(y_test)


print("Accuracy:", accuracy)

# Identify biased features


bias_scores = []
for i in range(X_train.shape[1]):
bias_score = np.abs(np.mean(X_train[y_train == 1, i]) - np.mean(X_train[y_train == 0,
i])) bias_scores.append(bias_score)

biased_features = np.argsort(bias_scores)[-10:]

# Remove biased features


X_train_without_bias = np.delete(X_train, biased_features, axis=1)
X_test_without_bias = np.delete(X_test, biased_features, axis=1)

# Retrain the model on the data without biased features


model.fit(X_train_without_bias, y_train)

# Evaluate the model on the test data without biased


features y_pred = model.predict(X_test_without_bias)

accuracy = np.sum(y_pred == y_test) / len(y_test)


print("Accuracy after removing biased features:",
accuracy)
Output:

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

You might also like