AI practical file
AI practical file
1. Install Python:
o Download and install Python from the official website. Ensure you check the box to
add Python to your PATH during installation.
o Use tools like Visual Studio Code, PyCharm, or Jupyter Notebook for coding.
bash
Copy code
myenv\Scripts\activate # Windows
2. Installing AI Libraries
bash
1
Copy code
python
Copy code
import numpy as np
# Data
y = np.array([1, 2, 3, 4, 5])
# Model
model = LinearRegression()
model.fit(X, y)
# Prediction
python
Copy code
import tensorflow as tf
# Data
# Model
model = Sequential([
2
Dense(10, activation='relu', input_shape=(1,)),
Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# Training
# Prediction
2. Online Courses:
3. Documentation:
5. Managing Dependencies
bash
Copy code
bash
Copy code
3
Practical # 2
Problem Description
We will predict house prices based on a single feature: house size (in square feet). This is a
simple
regression problem, and we’ll use synthetic data for the demonstration.
import numpy as np
# 1. Data Preparation
house size = np.array([500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750]).reshape(-1,1)
house_price = np.array([50, 75, 100, 120, 150, 170, 200, 210, 250, 270]) # Prices in $1000s
# Split the dataset into training and testing sets (80% train, 20% test)
# 2. Model Training
model = LinearRegression()
model.fit(X_train, y_train)
# 3. Predictions
y_pred = model.predict(X_test)
# 4. Evaluation
plt.legend()
plt.show()
predicted_price = model.predict(new_house_size)
Output:
1. The Mean Squared Error gives a measure of how well the model predicts.
5
Practical # 3
We’ll use a simple graph where nodes represent locations, and edges represent possible paths.
Graph Representation
graph = {
BFS explores all neighbors at the current depth before moving to nodes at the next level.
queue = deque([start])
visited = set()
path = {}
while queue:
current = queue.popleft()
if current == goal:
final_path.append(current)
current = path.get(current)
return list(reversed(final_path))
visited.add(current)
queue.append(neighbor)
# Test BFS
7
Practical # 4
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start)
path.append(start)
if start == goal:
return path
if result:
return result
path.pop() # Backtrack
return None
# Test DFS
8
Practical # 5
1. A Search*
A* Search uses heuristics to prioritize nodes, making it more efficient for pathfinding.
import heapq
priority_queue = []
path = {}
while priority_queue:
_, current = heapq.heappop(priority_queue)
if current == goal:
final_path = []
final_path.append(current)
current = path.get(current)
return list(reversed(final_path))
g_costs[neighbor] = tentative_g_cost
9
f_cost = tentative_g_cost + heuristic(neighbor, goal)
# Test A* Search
Sample Output
10
Practical # 6
Here’s an implementation of basic game-playing techniques for a simple two-player game: Tic-Tac-Toe.
We'll demonstrate:
Minimax Algorithm
Game: Tic-Tac-Toe
Rules:
1. Board Representation
def print_board(board):
print(" | ".join(row))
print("-" * 5)
def is_moves_left(board):
return True
return False
2. Minimax Algorithm
How It Works:
11
• The maximizing player (X) tries to maximize the score.
def evaluate(board):
return 0
# Minimax function
score = evaluate(board)
return score
if not is_moves_left(board):
return 0
if is_maximizing:
best = -float("inf")
for i in range(3):
for j in range(3):
return best
else:
best = float("inf")
for i in range(3):
for j in range(3):
board[i][j] = "O"
return best
for i in range(3):
for j in range(3):
if (is_maximizing and move_val > best_val) or (not is_maximizing and move_val < best_val):
best_val = move_val
best_move = (i, j)
13
return best_move
def play_tic_tac_toe():
print("Welcome to Tic-Tac-Toe!")
print_board(board)
print("AI's turn:")
board[row][col] = "X"
else: # Player O
board[row][col] = "O"
else:
continue
print_board(board)
if evaluate(board) == 10:
print("AI wins!")
return
print("You win!")
return
print("It's a draw!")
14
# Start the game
play_tic_tac_toe()
15
Practical # 7
model.add_cpds(cpd_rain, cpd_traffic)
print(model.check_model())
16