Titiksha Public School
A
Subject: Artificial Intelligence (843)
Practical File
Class: XII
Session: 2024-25
Submitted To: - Submitted by:-
Ms. Jyoti RatheeName:
Roll No:
INDEX
[Link] Program Name Date Signature
Create a NumPy array and then split it into two
1
equal parts. Display both parts.
Write a NumPy program to check that none of the
2
elements of a given array are zero.
Write Python code to create a Pandas DataFrame
using any sequence data type. Check for missing
3
values in your DataFrame and fill them with the
column mean.
Create a dataframe of countries using a dictionary
which stored country name, capitals and populations
of the country.
a. Display the DataFrame
4
b. Display last 7 records
c. Display first 3 records
d. Display the number of missing values in the
dataset.
In the DataFrame created in practical 4, fill the
5. missing values of population and Capital with mean()
and median()
6. Download a dataset from kaggle and perform
statistical functions, fill missing values, etc.
Demonstrate train-test split using Linear
7
Regression.
Use the above model to predict new values of salary
8
given the yearsofexperience.
Create a Pandas DataFrame with a column
named-risk_category containing the values
9
"Low", "Medium", and "High" for different
regions. Convert the categorical values of
risk_category into numerical labels using
LabelEncoder.
Create a Pandas DataFrame with two columns:
population and vaccination_rate. Use a suitable
10 preprocessing technique (like StandardScaler or
MinMaxScaler) to scale these [Link] the
original and the scaled DataFrames.
Download a dataset from Kaggle and build a k-
Nearest Neighbors (kNN) classification model, test
11
it, and evaluate performance using a Confusion
Matrix in Orange Data Mining.
Perform classification on the heart disease dataset
using the Logistic Regression model in Orange Data
12 Mining. Use appropriate preprocessing techniques
before building the model and evaluate its
performance using suitable evaluation metrics.
Using the Grimm’s Tales dataset, perform a text
classification task in Orange Data Mining (ODM).
Preprocess the data, convert it into a bag-of-words
representation, and train a Logistic Regression
13
model to classify the texts. Evaluate the model’s
performance using a confusion matrix and visualize
the results. Also, make predictions on a new corpus.
Document all steps with appropriate screenshots.
Perform image classification on Orange Data Mining
14 using a suitable algorithm on any image dataset
downloaded from kaggle.
Create an effective data story from the following data:
Semmelweis was a Hungarian physician. Semmelweis
worked as an assistant at an obstetrics clinic where
15 many women suffered childbed fever - a fever caused by
an infection post-delivery. During his stint at the clinic,
Semmelweis was intrigued by a peculiar trend. The
clinics operated by male physicians and medical students
had significantly higher mortality rates from childbed
fever as compared to clinics operated by midwives. As
a result, he introduced hand-washing. The child
mortality rate which was 12.% dropped to 2.%. However,
some doctors refused to listen to him . Then the
mortality rate again reached 35.%. When the mortality
rate touched 49.%, Semmelweis was thrown out of the
community
16
Practical-1
Create a NumPy array and then split it into two equal parts. Display both parts.
Source Code-
import numpy as np
arr=[Link](55,66)
arr1,arr2=np.array_split(arr,2)
print("First array=",arr1)
print("First array=",arr2)
Output-
Practical -2
Write a NumPy program to check that none of the elements of a given array are zero.
Source Code-
import numpy as np
arr= [Link]([21,56,78,45,67,87,33])
if [Link](arr!=0):
print("none of the elements are zero")
else:
print("There is atleast one element which is zero")
Output-
Practical -3
Write Python code to create a Pandas DataFrame using any sequence data [Link]
for missing values in your DataFrame and fill them with the column mean.
Source Code-
import pandas as pd
import numpy as np
data = {
"English": [50, 55, 67, [Link], 95],
"Hindi": [45, 78, [Link], 67, 56],
"Maths": [55, 45, 34, 78, 98],
"Science": [66, 34, 55, 23, 89],
"Artificial Intelligence": [53, 67, 89, 44, [Link]] }
df = [Link](data, index=["Sahil", "Rahul", "Shikha", "Uday", "Roma"])
print("Original DataFrame with Missing Values:")
print(df)
print("\nMissing values in each column:")
print([Link]().sum())
df.fillna([Link](numeric_only=True), inplace=True)
print("\nDataFrame after filling missing values with column mean:")
print(df)
Output-
Practical -4
Create a dataframe of countries using a dictionary which stored country name, capitals
and populations of the country.
a. Display the DataFrame
b. Display last 7 records
c. Display first 3 records
d. Display the number of missing values in the dataset.
Source Code-
import pandas as pd
data = [{'Country': 'India', 'Capital': 'New Delhi','Population': 139338},
{'Country': 'USA', 'Capital': 'Washington, D.C.', 'Population': 3310651},
{'Country': 'Germany', 'Capital': 'Berlin', 'Population': 837839},
{'Country': 'France', 'Capital': 'Paris', 'Population': 652711},
{'Country': 'Brazil', 'Capital': 'Brasília', 'Population': 2125517},
{'Country': 'Canada', 'Capital': 'Ottawa', 'Population': 377454},
{'Country': 'Japan', 'Capital': 'Tokyo', 'Population': 1264761},
{'Country': 'Australia', 'Capital': 'Canberra', 'Population': 254994},
{'Country': 'Russia', 'Capital': 'Moscow', 'Population': 1459462},
{'Country': 'Italy', 'Capital': None, 'Population': None}]
df = [Link](data)
print("DataFrame:")
print(df)
print("\nLast 7 Records:")
print([Link](7))
print("\nFirst 3 Records:")
print([Link](3))
print("\nNumber of missing values in each column:")
print([Link]().sum())
Output-
Practical -5
In the DataFrame created in practical 4, fill the missing values of population and Capital
with mean() and median()
Source Code-
import pandas as pd
data = [
{'Country': 'India', 'Capital': 'New Delhi','Population': 1398},
{'Country': 'USA', 'Capital': 'Washington, D.C.', 'Population': 33101},
{'Country': 'Germany', 'Capital': 'Berlin', 'Population': 8339},
{'Country': 'France', 'Capital': 'Paris', 'Population': 6521},
{'Country': 'Brazil', 'Capital': 'Brasília', 'Population': 2127},
{'Country': 'Canada', 'Capital': 'Ottawa', 'Population': 3774},
{'Country': 'Japan', 'Capital': 'Tokyo', 'Population': 12761},
{'Country': 'Australia', 'Capital': 'Canberra', 'Population': 2594},
{'Country': 'Russia', 'Capital': 'Moscow', 'Population': 14462},
{'Country': 'Italy', 'Capital': None, 'Population': None}]
df = [Link](data)
print("DataFrame:")
print(df)
df['Capital']=df['Capital'].fillna(df['Capital'].mode()[0])
df['Population']=df['Population'].fillna(df['Population'].mean())
print("\nDataFrame after filling missing values:")
print(df)
Output-
Practical -6
Download a dataset from kaggle and perform statistical functions, fill missing values,
etc..
Source Code-
import pandas as pd
df= pd.read_csv("melb_data.csv")
print("statistical summery")
print([Link]())
print("missing values")
print([Link]().sum())
df.fillna([Link](numeric_only=True),inplace=True)
# for categorial values
for col in df.select_dtypes(include=['object']):
df[col].fillna(df[col].mode()[0], inplace=True)
print("missing values after filling")
print([Link]().sum())
Output-
Practical -7
Demonstrate train-test split using Linear Regression.
Source Code-
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error
from [Link] import r2_score
df= pd.read_csv("Salary_Data.csv")
x=df[['YearsExperience']]
y=df['Salary']
x_train,x_test,y_train,y_test= train_test_split(x,y,test_size=0.1,random_state=42)
model=LinearRegression()
model.fit(x_train,y_train)
y_pred=[Link](x_test)
print("predicted values")
print(y_pred)
print("actual values=",y_test)
#Model evaluation
mse=mean_squared_error(y_test,y_pred)
r2=r2_score(y_test,y_pred)
print("Mean squared error=",mse)
print("R2 score=",r2)
Output-
Practical -8
Use the above model to predict new values of salary given the yearsofexperience.
Source Code-
yrexp=int(input("Enter the years of experience: "))
user_input=[Link]([[yrexp]])
prediction=[Link](user_input)
print("Predicted salary:-" , prediction)
Output-
Practical-9
Create a Pandas DataFrame with a column named-risk_category
containing the values "Low", "Medium", and "High" for different regions.
Convert the categorical values of risk_category into numerical labels using
LabelEncoder.
Source Code:
import pandas as pd
from [Link] import LabelEncoder
data = {
"region": ["North", "South", "East", "West", "Central"],
"Risk_category": ["Low", "High", "Medium", "Low", "High"]}
df = [Link](data)
label_encoder = LabelEncoder()
df["risk_encoded"] = label_encoder.fit_transform(df["Risk_category"])
print(df)
Output-
Practical 10
Create a Pandas DataFrame with two columns: population and vaccination_rate. Use a
suitable preprocessing technique (like StandardScaler or MinMaxScaler) to scale these
[Link] the original and the scaled DataFrames.
Source Code-
import pandas as pd
from [Link] import MinMaxScaler
data = {
"population": [150000, 85000, 240000, 120000, 175000],
"vaccination_rate": [78.5, 45.3, 88.2, 60.0, 72.9]}
df = [Link](data)
print(df)
# Step 2: Apply MinMaxScaler to scale the features between 0 and 1
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df)
print("scaled columns=", scaled_data)
scaled_df = [Link](scaled_data, columns=["population_scaled", "vaccination_rate_scaled"])
print("Scaled DataFrame using MinMaxScaler:")
print(scaled_df)
Output-
Orange data Mining
Practical -11
Download a dataset from Kaggle and build a k-Nearest Neighbors (kNN) classification
model, test it, and evaluate performance using a Confusion Matrix in Orange Data Mining.
Link of Dataset- [Link]
Steps to perform Classification in Orange data Mining-
1. File Widget
○ Drag and drop the File widget.
○ Load the dataset
2. Data Table Widget
○ Connect the File widget to a Data Table widget.
○ Use this to preview the raw dataset.
3. Impute Widget
○ Add the Impute widget to handle missing values.
○ Connect the File widget to Impute.
○ This replaces missing data with mean/mode/median.
4. Data Sampler Widget
○ This splits the dataset into training and testing samples.
○ Configure the percentage split (e.g., 70% training, 30% testing).
5. kNN Widget
○ Add the kNN widget.
○ Connect the Data Sampler Data Sample > Data output to kNN.
6. Test and Score Widget- Drag the Test and Score widget.
○ Connect both:
■ kNN (Learner) to Test and Score
■ Data Sampler Data Sample > Data to Test and Score
○ This evaluates the model on test data.
7. Confusion Matrix Widget
○ Connect Test and Score to Confusion Matrix.
○ It shows classification performance in a matrix format.
8. Predictions Widget -Connect the kNN (Model Predictors) and test data to a
Predictions widget to view predicted labels.
Snapshots-
Output-
Practical -12
Perform classification on the heart disease dataset using the Logistic Regression
model in Orange Data Mining. Use appropriate preprocessing techniques before building
the model and evaluate its performance using suitable evaluation metrics.
Steps to Perform the Practical:
1. Import the Dataset:
○Drag and drop the File widget to the canvas.
○Double-click it and browse to select the heart_disease.tab dataset.
2. Add Preprocessing:
○Add the Preprocess widget and connect it to the File or Select Columns
widget.
○In the Preprocess widget, apply preprocessing techniques such as:
■ Impute missing values
■ Normalize or standardize numeric data
3. Apply Logistic Regression:
○Drag the Logistic Regression widget to the canvas and connect it to the
Preprocess widget.
○Double-click the Logistic Regression widget to view and configure its
settings if required.
4. Evaluate the Model:
○Drag the Test & Score widget and connect both the Preprocess and
Logistic Regression widgets to it.
○This will evaluate the model using cross-validation or a train-test split.
○Note metrics such as Accuracy, AUC, Precision, Recall, and F1 Score.
5. View Predictions:
○Add the Confusion Matrix or Predictions widget to visualize results.
Output-
Practical -13
Using the Grimm’s Tales dataset, perform a text classification task in Orange Data
Mining (ODM). Preprocess the data, convert it into a bag-of-words representation,
and train a Logistic Regression model to classify the texts. Evaluate the model’s
performance using a confusion matrix and visualize the results. Also, make predictions
on a new corpus. Document all steps with appropriate screenshots.
Steps-
Step-1 Import Dataset- Load the Grimm’s Tales dataset using the Corpus widget.
Step-2 View Data - Use Corpus Viewer to explore the text data.
Step-3 Preprocess Text- Apply Preprocess Text to clean and prepare the text like lowercase,
remove stop words.
Step-4 Convert Text to Features- Use Bag of Words to convert the preprocessed text into
numerical data.
Step-5 Train Model - Connect Logistic Regression to train the model on the bag-of-words data.
Step-6 Evaluate Model- Use Test and Score and Confusion Matrix to evaluate model performance.
Step-7 Predict on New Data-Import new text using another Corpus, preprocess it, and use
Predictions to get results.
Step-8 Visualize Results- View results using Corpus Viewer for better understanding.
Output-
Wrongly predicted documents-
Prediction on unseen data-
Practical -14
Perform image classification on Orange Data Mining using a suitable algorithm on any
image dataset downloaded from kaggle.
Link to download the dataset-
Step-
Output-
Predictions on Unseen data-
Performance of ML Model-
Confusion Matrix-
Data
Storytelling
Practical -15
Create an effective data story from the following data:
Semmelweis was a Hungarian physician. Semmelweis worked as an assistant at an obstetrics
clinic where many women suffered childbed fever - a fever caused by an infection post-
delivery. During his stint at the clinic, Semmelweis was intrigued by a peculiar trend. The
clinics operated by male physicians and medical students had significantly higher mortality
rates from childbed fever as compared to clinics operated by midwives. As a result, he
introduced hand-washing. The child mortality rate which was 12.% dropped to 2.%. However,
some doctors refused to listen to him . Then the mortality rate again reached 35.%. When
the mortality rate touched 49.%, Semmelweis was (Source: Internet) thrown out of the
community
Practical -16