Pakki Lab Programs
Pakki Lab Programs
while queue:
vertex = queue.popleft()
print(vertex, end=' ')
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': [],
'F': [],
'G': []
}
bfs(graph, 'A')
Possible Input:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': [],
'F': [],
'G': []
}
start = 'A'
Possible Output:
ABCDEFG
Python Code:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': [],
'F': [],
'G': []
}
dfs(graph, 'A')
Explanation
1. Graph Representation:
o The graph is represented as an adjacency list. Each key is a node, and the
value is a list of its neighbors.
2. BFS Function:
o Queue Initialization: Start with a queue initialized with the starting node.
o Visited Set: Use a set to keep track of visited nodes to avoid processing a
node more than once.
o While Loop: Continue processing nodes until the queue is empty.
o Processing a Node: Dequeue a node, print it, and add its unvisited neighbors
to the queue and mark them as visited.
3. Example Graph and BFS Execution:
o The graph provided as an example is a simple directed graph.
o The BFS function is called with the starting node 'A'.
Possible Input:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': [],
'F': [],
'G': []
}
start = 'A'
Possible Output:
ABDECFG
This output represents the order in which nodes are visited using the BFS algorithm starting
from node 'A'.
Concept Explanation: Greedy best-first search algorithm always selects the path which
appears best at that moment. It uses a priority queue to explore the node which is closest to
the goal.
Python Code:
import heapq
while open_list:
_, current = heapq.heappop(open_list)
if current in closed_list:
continue
if current == goal:
break
closed_list.add(current)
path = []
while current:
path.append(current)
current = came_from[current]
return path[::-1]
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 1), ('G', 2)],
'D': [],
'E': [],
'F': [],
'G': []
}
Possible Input:
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 1), ('G', 2)],
'D': [],
'E': [],
'F': [],
'G': []
}
start = 'A'
goal = 'G'
Possible Output:
Program 4: A* Search
Concept Explanation: A* Search algorithm is a search algorithm that finds the shortest path
from a starting node to a goal node. It uses both the actual distance from the start node and
the estimated distance to the goal node to prioritize the nodes to be explored.
Python Code:
import heapq
while open_list:
_, current = heapq.heappop(open_list)
if current in closed_list:
continue
if current == goal:
break
closed_list.add(current)
path = []
while current:
path.append(current)
current = came_from[current]
return path[::-1]
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 1), ('G', 2)],
'D': [],
'E': [],
'F': [],
'G': []
}
Possible Input:
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 1), ('G', 2)],
'D': [],
'E': [],
'F': [],
'G': []
}
start = 'A'
goal = 'G'
Possible Output:
Python Code:
closed_list.add(node)
optimal_cost = float('inf')
closed_list.remove(node)
g_costs[node] = optimal_cost
return optimal_cost != float('inf'), optimal_cost
closed_list = set()
g_costs = {}
came_from = {}
recur_ao_star(start)
path = []
current = start
while current != goal:
path.append(current)
current = came_from[current][0]
path.append(goal)
return path
graph = {
'A': [[('B', 1), ('C', 3)]],
'B': [[('D', 3), ('E', 1)]],
'C': [[('F', 1), ('G', 2)]],
'D': [],
'E': [],
'F': [],
'G': []
}
path = ao_star(graph, 'A', 'G')
print(path)
Explanation
1. Graph Representation:
o The graph is represented using an adjacency list where each node has children
and an associated cost.
o The heuristic values are stored separately in a dictionary.
2. AO Function*:
o Initialization: Start with the open list containing the start node.
o Loop: Continue processing nodes until the open list is empty.
o Processing a Node: Update the closed list, evaluate each child combination's
cost, and select the best combination based on the heuristic values.
o Update Heuristic: Update the heuristic value of the current node with the
minimum cost found.
o Update Optimal Subgraph: Record the best combination of children for the
current node.
3. Example Usage:
o A sample graph is defined with nodes and heuristic values.
o The ao_star function is called with the start node 'A'.
Possible Input:
graph = {
'A': [[('B', 1), ('C', 3)]],
'B': [[('D', 3), ('E', 1)]],
'C': [[('F', 1), ('G', 2)]],
'D': [],
'E': [],
'F': [],
'G': []
}
start = 'A'
goal = 'G'
Possible Output:
For the given example graph, the output will display the optimal subgraph and the updated
heuristic values for each node, guiding towards the most cost-effective solution.
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [2, 4, 6, 8, 10],
'target': [3, 6, 9, 12, 15]
}
df = pd.DataFrame(data)
X = df[['feature1', 'feature2']]
y = df['target']
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
Possible Input:
Possible Output:
vbnet
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
# Example dataset
data = {
'year': [2010, 2011, 2012, 2013, 2014],
'mileage': [50000, 40000, 30000, 20000, 10000],
'price': [15000, 14000, 13000, 12000, 11000]
}
df = pd.DataFrame(data)
X = df[['year', 'mileage']]
y = df['price']
model = DecisionTreeRegressor()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
Possible Input:
yaml
Possible Output:
vbnet
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'temperature': [30, 25, 27, 35, 20],
'humidity': [70, 65, 80, 90, 60],
'rain': [1, 1, 1, 0, 0] # 1 for rain, 0 for no rain
}
df = pd.DataFrame(data)
X = df[['temperature', 'humidity']]
y = df['rain']
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_pred = [1 if p >= 0.5 else 0 for p in y_pred]
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Possible Input:
Possible Output:
makefile
Accuracy: 1.0
Predictions: [1]
Concept Explanation: This program creates a simple model to predict golf outcomes based
on historical data. For this example, we use a decision tree classifier.
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'weather': ['sunny', 'rainy', 'sunny', 'cloudy', 'sunny'],
'temperature': [30, 25, 28, 20, 35],
'play_golf': [1, 0, 1, 1, 0] # 1 for play, 0 for no play
}
df = pd.DataFrame(data)
X = df[['weather', 'temperature']]
y = df['play_golf']
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Possible Input:
Possible Output:
makefile
Accuracy: 1.0
Predictions: [1]
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'email': ['buy now', 'limited offer', 'meeting at 3', 'project
deadline', 'win a prize'],
'label': [1, 1, 0, 0, 1] # 1 for spam, 0 for not spam
}
df = pd.DataFrame(data)
X = df['email']
y = df['label']
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(X)
model = MultinomialNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Possible Input:
email label
0 buy now 1
1 limited offer 1
2 meeting at 3 0
3 project deadline 0
4 win a prize 1
Possible Output:
makefile
Accuracy: 1.0
Predictions: [1]
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'sepal_length': [5.1, 4.9, 4.7, 4.6, 5.0],
'sepal_width': [3.5, 3.0, 3.2, 3.1, 3.6],
'petal_length': [1.4, 1.4, 1.3, 1.5, 1.4],
'petal_width': [0.2, 0.2, 0.2, 0.2, 0.2],
'species': [0, 0, 0, 0, 0] # 0 for setosa, 1 for versicolor, 2 for
virginica
}
df = pd.DataFrame(data)
model = SVC(kernel='linear')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Possible Input:
Possible Output:
Accuracy: 1.0
Predictions: [0]
Python Code:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
# Example dataset
data = {
'text': ['the quick brown fox', 'jumped over the lazy dog', 'the fox is
quick and brown'],
}
df = pd.DataFrame(data)
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['text'])
print("TF-IDF Matrix:")
print(X.toarray())
print("Feature Names:", vectorizer.get_feature_names_out())
Possible Input:
text
0 the quick brown fox
1 jumped over the lazy dog
2 the fox is quick and brown
Possible Output:
TF-IDF Matrix:
[[0.4472136 0. 0. 0.4472136 0.4472136 0.4472136 0. 0.4472136]
[0. 0.5 0.5 0. 0. 0. 0.5 0.5 ]
[0.4 0. 0. 0.4 0.4 0.4 0. 0. ]]
Feature Names: ['and' 'dog' 'jumped' 'quick' 'the' 'fox' 'over' 'lazy']
Concept Explanation: Natural Language Processing (NLP) involves the interaction between
computers and humans using natural language. This example uses the NLTK library to
tokenize text data.
Python Code:
import nltk
from nltk.tokenize import word_tokenize
# Example text
text = "Natural Language Processing with Python is fun."
# Tokenizing the text
tokens = word_tokenize(text)
print("Tokens:", tokens)
Possible Input:
arduino
Possible Output:
arduino
Concept Explanation: Object detection involves identifying and locating objects within an
image. This example uses OpenCV to detect faces in an image.
Python Code:
import cv2
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
Possible Input:
Possible Output:
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Example dataset
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([2, 3, 5, 7, 11])
model = LinearRegression()
model.fit(X, y)
Possible Input:
X = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
Possible Output:
Python Code:
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [2, 4, 6, 8, 10],
'target': [3, 6, 9, 12, 15]
}
df = pd.DataFrame(data)
X = df[['feature1', 'feature2']]
y = df['target']
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
Possible Input:
Possible Output:
Concept Explanation: Artificial Neural Networks (ANN) are computing systems inspired by
biological neural networks. This example demonstrates a simple ANN using
TensorFlow/Keras.
Python Code:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Example dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0]) # XOR problem
model = Sequential()
model.add(Dense(2, input_dim=2, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['accuracy'])
model.fit(X, y, epochs=1000, verbose=0)
predictions = model.predict(X)
print("Predictions:", (predictions > 0.5).astype(int))
Possible Input:
Possible Output:
Predictions: [[0]
[1]
[1]
[0]]
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [2, 4, 6, 8, 10],
'target': [0, 0, 1, 1, 1]
}
df = pd.DataFrame(data)
X = df[['feature1', 'feature2']]
y = df['target']
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Possible Input:
Possible Output:
Accuracy: 1.0
Predictions: [1]
Concept Explanation: Support Vector Machines (SVM) are supervised learning models
used for classification and regression tasks. This example demonstrates SVM classification
using Scikit-learn.
Python Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [2, 4, 6, 8, 10],
'target': [0, 0, 1, 1, 1]
}
df = pd.DataFrame(data)
X = df[['feature1', 'feature2']]
y = df['target']
model = SVC(kernel='linear')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Possible Input:
Possible Output:
Accuracy: 1.0
Predictions: [1]
Python Code:
import pandas as pd
from sklearn.decomposition import PCA
# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [2, 4, 6, 8, 10],
'feature3': [3, 6, 9, 12, 15]
}
df = pd.DataFrame(data)
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
print("PCA Components:")
print(X_pca)
Possible Input:
Possible Output:
PCA Components:
[[-5.65685425e+00 -1.77211596e-15]
[-2.82842712e+00 -2.72165527e-16]
[ 0.00000000e+00 2.13518101e-16]
[ 2.82842712e+00 8.10535199e-16]
[ 5.65685425e+00 -2.64943925e-16]]
Python program using the PIL (Pillow) library to illustrate basic image processing operations
like opening an image, resizing it, applying a filter, and saving the processed image.
if __name__ == "__main__":
input_image_path = 'input_image.jpg' # Path to the input image
output_image_path = 'output_image.jpg' # Path to save the processed
image
process_image(input_image_path, output_image_path)
Explanation
1. Importing Libraries:
o Image and ImageFilter are imported from the PIL (Pillow) library to handle
image operations and apply filters.
2. Opening an Image:
o The image is opened using Image.open(input_path), where input_path is
the path to the input image file.
3. Resizing the Image:
o The image is resized to 300x300 pixels using the resize() method.
4. Applying a Filter:
oA blur filter is applied to the resized image using
filter(ImageFilter.BLUR).
5. Saving the Processed Image:
o The processed image is saved to the specified output path using the save()
method.
6. Main Function:
o The process_image() function is called with paths to the input and output
images.
Instructions
1. Install Pillow:
o Ensure you have Pillow installed in your Python environment. You can install
it using pip:
sh
Copy code
pip install Pillow
This example demonstrates basic image processing operations using the Pillow library. You
can further extend it to include other operations such as cropping, rotating, adjusting colors,
and more.