Python Lab Manual Detail
Python Lab Manual Detail
6th SEMESTER,
EVEN 2025
Prepared by
TEJASWINI H S
Assistant Professor
Dept. of ECE
CIT, Mandya
INDEX
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the
cost of program maintenance.
Machine learning finds applications in diverse fields such as image and speech
recognition, natural language processing, recommendation systems, fraud detection,
portfolio optimization, and automating tasks.
Python is considered one of the most popular programming languages used for Machine
Learning due to its readily available libraries like NumPy, Pandas, Scikit-learn,
TensorFlow, and Keras, which significantly simplify the process of building and
implementing machine learning models, making it a widely preferred choice for data
analysis and predictive modeling across various industries.
Software Used:
PIP
PyCharm
PIP
Installation links:
https://www.python.org/downloads/
https://www.jetbrains.com/pycharm/download/?section=windows
python –-version
List of Libraries:
1. TensorFlow: This library was developed by Google in collaboration with the Brain
Team. It is an open-source library used for high-level computations. It is also used
in machine learning and deep learning algorithms. It contains a large number of
tensor operations. Researchers also use this Python library to solve complex
computations in Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why
it is used in data analysis. It is also an open-source library and plots high-defined
figures like pie charts, histograms, scatterplots, graphs, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly
used library. It is a popular machine learning library that supports large matrices
and multi-dimensional data. It consists of in-built mathematical functions for
easy computations. Even libraries like TensorFlow use Numpy internally to
perform several operations on tensors. Array Interface is one of the key features of
this library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source
library used for high-level scientific computations. This library is built over an
extension of Numpy. It works with Numpy to handle complex computations. While
Numpy allows sorting and indexing of array data, the numerical data code is
stored in SciPy. It is also widely used by application developers and engineers.
6. Scrapy: It is an open-source library that is used for extracting data from websites.
It provides very fast web crawling and high-level screen scraping. It can also be
used for data mining and automated testing of data.
9. PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural networks.
10. PyBrain: The name “PyBrain” stands for Python Based Reinforcement
Learning, Artificial Intelligence, and Neural Networks library. It is an open-
source library built for beginners in the field of Machine Learning. It provides fast
and easy-to-use algorithms for machine learning tasks. It is so flexible and easily
understandable and that’s why is really helpful for developers that are new in
research fields
.
1|Page Python Programming for Machine Learning Applications [BEC657D]
Program 1:
Solve the Tic-Tac-Toe problem using the Depth First Search technique.
grid = []
line = []
for i in range(3):
for j in range(3):
line.append(" ")
grid.append(line)
line = []
# grid printing
def print_grid():
for i in range(3):
print("|", end="")
for j in range(3):
print(grid[i][j], "|", end="")
print("")
# player turn
def player_turn(turn_player1):
if turn_player1 == True:
turn_player1 = False
print(f"It's {player2}'s turn")
else:
turn_player1 = True
print(f"It's {player1}'s turn")
return turn_player1
# choosing cell
def write_cell(cell):
cell -= 1
i = int(cell / 3)
j = cell % 3
if turn_player1 == True:
grid[i][j] = player1_symbol
else:
grid[i][j] = player2_symbol
return grid
# checking cell
def free_cell(cell):
cell -= 1
i = int(cell / 3)
j = cell % 3
if grid[i][j] == player1_symbol or grid[i][j] == player2_symbol:
print("This cell is not free")
return False
return True
# game opening
print("Welcome to the Tic-Tac-Toe !")
print("")
print_grid()
print("")
player1 = input("Please enter name of player 1 : ")
player1_symbol = input("Please enter the symbol of player 1 : ")
player2 = input("Please enter name of player 2 : ")
player2_symbol = input("Please enter the symbol of player 2 : ")
Department of ECE CIT Mandya Prof.Tejaswini H S,
Asst.Professor
3|Page Python Programming for Machine Learning Applications [BEC657D]
game = True
full_grid = False
turn_player1 = False
winner = ""
# win check
def win_check(grid, player1_symbol, player2_symbol):
full_grid = True
player1_symbol_count = 0
player2_symbol_count = 0
# checking rows
for i in range(3):
for j in range(3):
if grid[i][j] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i][j] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
Department of ECE CIT Mandya Prof.Tejaswini H S,
Asst.Professor
4|Page Python Programming for Machine Learning Applications [BEC657D]
player2_symbol_count = 0
# checking columns
player1_symbol_count = 0
player2_symbol_count = 0
for i in range(3):
for j in range(3):
for k in range(3):
if i + k <= 2:
if grid[i + k][j] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i + k][j] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
# checking diagonals
player1_symbol_count = 0
player2_symbol_count = 0
for i in range(3):
for j in range(3):
Department of ECE CIT Mandya Prof.Tejaswini H S,
Asst.Professor
5|Page Python Programming for Machine Learning Applications [BEC657D]
for k in range(3):
if j + k <= 2 and i + k <= 2:
if grid[i + k][j + k] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
game = False
winner = player1
return game, winner
if grid[i + k][j + k] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
player1_symbol_count = 0
player2_symbol_count = 0
for i in range(3):
for j in range(3):
for k in range(3):
if j - k >= 0 and i + k <= 2:
if grid[i + k][j - k] == player1_symbol:
player1_symbol_count += 1
player2_symbol_count = 0
if player1_symbol_count == 3:
Department of ECE CIT Mandya Prof.Tejaswini H S,
Asst.Professor
6|Page Python Programming for Machine Learning Applications [BEC657D]
game = False
winner = player1
return game, winner
if grid[i + k][j - k] == player2_symbol:
player2_symbol_count += 1
player1_symbol_count = 0
if player2_symbol_count == 3:
game = False
winner = player2
return game, winner
if grid[i][j] == " ":
full_grid = False
player1_symbol_count = 0
player2_symbol_count = 0
# game
while game == True:
turn_player1 = player_turn(turn_player1)
free_box = False
while free_box == False:
Department of ECE CIT Mandya Prof.Tejaswini H S,
Asst.Professor
7|Page Python Programming for Machine Learning Applications [BEC657D]
cell = int(input("Please enter a number for your case (1 to 9 from left to right and from
top to bottom) : "))
free_box = free_cell(cell)
grid = write_cell(cell)
print_grid()
game, winner = win_check(grid, player1_symbol, player2_symbol)
# end of game
if winner == player1:
print(f"Winner is {player1} !")
elif winner == player2:
print(f"Winner is {player2} !")
else:
print(f"Grid is full : equality for {player1} and {player2} !")
Program 2:
Show that the 8-puzzle states are divided into two disjoint sets, such that any
state is reachable from any other state in the same set, while no state is reachable
from any state in the other set.
For each state in the input list, it calls count_inversions to get the
number of inversions.
Depending on whether the number of inversions is even or odd, it
appends the state to the corresponding list.
Return Value: A tuple containing the two lists: set_even and set_odd.
3. Example States:
A list of example states is provided, where each state is a configuration of the
puzzle. The number of inversions for each state is commented next to it.
4. Classification and Output:
The classify_states function is called with the example states, and the results
are stored in set_even and set_odd.
Finally, the code prints the states classified as having even inversions and those
with odd inversions.
def count_inversions(state):
for i in range(len(flat_state)):
for j in range(i + 1, len(flat_state)):
if flat_state[i] > flat_state[j]:
inversions += 1
return inversions
def classify_states(states):
"""Classify states into two sets based on the parity of inversions."""
set_even = []
set_odd = []
inversions = count_inversions(state)
if inversions % 2 == 0:
set_even.append(state)
else:
set_odd.append(state)
Program 3:
To represent and evaluate different scenarios using predicate logic and
knowledge rules.
class Predicate:
def __init__(self, name, *args):
self.name = name
self.args = args
def __repr__(self):
return f"{self.name}({', '.join(map(str, self.args))})"
class KnowledgeBase:
def __init__(self):
self.facts = set()
self.rules = []
# Evaluate rules
for rule in self.rules:
if rule['condition'](self):
self.facts.add(rule['conclusion'])
if query == rule['conclusion']:
return True
return False
# Example predicates
is_mammal = Predicate('is_mammal', 'dog')
is_mammal2 = Predicate('is_mammal', 'cat')
is_bird = Predicate('is_bird', 'sparrow')
# Add facts
kb.add_fact(is_mammal)
kb.add_fact(is_mammal2)
# Define rules
def rule1(kb):
return Predicate('is_mammal', 'dog') in kb.facts
def rule2(kb):
return Predicate('is_bird', 'sparrow') in kb.facts
# Evaluate scenarios
query1 = Predicate('has_fur', 'dog')
query2 = Predicate('can_fly', 'sparrow')
or
class KnowledgeBase:
def __init__(self):
self.facts = {}
self.rules = []
# Define a rule
def can_fly(kb, animal):
if is_bird(kb, animal):
return True
return False
# Add facts
kb.add_fact('mammals', 'dog')
kb.add_fact('mammals', 'cat')
kb.add_fact('birds', 'sparrow')
kb.add_fact('birds', 'eagle')
# Add rules
kb.add_rule({'condition': is_bird, 'conclusion': can_fly})
# Evaluate scenarios
animals_to_check = ['dog', 'sparrow', 'cat', 'eagle']
Program 4:
S[j] = '?'
def update_hypotheses_negative(G, S, example):
new_G = copy.deepcopy(G)
for i in range(len(G)):
if not is_consistent(G[i], example):
new_G.remove(G[i])
return new_G
instance1 = ['sunny', 'warm', 'normal', 'strong', 'warm', 'same']
instance2 = ['sunny', 'warm', 'high', 'strong', 'warm', 'same']
instance3 = ['rainy', 'cold', 'high', 'strong', 'warm', 'change']
instance4 = ['sunny', 'warm', 'high', 'strong', 'cool', 'change']
update_hypotheses_positive(G, S, instance1)
print("After instance 1:")
print("G =", G)
print("S =", S)
update_hypotheses_positive(G, S, instance2)
print("\nAfter instance 2:")
print("G =", G)
print("S =", S)
G = update_hypotheses_negative(G, S, instance3)
print("\nAfter instance 3:")
print("G =", G)
print("S =", S)
update_hypotheses_positive(G, S, instance4)
print("\nAfter instance 4:")
print("G =", G)
print("S =", S)
Find-S Algorithm
The Find-S algorithm is a simple version of the concept learning algorithm that finds the
most specific hypothesis that is consistent with the training examples. It starts with the most
specific hypothesis (the most specific instance) and generalizes it only when it encounters
negative examples.
Find S – Algorithm
import numpy as np
class FindS:
def __init__(self):
self.hypothesis = None
for i in range(len(X)):
if y[i] == 'yes': # Only consider positive examples
for j in range(len(X[i])):
# If the attribute is not a wildcard, update the hypothesis
if self.hypothesis[j] == '0':
self.hypothesis[j] = X[i][j]
elif self.hypothesis[j] != X[i][j]:
self.hypothesis[j] = '?'
# Example dataset
X = np.array([
['sunny', 'hot', 'high', 'false'],
['sunny', 'hot', 'high', 'true'],
['overcast', 'hot', 'high', 'false'],
['rainy', 'mild', 'high', 'false'],
['rainy', 'cool', 'normal', 'false'],
['rainy', 'cool', 'normal', 'true'],
['overcast', 'cool', 'normal', 'true'],
['sunny', 'mild', 'high', 'false'],
['sunny', 'cool', 'normal', 'false'],
['rainy', 'mild', 'normal', 'false'],
['sunny', 'mild', 'normal', 'true'],
['overcast', 'mild', 'high', 'true'],
['overcast', 'hot', 'normal', 'false'],
['rainy', 'mild', 'high', 'true']
])
y = np.array(['no', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'no', 'yes'])
# Applying Find-S
find_s = FindS()
find_s.fit(X, y)
print("Find-S Hypothesis:", find_s.hypothesis)
# Predictions
predictions = find_s.predict(X)
print("Predictions:", predictions)
class VersionSpace:
def __init__(self):
self.hypotheses = []
for i in range(len(X)):
if y[i] == 'yes':
# Update hypotheses for positive examples
self.hypotheses = [h for h in self.hypotheses if self.is_consistent(h, X[i])]
self.hypotheses.append(X[i].tolist())
else:
# Remove inconsistent hypotheses for negative examples
self.hypotheses = [h for h in self.hypotheses if not self.is_consistent(h,
X[i])]
predictions = []
for x in X:
match = any(self.is_consistent(h, x) for h in self.hypotheses)
predictions.append('yes' if match else 'no')
return predictions
# Predictions
predictions_vs = version_space.predict(X)
print("Predictions (Version Space):", predictions_vs)
Program 5:
To construct a decision tree using the ID3 algorithm on a simple classification dataset
import pandas as pd
The ID3 (Iterative Dichotomiser 3) algorithm is a popular method for constructing decision
trees, which are used for classification tasks in machine learning. The decision tree is a
flowchart-like structure where each internal node represents a test on an attribute, each branch
represents the outcome of the test, and each leaf node represents a class label. The goal of the
ID3 algorithm is to create a decision tree that accurately classifies instances based on their
attributes.
import pandas as pd
data = {
'Temperature': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Mild', 'Mild', 'Hot', 'Mild',
'Cool', 'Mild', 'Cool', 'Cool'],
'Windy': [False, True, False, False, False, True, True, False, False, False, True, True,
False, True],
'Play': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes',
'No']
df = pd.DataFrame(data)
le = LabelEncoder()
df['Outlook'] = le.fit_transform(df['Outlook'])
df['Temperature'] = le.fit_transform(df['Temperature'])
df['Humidity'] = le.fit_transform(df['Humidity'])
df['Windy'] = le.fit_transform(df['Windy'])
df['Play'] = le.fit_transform(df['Play'])
X = df.drop('Play', axis=1)
y = df['Play']
clf.fit(X_train, y_train)
print(f'Accuracy: {accuracy:.2f}')
plt.figure(figsize=(12,8))
plt.show()
Program 6:
To assess how the ID3 algorithm performs on datasets with varying characteristics and
complexity, examining overfitting, underfitting, and decision tree depth.
import numpy as np
import pandas as pd
# Create datasets
datasets = {
train_accuracies = []
test_accuracies = []
clf.fit(X_train, y_train)
train_pred = clf.predict(X_train)
test_pred = clf.predict(X_test)
train_accuracies.append(accuracy_score(y_train, train_pred))
test_accuracies.append(accuracy_score(y_test, test_pred))
# Store results
results = {}
plt.figure(figsize=(15, 10))
plt.xlabel('Max Depth')
plt.ylabel('Accuracy')
plt.xticks(max_depths)
plt.ylim(0, 1)
plt.legend()
plt.grid()
plt.show()
Program 7:
Supervised Learning
Application: For a classification problem, you might use a dataset of emails labeled as
"spam" or "not spam." The algorithm learns to classify new emails based on the
features it identifies in the training data.
import numpy as np
model = RandomForestClassifier()
model.fit(X_train, y_train)
# Make predictions
predictions = model.predict(X_test)
Unsupervised:
import numpy as np
X = np.array([[1.0, 2.0],
[1.5, 1.8],
[5.0, 8.0],
[8.0, 8.0],
[1.0, 0.6],
[9.0, 11.0],
[8.0, 2.0],
[10.0, 2.0],
[9.0, 3.0],
[5.0, 4.0]])
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
# Predict clusters
clusters = kmeans.predict(X)
Semi Supervised:
Definition: Semi-supervised learning combines both labeled and unlabeled data for
training. It typically starts with a small amount of labeled data and a larger amount of
unlabeled data.
Application: This approach is useful when acquiring labeled data is expensive or time-
consuming, such as in image classification where only a few images are labeled.
import numpy as np
base_model = RandomForestClassifier()
self_training_model = SelfTrainingClassifier(base_model)
self_training_model.fit(X, y)
# Make predictions
predictions = self_training_model.predict(X)
print("Predictions:", predictions)
Program 8:
To understand how Find-S and Candidate Elimination algorithms search through the
hypothesis space in concept learning tasks, and to observe the role of inductive bias in
shaping the learned concept.
Find-S Algorithm
The Find-S algorithm is a simple version of a concept learning algorithm that finds the most
specific hypothesis that is consistent with the positive training examples. It starts with the most
specific hypothesis and generalizes it based on the positive examples.
The Candidate Elimination algorithm maintains a set of hypotheses that are consistent with the
training examples. It uses two sets: the general boundary (G) and the specific boundary (S).
The algorithm refines these sets based on the training examples.
import numpy as np
# Sample dataset
# Each row represents an example: [Sky, Air Temp, Humidity, Windy, Water, Forecast,
Enjoy Sport]
# 1 = Yes, 0 = No
data = np.array([
])
# Find-S Algorithm
def find_s(data):
for i in range(len(specific_hypothesis)):
if specific_hypothesis[i] == '0':
specific_hypothesis[i] = example[i]
specific_hypothesis[i] = '?'
return specific_hypothesis
def candidate_elimination(data):
for i in range(len(specific_hypothesis)):
if specific_hypothesis[i] == '0':
specific_hypothesis[i] = example[i]
specific_hypothesis[i] = '?'
# Remove general hypotheses that are inconsistent with the positive example
# Remove specific hypotheses that are inconsistent with the negative example
new_general_hypotheses = generate_general_hypotheses(example,
specific_hypothesis)
general_hypothesis.extend(new_general_hypotheses)
if h != '?' and h != e:
return False
return True
new_general_hypotheses = []
for i in range(len(specific_hypothesis)):
new_hypothesis = specific_hypothesis.copy()
new_hypothesis[i] = '?'
new_general_hypotheses.append(new_hypothesis)
return new_general_hypotheses
find_s_hypothesis = find_s(data)
Program 9:
To go through all stages of a real-life machine learning project, from data collection to
model fine-tuning, using a regression dataset like the "California Housing Prices."
1. Data Collection
Acquire the California Housing Prices dataset, which contains metrics such as
population, median income, and median housing prices for various districts in
California.
import pandas as pd
housing = pd.read_csv("F:\\python\\housing.csv")
print(housing.head())
imputer = SimpleImputer(strategy="median")
imputer.fit(housing_num)
X = imputer.transform(housing_num)
plt.show()
corr_matrix = housing.corr()
print(corr_matrix['median_house_value'].sort_values(ascending=False))
lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, housing_labels)
housing_predictions = lin_reg.predict(housing_prepared)
lin_rmse = np.sqrt(lin_mse)
print(lin_rmse)
param_grid = [
grid_search.fit(housing_prepared, housing_labels)
final_model = grid_search.best_estimator_
X_test_prepared = full_pipeline.transform(X_test)
final_predictions = final_model.predict(X_test_prepared)
final_rmse = np.sqrt(final_mse)
print(final_rmse)
Program 10:
More Explanation:
https://www.geeksforgeeks.org/evaluation-metrics-for-classification-model-in-python/
train_y = to_categorical(train_y)
test_y = to_categorical(test_y)
model = Sequential([
MaxPooling2D((2, 2)),
Flatten(),
Dense(100, activation='relu'),
Dense(10, activation='softmax')
])
y_pred = model.predict(test_X)
y_pred_classes = y_pred.argmax(axis=1)
y_test_classes = test_y.argmax(axis=1)