Ai Lab
Ai Lab
def print_board(board):
print(" | ".join(row))
print("-" * 5)
for i in range(3):
return True
return True
return False
def is_board_full(board):
def tic_tac_toe():
current_player = 'X'
while True:
print_board(board)
board[row][col] = current_player
if check_winner(board, current_player):
print_board(board)
break
if is_board_full(board):
print_board(board)
print("It's a tie!")
break
else:
if __name__ == "__main__":
tic_tac_toe()
import math
if depth == 0 or node_is_terminal(node):
return evaluate_node(node)
if maximizing_player:
max_eval = -math.inf
break
return max_eval
else:
min_eval = math.inf
break
return min_eval
def node_is_terminal(node):
return True
def evaluate_node(node):
return 0
def generate_children(node):
return []
# Example usage:
3.EM Algorithm
import numpy as np
# Initialization
n = len(data)
for _ in range(max_iterations):
# E-step: Compute responsibilities
for k in range(num_components):
Nk = responsibilities.sum(axis=0)
weights = Nk / n
break
np.random.seed(42)
# Run EM algorithm
num_components = 2
# Display results
import numpy as np
np.random.seed(42)
num_clusters = 4
kmeans.fit(X)
labels = kmeans.labels_
centers = kmeans.cluster_centers_
plt.title('K-means Clustering')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()
import numpy as np
iris = datasets.load_iris()
y = iris.target
svm_classifier.fit(X_train, y_train)
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.title(title)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()
data = {
# Fit the model with the data using Maximum Likelihood Estimation
model.fit(data, estimator=ParameterEstimator)
print(cpd)
inference = VariableElimination(model)
print(query_result)
7.Hidden Markov Model
import numpy as np
model = hmm.MultinomialHMM(n_components=2)
model.fit(obs)
hidden_states = model.predict(new_obs)
import speech_recognition as sr
def recognize_speech():
recognizer = sr.Recognizer()
print("Say something:")
try:
except sr.UnknownValueError:
except sr.RequestError as e:
print(f"Could not request results from Google Web Speech API; {e}")
if __name__ == "__main__":
recognize_speech()
9.Handwritten digit recognition
digits = datasets.load_digits()
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
predictions = clf.predict(X_test)
# Calculate accuracy
for i, ax in enumerate(axes.flat):
ax.set_title(f"Prediction: {predictions[i]}")
ax.axis('off')
plt.show()
10.Best first search
class Graph:
def __init__(self):
self.graph = {}
self.graph[node] = neighbors
visited = set()
priority_queue = PriorityQueue()
priority_queue.put((0, start))
print("Visiting:", current_node)
visited.add(current_node)
if current_node == goal:
print("Goal reached!")
break
priority_queue.put((cost, neighbor))
# Example usage
if __name__ == "__main__":
g = Graph()
g.add_edge("D", [])
g.add_edge("E", [])
g.add_edge("F", [])
print("Best-First Search:")
def predict(fruit):
# Count the number of apples and oranges among the nearest neighbors
# Predict the label of the fruit based on the majority class among the nearest neighbors
if num_apples_nn>num_oranges_nn:
return 'apple'
else:
return 'orange'
training_data = [
prediction = predict(test_fruit)
print(prediction)
Output:
‘apple’