sickittit-learno 3.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sickittit-learno-3.0.1/MANIFEST.in +2 -0
- sickittit-learno-3.0.1/PKG-INFO +12 -0
- sickittit-learno-3.0.1/setup.cfg +4 -0
- sickittit-learno-3.0.1/setup.py +22 -0
- sickittit-learno-3.0.1/sickittit_learno/__init__.py +4 -0
- sickittit-learno-3.0.1/sickittit_learno/data/__init__.py +0 -0
- sickittit-learno-3.0.1/sickittit_learno/data/student.csv +21 -0
- sickittit-learno-3.0.1/sickittit_learno/data/student_marks.csv +21 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/__init__.py +0 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p01_reflex_vacuum.py +34 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p02_bfs_8puzzle.py +92 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p03_dfs_waterjug.py +47 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p04_ucs_citygraph.py +40 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p05_greedy_8puzzle.py +83 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p06_astar_8puzzle.py +91 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p07_astar_romania.py +58 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p08_bayes_medical.py +20 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p09_naivebayes_weather.py +43 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p10_bayesnet_burglary.py +81 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p11_bayesnet_posterior.py +62 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_1_ml_student_csv.py +43 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_2_linreg_marks.py +33 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_3_mnist_binary.py +33 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_4_kfold_iris.py +25 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_5_dtree_iris.py +30 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_6_dtree_reg_marks.py +34 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_7_knn_iris.py +30 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p12_8_multiclass_dtree_iris.py +30 -0
- sickittit-learno-3.0.1/sickittit_learno/practicals/p13_ethics_bias_iris.py +31 -0
- sickittit-learno-3.0.1/sickittit_learno/practs.py +133 -0
- sickittit-learno-3.0.1/sickittit_learno.egg-info/PKG-INFO +12 -0
- sickittit-learno-3.0.1/sickittit_learno.egg-info/SOURCES.txt +34 -0
- sickittit-learno-3.0.1/sickittit_learno.egg-info/dependency_links.txt +1 -0
- sickittit-learno-3.0.1/sickittit_learno.egg-info/entry_points.txt +4 -0
- sickittit-learno-3.0.1/sickittit_learno.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sickittit-learno
|
|
3
|
+
Version: 3.0.1
|
|
4
|
+
Summary: AI Practicals cheatsheet (print code + fetch ready-made data files)
|
|
5
|
+
Home-page: UNKNOWN
|
|
6
|
+
Author: Anant Prajapati
|
|
7
|
+
License: UNKNOWN
|
|
8
|
+
Platform: UNKNOWN
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
|
|
11
|
+
UNKNOWN
|
|
12
|
+
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from setuptools import setup, find_packages
|
|
2
|
+
|
|
3
|
+
setup(
|
|
4
|
+
name="sickittit-learno",
|
|
5
|
+
version="3.0.1",
|
|
6
|
+
author="Anant Prajapati",
|
|
7
|
+
description="AI Practicals cheatsheet (print code + fetch ready-made data files)",
|
|
8
|
+
packages=find_packages(),
|
|
9
|
+
python_requires=">=3.9",
|
|
10
|
+
entry_points={
|
|
11
|
+
"console_scripts": [
|
|
12
|
+
"sickittit-learno=sickittit_learno.practs:main",
|
|
13
|
+
"sickittit_learno=sickittit_learno.practs:main",
|
|
14
|
+
],
|
|
15
|
+
},
|
|
16
|
+
include_package_data=True,
|
|
17
|
+
package_data={
|
|
18
|
+
"sickittit_learno.practicals": ["*.py"],
|
|
19
|
+
"sickittit_learno.data": ["*.csv"],
|
|
20
|
+
},
|
|
21
|
+
install_requires=[],
|
|
22
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Hours,Attendance,Result
|
|
2
|
+
1,55,Fail
|
|
3
|
+
2,60,Fail
|
|
4
|
+
2,50,Fail
|
|
5
|
+
3,65,Fail
|
|
6
|
+
3,70,Fail
|
|
7
|
+
4,60,Fail
|
|
8
|
+
4,75,Pass
|
|
9
|
+
5,80,Pass
|
|
10
|
+
5,72,Pass
|
|
11
|
+
6,78,Pass
|
|
12
|
+
6,85,Pass
|
|
13
|
+
7,88,Pass
|
|
14
|
+
7,80,Pass
|
|
15
|
+
8,90,Pass
|
|
16
|
+
8,95,Pass
|
|
17
|
+
9,92,Pass
|
|
18
|
+
9,98,Pass
|
|
19
|
+
10,99,Pass
|
|
20
|
+
2,45,Fail
|
|
21
|
+
3,58,Fail
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 1: Simple Reflex Agent — Table-Driven Vacuum Cleaner Agent
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p01_reflex_vacuum.py
|
|
7
|
+
# NOTE: this program asks for keyboard input while it runs.
|
|
8
|
+
# ============================================================
|
|
9
|
+
|
|
10
|
+
rooms = {}
|
|
11
|
+
rooms['A'] = input("Enter status of Room A (Clean/Dirty): ")
|
|
12
|
+
rooms['B'] = input("Enter status of Room B (Clean/Dirty): ")
|
|
13
|
+
|
|
14
|
+
if rooms['A'] == "Clean" and rooms['B'] == "Clean":
|
|
15
|
+
print("\nAll rooms are already clean. Task completed.")
|
|
16
|
+
else:
|
|
17
|
+
if rooms['A'] == "Dirty":
|
|
18
|
+
print("\nRoom A is Dirty")
|
|
19
|
+
print("Action: Suck")
|
|
20
|
+
rooms['A'] = "Clean"
|
|
21
|
+
print("Room A cleaned")
|
|
22
|
+
else:
|
|
23
|
+
print("\nRoom A is already Clean")
|
|
24
|
+
|
|
25
|
+
if rooms['B'] == "Dirty":
|
|
26
|
+
print("\nRoom B is Dirty")
|
|
27
|
+
print("Action: Suck")
|
|
28
|
+
rooms['B'] = "Clean"
|
|
29
|
+
print("Room B cleaned")
|
|
30
|
+
else:
|
|
31
|
+
print("\nRoom B is already Clean")
|
|
32
|
+
|
|
33
|
+
if rooms['A'] == "Clean" and rooms['B'] == "Clean":
|
|
34
|
+
print("\nAll rooms are clean. Task completed.")
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 2: BFS — 8-Puzzle Solver
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p02_bfs_8puzzle.py
|
|
7
|
+
# ============================================================
|
|
8
|
+
|
|
9
|
+
from collections import deque
|
|
10
|
+
|
|
11
|
+
def print_state(state):
|
|
12
|
+
for i in range(0, 9, 3):
|
|
13
|
+
print(state[i], state[i+1], state[i+2])
|
|
14
|
+
print()
|
|
15
|
+
|
|
16
|
+
def get_blank_index(state):
|
|
17
|
+
return state.index(0)
|
|
18
|
+
|
|
19
|
+
def get_neighbors(state):
|
|
20
|
+
neighbors = []
|
|
21
|
+
blank_index = state.index(0)
|
|
22
|
+
|
|
23
|
+
moves = {
|
|
24
|
+
"Up": -3,
|
|
25
|
+
"Down": 3,
|
|
26
|
+
"Left": -1,
|
|
27
|
+
"Right": 1
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
for move, position_change in moves.items():
|
|
31
|
+
if move == "Up" and blank_index < 3:
|
|
32
|
+
continue
|
|
33
|
+
if move == "Down" and blank_index > 5:
|
|
34
|
+
continue
|
|
35
|
+
if move == "Left" and blank_index % 3 == 0:
|
|
36
|
+
continue
|
|
37
|
+
if move == "Right" and blank_index % 3 == 2:
|
|
38
|
+
continue
|
|
39
|
+
|
|
40
|
+
new_index = blank_index + position_change
|
|
41
|
+
|
|
42
|
+
new_state = list(state)
|
|
43
|
+
new_state[blank_index], new_state[new_index] = new_state[new_index], new_state[blank_index]
|
|
44
|
+
neighbors.append((tuple(new_state), move))
|
|
45
|
+
|
|
46
|
+
return neighbors
|
|
47
|
+
|
|
48
|
+
def bfs(initial_state, goal_state):
|
|
49
|
+
queue = deque()
|
|
50
|
+
queue.append((initial_state, []))
|
|
51
|
+
visited = set()
|
|
52
|
+
visited.add(initial_state)
|
|
53
|
+
|
|
54
|
+
while queue:
|
|
55
|
+
current_state, path = queue.popleft()
|
|
56
|
+
|
|
57
|
+
if current_state == goal_state:
|
|
58
|
+
return path
|
|
59
|
+
|
|
60
|
+
for neighbor, move in get_neighbors(current_state):
|
|
61
|
+
if neighbor not in visited:
|
|
62
|
+
visited.add(neighbor)
|
|
63
|
+
queue.append((neighbor, path + [(move, neighbor)]))
|
|
64
|
+
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
initial_state = (1, 2, 3,
|
|
68
|
+
4, 0, 6,
|
|
69
|
+
7, 5, 8)
|
|
70
|
+
goal_state = (1, 2, 3,
|
|
71
|
+
4, 5, 6,
|
|
72
|
+
7, 8, 0)
|
|
73
|
+
|
|
74
|
+
print("Initial State:")
|
|
75
|
+
print_state(initial_state)
|
|
76
|
+
|
|
77
|
+
print("Goal State:")
|
|
78
|
+
print_state(goal_state)
|
|
79
|
+
|
|
80
|
+
solution = bfs(initial_state, goal_state)
|
|
81
|
+
|
|
82
|
+
if solution:
|
|
83
|
+
print("Shortest sequence of moves:")
|
|
84
|
+
current_step = 1
|
|
85
|
+
for move, state in solution:
|
|
86
|
+
print(f"Step {current_step} - Move: {move}")
|
|
87
|
+
print_state(state)
|
|
88
|
+
current_step += 1
|
|
89
|
+
print("Goal reached successfully.")
|
|
90
|
+
print("Total number of moves:", len(solution))
|
|
91
|
+
else:
|
|
92
|
+
print("No solution found.")
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 3: DFS — Water Jug Problem (4L and 3L jugs)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p03_dfs_waterjug.py
|
|
7
|
+
# NOTE: this program asks for keyboard input while it runs.
|
|
8
|
+
# ============================================================
|
|
9
|
+
|
|
10
|
+
j1 = int(input("Enter capacity of Jug 1: "))
|
|
11
|
+
j2 = int(input("Enter capacity of Jug 2: "))
|
|
12
|
+
goal = int(input("Enter target amount: "))
|
|
13
|
+
|
|
14
|
+
visited = set()
|
|
15
|
+
path = []
|
|
16
|
+
|
|
17
|
+
def dfs(x, y):
|
|
18
|
+
if (x, y) in visited:
|
|
19
|
+
return False
|
|
20
|
+
visited.add((x, y))
|
|
21
|
+
path.append((x, y))
|
|
22
|
+
|
|
23
|
+
if x == goal or y == goal:
|
|
24
|
+
print("\nGoal Achieved Successfully!")
|
|
25
|
+
print("Solution Path:")
|
|
26
|
+
for state in path:
|
|
27
|
+
print(state)
|
|
28
|
+
return True
|
|
29
|
+
|
|
30
|
+
next_states = [
|
|
31
|
+
(j1, y),
|
|
32
|
+
(x, j2),
|
|
33
|
+
(0, y),
|
|
34
|
+
(x, 0),
|
|
35
|
+
(x - min(x, j2 - y), y + min(x, j2 - y)),
|
|
36
|
+
(x + min(y, j1 - x), y - min(y, j1 - x)),
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
for (nx, ny) in next_states:
|
|
40
|
+
if dfs(nx, ny):
|
|
41
|
+
return True
|
|
42
|
+
|
|
43
|
+
path.pop()
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
if not dfs(0, 0):
|
|
47
|
+
print("No solution found")
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 4: Uniform Cost Search (UCS) — Weighted City Graph
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p04_ucs_citygraph.py
|
|
7
|
+
# ============================================================
|
|
8
|
+
|
|
9
|
+
import heapq
|
|
10
|
+
|
|
11
|
+
graph = {
|
|
12
|
+
'Mumbai': [('Pune', 150), ('Hyderabad', 710)],
|
|
13
|
+
'Pune': [('Mumbai', 150), ('Bangalore', 840)],
|
|
14
|
+
'Hyderabad': [('Mumbai', 710), ('Bangalore', 570)],
|
|
15
|
+
'Bangalore': []
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
def ucs(start, goal):
|
|
19
|
+
queue = [(0, start, [start])]
|
|
20
|
+
visited = []
|
|
21
|
+
|
|
22
|
+
while queue:
|
|
23
|
+
cost, city, path = heapq.heappop(queue)
|
|
24
|
+
|
|
25
|
+
if city == goal:
|
|
26
|
+
return cost, path
|
|
27
|
+
|
|
28
|
+
if city not in visited:
|
|
29
|
+
visited.append(city)
|
|
30
|
+
for neighbor, distance in graph[city]:
|
|
31
|
+
if neighbor not in visited:
|
|
32
|
+
heapq.heappush(queue, (cost + distance, neighbor, path + [neighbor]))
|
|
33
|
+
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
cost, path = ucs("Mumbai", "Bangalore")
|
|
37
|
+
|
|
38
|
+
print("Least-cost path:")
|
|
39
|
+
print("Path:", " -> ".join(path))
|
|
40
|
+
print("Total Distance:", cost, "km")
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 5: Greedy Best-First Search — 8-Puzzle (Manhattan Heuristic)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p05_greedy_8puzzle.py
|
|
7
|
+
# ============================================================
|
|
8
|
+
|
|
9
|
+
import heapq
|
|
10
|
+
|
|
11
|
+
def heuristic(state, goal):
|
|
12
|
+
distance = 0
|
|
13
|
+
for num in range(1, 9):
|
|
14
|
+
current = state.index(num)
|
|
15
|
+
target = goal.index(num)
|
|
16
|
+
x1, y1 = current // 3, current % 3
|
|
17
|
+
x2, y2 = target // 3, target % 3
|
|
18
|
+
distance += abs(x1 - x2) + abs(y1 - y2)
|
|
19
|
+
return distance
|
|
20
|
+
|
|
21
|
+
def print_state(state):
|
|
22
|
+
for i in range(0, 9, 3):
|
|
23
|
+
print(state[i], state[i+1], state[i+2])
|
|
24
|
+
print()
|
|
25
|
+
def get_neighbors(state):
|
|
26
|
+
neighbors = []
|
|
27
|
+
blank = state.index(0)
|
|
28
|
+
moves = [-3, 3, -1, 1]
|
|
29
|
+
|
|
30
|
+
for move in moves:
|
|
31
|
+
new = blank + move
|
|
32
|
+
if new < 0 or new >= 9:
|
|
33
|
+
continue
|
|
34
|
+
if blank % 3 == 0 and move == -1:
|
|
35
|
+
continue
|
|
36
|
+
if blank % 3 == 2 and move == 1:
|
|
37
|
+
continue
|
|
38
|
+
|
|
39
|
+
new_state = list(state)
|
|
40
|
+
new_state[blank], new_state[new] = new_state[new], new_state[blank]
|
|
41
|
+
neighbors.append(tuple(new_state))
|
|
42
|
+
|
|
43
|
+
return neighbors
|
|
44
|
+
|
|
45
|
+
def greedy(initial, goal):
|
|
46
|
+
queue = []
|
|
47
|
+
heapq.heappush(queue, (heuristic(initial, goal), initial, []))
|
|
48
|
+
visited = set()
|
|
49
|
+
|
|
50
|
+
while queue:
|
|
51
|
+
h, state, path = heapq.heappop(queue)
|
|
52
|
+
|
|
53
|
+
if state == goal:
|
|
54
|
+
return path + [state]
|
|
55
|
+
|
|
56
|
+
if state not in visited:
|
|
57
|
+
visited.add(state)
|
|
58
|
+
for next_state in get_neighbors(state):
|
|
59
|
+
heapq.heappush(queue, (heuristic(next_state, goal), next_state, path + [state]))
|
|
60
|
+
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
initial = (1, 2, 3,
|
|
64
|
+
7, 5, 8,
|
|
65
|
+
4, 0, 6)
|
|
66
|
+
goal = (1, 2, 3,
|
|
67
|
+
4, 5, 6,
|
|
68
|
+
7, 8, 0)
|
|
69
|
+
|
|
70
|
+
print("Initial State:")
|
|
71
|
+
print_state(initial)
|
|
72
|
+
print("Goal State:")
|
|
73
|
+
print_state(goal)
|
|
74
|
+
|
|
75
|
+
solution = greedy(initial, goal)
|
|
76
|
+
|
|
77
|
+
if solution:
|
|
78
|
+
for step, state in enumerate(solution):
|
|
79
|
+
print(f"Step {step}")
|
|
80
|
+
print_state(state)
|
|
81
|
+
print("Goal reached successfully.")
|
|
82
|
+
else:
|
|
83
|
+
print("No solution found.")
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 6: A* Search — 8-Puzzle (Manhattan Heuristic)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p06_astar_8puzzle.py
|
|
7
|
+
# ============================================================
|
|
8
|
+
|
|
9
|
+
import heapq
|
|
10
|
+
|
|
11
|
+
def heuristic(state, goal):
|
|
12
|
+
distance = 0
|
|
13
|
+
for num in range(1, 9):
|
|
14
|
+
current = state.index(num)
|
|
15
|
+
target = goal.index(num)
|
|
16
|
+
x1, y1 = current // 3, current % 3
|
|
17
|
+
x2, y2 = target // 3, target % 3
|
|
18
|
+
distance += abs(x1 - x2) + abs(y1 - y2)
|
|
19
|
+
return distance
|
|
20
|
+
|
|
21
|
+
def print_state(state):
|
|
22
|
+
for i in range(0, 9, 3):
|
|
23
|
+
print(state[i], state[i+1], state[i+2])
|
|
24
|
+
print()
|
|
25
|
+
|
|
26
|
+
def get_neighbors(state):
|
|
27
|
+
neighbors = []
|
|
28
|
+
blank = state.index(0)
|
|
29
|
+
moves = [-3, 3, -1, 1]
|
|
30
|
+
|
|
31
|
+
for move in moves:
|
|
32
|
+
new = blank + move
|
|
33
|
+
if new < 0 or new >= 9:
|
|
34
|
+
continue
|
|
35
|
+
if blank % 3 == 0 and move == -1:
|
|
36
|
+
continue
|
|
37
|
+
if blank % 3 == 2 and move == 1:
|
|
38
|
+
continue
|
|
39
|
+
|
|
40
|
+
new_state = list(state)
|
|
41
|
+
new_state[blank], new_state[new] = new_state[new], new_state[blank]
|
|
42
|
+
neighbors.append(tuple(new_state))
|
|
43
|
+
|
|
44
|
+
return neighbors
|
|
45
|
+
|
|
46
|
+
def astar(initial, goal):
|
|
47
|
+
queue = []
|
|
48
|
+
heapq.heappush(queue, (heuristic(initial, goal), 0, initial, [initial]))
|
|
49
|
+
visited = set()
|
|
50
|
+
|
|
51
|
+
while queue:
|
|
52
|
+
f, g, state, path = heapq.heappop(queue)
|
|
53
|
+
|
|
54
|
+
if state == goal:
|
|
55
|
+
return path
|
|
56
|
+
|
|
57
|
+
if state not in visited:
|
|
58
|
+
visited.add(state)
|
|
59
|
+
for next_state in get_neighbors(state):
|
|
60
|
+
if next_state not in visited:
|
|
61
|
+
new_g = g + 1
|
|
62
|
+
new_f = new_g + heuristic(next_state, goal)
|
|
63
|
+
heapq.heappush(queue, (new_f, new_g, next_state, path + [next_state]))
|
|
64
|
+
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
initial = (1, 2, 3,
|
|
68
|
+
7, 5, 8,
|
|
69
|
+
4, 0, 6)
|
|
70
|
+
goal = (1, 2, 3,
|
|
71
|
+
4, 5, 6,
|
|
72
|
+
7, 8, 0)
|
|
73
|
+
|
|
74
|
+
print("Initial State:")
|
|
75
|
+
print_state(initial)
|
|
76
|
+
print("Goal State:")
|
|
77
|
+
print_state(goal)
|
|
78
|
+
|
|
79
|
+
solution = astar(initial, goal)
|
|
80
|
+
|
|
81
|
+
if solution:
|
|
82
|
+
print("Shortest Path using A* Search:")
|
|
83
|
+
step = 1
|
|
84
|
+
for state in solution[1:]:
|
|
85
|
+
print(f"Step {step}")
|
|
86
|
+
print_state(state)
|
|
87
|
+
step += 1
|
|
88
|
+
print("Goal reached successfully.")
|
|
89
|
+
print("Total number of moves:", len(solution) - 1)
|
|
90
|
+
else:
|
|
91
|
+
print("No solution found.")
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 7: A* Search — Weighted Graph (Arad to Bucharest, Straight-Line Heuristic)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p07_astar_romania.py
|
|
7
|
+
# ============================================================
|
|
8
|
+
|
|
9
|
+
import heapq
|
|
10
|
+
|
|
11
|
+
graph = {
|
|
12
|
+
'Arad': [('Zerind', 75), ('Sibiu', 140), ('Timisoara', 118)],
|
|
13
|
+
'Zerind': [('Arad', 75), ('Oradea', 71)],
|
|
14
|
+
'Oradea': [('Zerind', 71), ('Sibiu', 151)],
|
|
15
|
+
'Sibiu': [('Arad', 140), ('Oradea', 151), ('Fagaras', 99), ('Rimnicu Vilcea', 80)],
|
|
16
|
+
'Timisoara': [('Arad', 118), ('Lugoj', 111)],
|
|
17
|
+
'Lugoj': [('Timisoara', 111), ('Mehadia', 70)],
|
|
18
|
+
'Mehadia': [('Lugoj', 70), ('Drobeta', 75)],
|
|
19
|
+
'Drobeta': [('Mehadia', 75), ('Craiova', 120)],
|
|
20
|
+
'Craiova': [('Drobeta', 120), ('Rimnicu Vilcea', 146), ('Pitesti', 138)],
|
|
21
|
+
'Rimnicu Vilcea': [('Sibiu', 80), ('Craiova', 146), ('Pitesti', 97)],
|
|
22
|
+
'Fagaras': [('Sibiu', 99), ('Bucharest', 211)],
|
|
23
|
+
'Pitesti': [('Rimnicu Vilcea', 97), ('Craiova', 138), ('Bucharest', 101)],
|
|
24
|
+
'Bucharest': []
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
heuristic = {
|
|
28
|
+
'Arad': 366, 'Zerind': 374, 'Oradea': 380, 'Sibiu': 253,
|
|
29
|
+
'Timisoara': 329, 'Lugoj': 244, 'Mehadia': 241, 'Drobeta': 242,
|
|
30
|
+
'Craiova': 160, 'Rimnicu Vilcea': 193, 'Fagaras': 176,
|
|
31
|
+
'Pitesti': 100, 'Bucharest': 0
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
def astar(start, goal):
|
|
35
|
+
queue = [(heuristic[start], 0, start, [start])]
|
|
36
|
+
visited = set()
|
|
37
|
+
|
|
38
|
+
while queue:
|
|
39
|
+
f, g_cost, city, path = heapq.heappop(queue)
|
|
40
|
+
|
|
41
|
+
if city == goal:
|
|
42
|
+
return g_cost, path
|
|
43
|
+
|
|
44
|
+
if city not in visited:
|
|
45
|
+
visited.add(city)
|
|
46
|
+
for neighbor, distance in graph[city]:
|
|
47
|
+
if neighbor not in visited:
|
|
48
|
+
new_g = g_cost + distance
|
|
49
|
+
new_f = new_g + heuristic[neighbor]
|
|
50
|
+
heapq.heappush(queue, (new_f, new_g, neighbor, path + [neighbor]))
|
|
51
|
+
|
|
52
|
+
return None, []
|
|
53
|
+
|
|
54
|
+
cost, path = astar('Arad', 'Bucharest')
|
|
55
|
+
|
|
56
|
+
print("Shortest path using A* Search:")
|
|
57
|
+
print("Path:", " -> ".join(path))
|
|
58
|
+
print("Total Cost:", cost)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 8: Bayes' Rule — Medical Test Probability
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Run this file:
|
|
6
|
+
# python p08_bayes_medical.py
|
|
7
|
+
# ============================================================
|
|
8
|
+
|
|
9
|
+
P_D = 0.01
|
|
10
|
+
|
|
11
|
+
P_NotD = 1 - P_D
|
|
12
|
+
|
|
13
|
+
P_Pos_D = 0.99
|
|
14
|
+
|
|
15
|
+
P_Pos_NotD = 0.05
|
|
16
|
+
|
|
17
|
+
P_D_Pos = (P_Pos_D * P_D) / ((P_Pos_D * P_D) + (P_Pos_NotD * P_NotD))
|
|
18
|
+
|
|
19
|
+
print("Probability that person actually has disease:")
|
|
20
|
+
print(round(P_D_Pos * 100, 2), "%")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 9: Naive Bayes' Classification — Weather Dataset
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pandas scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p09_naivebayes_weather.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from sklearn.preprocessing import LabelEncoder
|
|
13
|
+
from sklearn.naive_bayes import GaussianNB
|
|
14
|
+
|
|
15
|
+
data = {
|
|
16
|
+
'Outlook': ['Sunny','Sunny','Overcast','Rainy','Rainy','Rainy','Overcast','Sunny','Sunny','Rainy'],
|
|
17
|
+
'Temperature': ['Hot','Hot','Hot','Mild','Cool','Cool','Cool','Mild','Cool','Mild'],
|
|
18
|
+
'Humidity': ['High','High','High','High','Normal','Normal','Normal','High','Normal','Normal'],
|
|
19
|
+
'Windy': ['False','True','False','False','False','True','True','False','False','False'],
|
|
20
|
+
'Play': ['No','No','Yes','Yes','Yes','No','Yes','No','Yes','Yes']
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
df = pd.DataFrame(data)
|
|
24
|
+
|
|
25
|
+
le = LabelEncoder()
|
|
26
|
+
for col in df.columns:
|
|
27
|
+
df[col] = le.fit_transform(df[col])
|
|
28
|
+
|
|
29
|
+
X = df[['Outlook','Temperature','Humidity','Windy']]
|
|
30
|
+
y = df['Play']
|
|
31
|
+
|
|
32
|
+
model = GaussianNB()
|
|
33
|
+
model.fit(X, y)
|
|
34
|
+
|
|
35
|
+
test = pd.DataFrame([[2, 0, 0, 0]],
|
|
36
|
+
columns=['Outlook', 'Temperature', 'Humidity', 'Windy'])
|
|
37
|
+
|
|
38
|
+
prediction = model.predict(test)
|
|
39
|
+
|
|
40
|
+
if prediction[0] == 1:
|
|
41
|
+
print("Prediction: Yes, we can play")
|
|
42
|
+
else:
|
|
43
|
+
print("Prediction: No, we cannot play")
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 10: Bayesian Network (Burglary–Alarm) with pgmpy
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pgmpy
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p10_bayesnet_burglary.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from pgmpy.models import DiscreteBayesianNetwork
|
|
12
|
+
from pgmpy.factors.discrete import TabularCPD
|
|
13
|
+
from pgmpy.inference import VariableElimination
|
|
14
|
+
|
|
15
|
+
model = DiscreteBayesianNetwork([
|
|
16
|
+
("Burglary", "Alarm"),
|
|
17
|
+
("Earthquake", "Alarm"),
|
|
18
|
+
("Alarm", "JohnCalls"),
|
|
19
|
+
("Alarm", "MaryCalls")
|
|
20
|
+
])
|
|
21
|
+
|
|
22
|
+
cpd_burglary = TabularCPD(
|
|
23
|
+
variable="Burglary",
|
|
24
|
+
variable_card=2,
|
|
25
|
+
values=[[0.999], [0.001]],
|
|
26
|
+
state_names={"Burglary": ["False", "True"]}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
cpd_earthquake = TabularCPD(
|
|
30
|
+
variable="Earthquake",
|
|
31
|
+
variable_card=2,
|
|
32
|
+
values=[[0.998], [0.002]],
|
|
33
|
+
state_names={"Earthquake": ["False", "True"]}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
cpd_alarm = TabularCPD(
|
|
37
|
+
variable="Alarm",
|
|
38
|
+
variable_card=2,
|
|
39
|
+
values=[
|
|
40
|
+
[0.999, 0.71, 0.06, 0.05],
|
|
41
|
+
[0.001, 0.29, 0.94, 0.95]
|
|
42
|
+
],
|
|
43
|
+
evidence=["Burglary", "Earthquake"],
|
|
44
|
+
evidence_card=[2, 2],
|
|
45
|
+
state_names={
|
|
46
|
+
"Alarm": ["False", "True"],
|
|
47
|
+
"Burglary": ["False", "True"],
|
|
48
|
+
"Earthquake": ["False", "True"]
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
cpd_john = TabularCPD(
|
|
53
|
+
variable="JohnCalls",
|
|
54
|
+
variable_card=2,
|
|
55
|
+
values=[[0.95, 0.10], [0.05, 0.90]],
|
|
56
|
+
evidence=["Alarm"],
|
|
57
|
+
evidence_card=[2],
|
|
58
|
+
state_names={"JohnCalls": ["False", "True"], "Alarm": ["False", "True"]}
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
cpd_mary = TabularCPD(
|
|
62
|
+
variable="MaryCalls",
|
|
63
|
+
variable_card=2,
|
|
64
|
+
values=[[0.99, 0.30], [0.01, 0.70]],
|
|
65
|
+
evidence=["Alarm"],
|
|
66
|
+
evidence_card=[2],
|
|
67
|
+
state_names={"MaryCalls": ["False", "True"], "Alarm": ["False", "True"]}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
model.add_cpds(cpd_burglary, cpd_earthquake, cpd_alarm, cpd_john, cpd_mary)
|
|
71
|
+
|
|
72
|
+
print("Is Bayesian Network valid?", model.check_model())
|
|
73
|
+
|
|
74
|
+
inference = VariableElimination(model)
|
|
75
|
+
|
|
76
|
+
print("\nProbability of Burglary given JohnCalls=True and MaryCalls=True:")
|
|
77
|
+
result = inference.query(
|
|
78
|
+
variables=["Burglary"],
|
|
79
|
+
evidence={"JohnCalls": "True", "MaryCalls": "True"}
|
|
80
|
+
)
|
|
81
|
+
print(result)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 11: Bayesian Network — Posterior Probability P(Burglary | Alarm = True)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pgmpy
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p11_bayesnet_posterior.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from pgmpy.models import DiscreteBayesianNetwork
|
|
12
|
+
from pgmpy.factors.discrete import TabularCPD
|
|
13
|
+
from pgmpy.inference import VariableElimination
|
|
14
|
+
|
|
15
|
+
model = DiscreteBayesianNetwork([
|
|
16
|
+
("Burglary", "Alarm"),
|
|
17
|
+
("Earthquake", "Alarm")
|
|
18
|
+
])
|
|
19
|
+
|
|
20
|
+
cpd_burglary = TabularCPD(
|
|
21
|
+
variable="Burglary",
|
|
22
|
+
variable_card=2,
|
|
23
|
+
values=[[0.999], [0.001]],
|
|
24
|
+
state_names={"Burglary": ["False", "True"]}
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
cpd_earthquake = TabularCPD(
|
|
28
|
+
variable="Earthquake",
|
|
29
|
+
variable_card=2,
|
|
30
|
+
values=[[0.998], [0.002]],
|
|
31
|
+
state_names={"Earthquake": ["False", "True"]}
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
cpd_alarm = TabularCPD(
|
|
35
|
+
variable="Alarm",
|
|
36
|
+
variable_card=2,
|
|
37
|
+
values=[
|
|
38
|
+
[0.999, 0.71, 0.06, 0.05],
|
|
39
|
+
[0.001, 0.29, 0.94, 0.95]
|
|
40
|
+
],
|
|
41
|
+
evidence=["Burglary", "Earthquake"],
|
|
42
|
+
evidence_card=[2, 2],
|
|
43
|
+
state_names={
|
|
44
|
+
"Alarm": ["False", "True"],
|
|
45
|
+
"Burglary": ["False", "True"],
|
|
46
|
+
"Earthquake": ["False", "True"]
|
|
47
|
+
}
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
model.add_cpds(cpd_burglary, cpd_earthquake, cpd_alarm)
|
|
51
|
+
|
|
52
|
+
print("Is Bayesian Network valid?", model.check_model())
|
|
53
|
+
|
|
54
|
+
inference = VariableElimination(model)
|
|
55
|
+
|
|
56
|
+
print("\nPosterior Probability:")
|
|
57
|
+
result = inference.query(
|
|
58
|
+
variables=["Burglary"],
|
|
59
|
+
evidence={"Alarm": "True"}
|
|
60
|
+
)
|
|
61
|
+
print(result)
|
|
62
|
+
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.1: Machine Learning Workflow — CSV Dataset (student.csv)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pandas scikit-learn
|
|
7
|
+
# 2. Get the data file (one line, from this library):
|
|
8
|
+
# from sickittit_learno import get_data; get_data("student.csv")
|
|
9
|
+
# 3. Run this file:
|
|
10
|
+
# python p12_1_ml_student_csv.py
|
|
11
|
+
# ============================================================
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
from sklearn.preprocessing import LabelEncoder
|
|
15
|
+
from sklearn.preprocessing import StandardScaler
|
|
16
|
+
from sklearn.model_selection import train_test_split
|
|
17
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
18
|
+
from sklearn.metrics import accuracy_score
|
|
19
|
+
|
|
20
|
+
data = pd.read_csv("student.csv")
|
|
21
|
+
print("Dataset:")
|
|
22
|
+
print(data)
|
|
23
|
+
|
|
24
|
+
le = LabelEncoder()
|
|
25
|
+
data["Result"] = le.fit_transform(data["Result"])
|
|
26
|
+
|
|
27
|
+
X = data[["Hours", "Attendance"]]
|
|
28
|
+
y = data["Result"]
|
|
29
|
+
|
|
30
|
+
scaler = StandardScaler()
|
|
31
|
+
X = scaler.fit_transform(X)
|
|
32
|
+
|
|
33
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
34
|
+
X, y, test_size=0.3, random_state=1)
|
|
35
|
+
|
|
36
|
+
model = KNeighborsClassifier()
|
|
37
|
+
model.fit(X_train, y_train)
|
|
38
|
+
|
|
39
|
+
train_pred = model.predict(X_train)
|
|
40
|
+
test_pred = model.predict(X_test)
|
|
41
|
+
|
|
42
|
+
print("\nTraining Accuracy:", accuracy_score(y_train, train_pred) * 100)
|
|
43
|
+
print("Testing Accuracy:", accuracy_score(y_test, test_pred) * 100)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.2: Linear Regression — Student Study Hours Dataset (student_marks.csv)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pandas scikit-learn
|
|
7
|
+
# 2. Get the data file (one line, from this library):
|
|
8
|
+
# from sickittit_learno import get_data; get_data("student_marks.csv")
|
|
9
|
+
# 3. Run this file:
|
|
10
|
+
# python p12_2_linreg_marks.py
|
|
11
|
+
# ============================================================
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
from sklearn.model_selection import train_test_split
|
|
15
|
+
from sklearn.linear_model import LinearRegression
|
|
16
|
+
|
|
17
|
+
data = pd.read_csv("student_marks.csv")
|
|
18
|
+
|
|
19
|
+
X = data[["Hours"]]
|
|
20
|
+
y = data["Marks"]
|
|
21
|
+
|
|
22
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
23
|
+
X, y, test_size=0.3, random_state=1)
|
|
24
|
+
|
|
25
|
+
model = LinearRegression()
|
|
26
|
+
model.fit(X_train, y_train)
|
|
27
|
+
|
|
28
|
+
print("Training Accuracy:", round(model.score(X_train, y_train) * 100, 2))
|
|
29
|
+
print("Testing Accuracy:", round(model.score(X_test, y_test) * 100, 2))
|
|
30
|
+
|
|
31
|
+
new_data = pd.DataFrame([[11]], columns=["Hours"])
|
|
32
|
+
pred = model.predict(new_data)
|
|
33
|
+
print("Predicted Marks for 11 hours:", round(pred[0], 2))
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.3: Binary Classifier — MNIST Dataset (Digit 5 vs Not Digit 5)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p12_3_mnist_binary.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from sklearn.datasets import load_digits
|
|
12
|
+
from sklearn.model_selection import train_test_split
|
|
13
|
+
from sklearn.linear_model import LogisticRegression
|
|
14
|
+
|
|
15
|
+
digits = load_digits()
|
|
16
|
+
|
|
17
|
+
X = digits.data
|
|
18
|
+
y = (digits.target == 5)
|
|
19
|
+
|
|
20
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
21
|
+
X, y, test_size=0.3, random_state=1)
|
|
22
|
+
|
|
23
|
+
model = LogisticRegression(max_iter=1000)
|
|
24
|
+
model.fit(X_train, y_train)
|
|
25
|
+
|
|
26
|
+
print("Training Accuracy:", model.score(X_train, y_train) * 100)
|
|
27
|
+
print("Testing Accuracy:", model.score(X_test, y_test) * 100)
|
|
28
|
+
|
|
29
|
+
prediction = model.predict([X_test[0]])
|
|
30
|
+
if prediction[0]:
|
|
31
|
+
print("Digit is 5")
|
|
32
|
+
else:
|
|
33
|
+
print("Digit is not 5")
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.4: K-Fold Cross-Validation on a Classification Model (Iris + KNN)
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p12_4_kfold_iris.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from sklearn.datasets import load_iris
|
|
12
|
+
from sklearn.model_selection import cross_val_score
|
|
13
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
14
|
+
|
|
15
|
+
iris = load_iris()
|
|
16
|
+
X = iris.data
|
|
17
|
+
y = iris.target
|
|
18
|
+
|
|
19
|
+
model = KNeighborsClassifier()
|
|
20
|
+
|
|
21
|
+
scores = cross_val_score(model, X, y, cv=5)
|
|
22
|
+
|
|
23
|
+
print("Accuracy scores for each fold:")
|
|
24
|
+
print(scores)
|
|
25
|
+
print("Average Accuracy:", round(scores.mean() * 100, 2), "%")
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.5: Decision Tree Classifier — Iris Dataset
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p12_5_dtree_iris.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from sklearn.datasets import load_iris
|
|
12
|
+
from sklearn.model_selection import train_test_split
|
|
13
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
14
|
+
|
|
15
|
+
iris = load_iris()
|
|
16
|
+
X = iris.data
|
|
17
|
+
y = iris.target
|
|
18
|
+
|
|
19
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
20
|
+
X, y, test_size=0.3, random_state=1)
|
|
21
|
+
|
|
22
|
+
model = DecisionTreeClassifier()
|
|
23
|
+
|
|
24
|
+
model.fit(X_train, y_train)
|
|
25
|
+
|
|
26
|
+
print("Training Accuracy:", model.score(X_train, y_train) * 100)
|
|
27
|
+
print("Testing Accuracy:", model.score(X_test, y_test) * 100)
|
|
28
|
+
|
|
29
|
+
prediction = model.predict([X_test[0]])
|
|
30
|
+
print("Predicted Class:", prediction[0])
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.6: Decision Tree Regression — student_marks.csv
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pandas scikit-learn
|
|
7
|
+
# 2. Get the data file (one line, from this library):
|
|
8
|
+
# from sickittit_learno import get_data; get_data("student_marks.csv")
|
|
9
|
+
# 3. Run this file:
|
|
10
|
+
# python p12_6_dtree_reg_marks.py
|
|
11
|
+
# ============================================================
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
from sklearn.model_selection import train_test_split
|
|
15
|
+
from sklearn.tree import DecisionTreeRegressor
|
|
16
|
+
|
|
17
|
+
data = pd.read_csv("student_marks.csv")
|
|
18
|
+
|
|
19
|
+
X = data[["Hours"]]
|
|
20
|
+
y = data["Marks"]
|
|
21
|
+
|
|
22
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
23
|
+
X, y, test_size=0.3, random_state=1)
|
|
24
|
+
|
|
25
|
+
model = DecisionTreeRegressor()
|
|
26
|
+
|
|
27
|
+
model.fit(X_train, y_train)
|
|
28
|
+
|
|
29
|
+
print("Training Accuracy:", model.score(X_train, y_train) * 100)
|
|
30
|
+
print("Testing Accuracy:", model.score(X_test, y_test) * 100)
|
|
31
|
+
|
|
32
|
+
new_data = pd.DataFrame([[11]], columns=["Hours"])
|
|
33
|
+
prediction = model.predict(new_data)
|
|
34
|
+
print("Predicted Marks for 11 Hours:", prediction[0])
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.7: K-Nearest Neighbors (KNN) Classifier — Iris Dataset
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p12_7_knn_iris.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from sklearn.datasets import load_iris
|
|
12
|
+
from sklearn.model_selection import train_test_split
|
|
13
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
14
|
+
|
|
15
|
+
iris = load_iris()
|
|
16
|
+
X = iris.data
|
|
17
|
+
y = iris.target
|
|
18
|
+
|
|
19
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
20
|
+
X, y, test_size=0.3, random_state=1)
|
|
21
|
+
|
|
22
|
+
model = KNeighborsClassifier(n_neighbors=3)
|
|
23
|
+
|
|
24
|
+
model.fit(X_train, y_train)
|
|
25
|
+
|
|
26
|
+
print("Training Accuracy:", model.score(X_train, y_train) * 100)
|
|
27
|
+
print("Testing Accuracy:", model.score(X_test, y_test) * 100)
|
|
28
|
+
|
|
29
|
+
prediction = model.predict([X_test[0]])
|
|
30
|
+
print("Predicted Class:", prediction[0])
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 12.8: Multiclass Classification Using Decision Tree — Iris Dataset
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p12_8_multiclass_dtree_iris.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
from sklearn.datasets import load_iris
|
|
12
|
+
from sklearn.model_selection import train_test_split
|
|
13
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
14
|
+
|
|
15
|
+
iris = load_iris()
|
|
16
|
+
X = iris.data
|
|
17
|
+
y = iris.target
|
|
18
|
+
|
|
19
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
20
|
+
X, y, test_size=0.3, random_state=1)
|
|
21
|
+
|
|
22
|
+
model = DecisionTreeClassifier()
|
|
23
|
+
|
|
24
|
+
model.fit(X_train, y_train)
|
|
25
|
+
|
|
26
|
+
print("Training Accuracy:", model.score(X_train, y_train) * 100)
|
|
27
|
+
print("Testing Accuracy:", model.score(X_test, y_test) * 100)
|
|
28
|
+
|
|
29
|
+
prediction = model.predict([X_test[0]])
|
|
30
|
+
print("Predicted Class:", prediction[0])
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# ============================================================
|
|
2
|
+
# Practical 13: Ethics and Bias Analysis — Iris Dataset
|
|
3
|
+
# ------------------------------------------------------------
|
|
4
|
+
# HOW TO RUN
|
|
5
|
+
# 1. Install dependencies:
|
|
6
|
+
# pip install pandas scikit-learn
|
|
7
|
+
# 2. Run this file:
|
|
8
|
+
# python p13_ethics_bias_iris.py
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from sklearn.datasets import load_iris
|
|
13
|
+
|
|
14
|
+
iris = load_iris()
|
|
15
|
+
data = pd.DataFrame(iris.data, columns=iris.feature_names)
|
|
16
|
+
data['Class'] = iris.target
|
|
17
|
+
|
|
18
|
+
print("First 5 records:")
|
|
19
|
+
print(data.head())
|
|
20
|
+
|
|
21
|
+
print("Class Distribution:")
|
|
22
|
+
print(data['Class'].value_counts())
|
|
23
|
+
|
|
24
|
+
print("Missing Values:")
|
|
25
|
+
print(data.isnull().sum())
|
|
26
|
+
|
|
27
|
+
print("Bias Analysis:")
|
|
28
|
+
if data['Class'].value_counts().min() == data['Class'].value_counts().max():
|
|
29
|
+
print("Dataset is balanced.")
|
|
30
|
+
else:
|
|
31
|
+
print("Dataset is imbalanced.")
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""sickittit_learno — Anant's AI Practicals cheatsheet.
|
|
2
|
+
|
|
3
|
+
Quick use:
|
|
4
|
+
from sickittit_learno import list_all, show, get_data
|
|
5
|
+
|
|
6
|
+
list_all() # see every practical
|
|
7
|
+
show("p09_naivebayes_weather") # print a practical's code
|
|
8
|
+
get_data("student.csv") # drop a required data file into your folder
|
|
9
|
+
"""
|
|
10
|
+
from importlib import resources
|
|
11
|
+
import shutil
|
|
12
|
+
import sys
|
|
13
|
+
import os
|
|
14
|
+
|
|
15
|
+
PKG_PRACTICALS = "sickittit_learno.practicals"
|
|
16
|
+
PKG_DATA = "sickittit_learno.data"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _practical_files():
|
|
20
|
+
"""Return sorted list of practical stems (filenames without .py)."""
|
|
21
|
+
root = resources.files(PKG_PRACTICALS)
|
|
22
|
+
names = []
|
|
23
|
+
for entry in root.iterdir():
|
|
24
|
+
n = entry.name
|
|
25
|
+
if n.endswith(".py") and not n.startswith("__"):
|
|
26
|
+
names.append(n[:-3])
|
|
27
|
+
return sorted(names)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _resolve(name):
|
|
31
|
+
"""Match a user-typed name to an actual practical stem (forgiving)."""
|
|
32
|
+
name = name.strip()
|
|
33
|
+
if name.endswith(".py"):
|
|
34
|
+
name = name[:-3]
|
|
35
|
+
stems = _practical_files()
|
|
36
|
+
if name in stems:
|
|
37
|
+
return name
|
|
38
|
+
low = name.lower()
|
|
39
|
+
# exact case-insensitive
|
|
40
|
+
for s in stems:
|
|
41
|
+
if s.lower() == low:
|
|
42
|
+
return s
|
|
43
|
+
# match by the leading pNN / pNN_M token (e.g. "p9", "9", "12.1", "p12_1")
|
|
44
|
+
token = low.replace("practical", "").replace("prac", "").strip()
|
|
45
|
+
token = token.lstrip("p").replace(".", "_").strip("_ ")
|
|
46
|
+
for s in stems:
|
|
47
|
+
head = s[1:].split("_")
|
|
48
|
+
# head like ['01'] or ['12','1']
|
|
49
|
+
norm = "_".join(str(int(x)) if x.isdigit() else x for x in head[:2] if x.isdigit())
|
|
50
|
+
if token == norm or token == norm.replace("_", ""):
|
|
51
|
+
return s
|
|
52
|
+
# substring fallback
|
|
53
|
+
for s in stems:
|
|
54
|
+
if low in s.lower():
|
|
55
|
+
return s
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def list_all():
|
|
60
|
+
"""List all available practicals."""
|
|
61
|
+
stems = _practical_files()
|
|
62
|
+
print("Available practicals (use show(\"<name>\") to print the code):\n")
|
|
63
|
+
for s in stems:
|
|
64
|
+
print(" -", s)
|
|
65
|
+
print("\nData files (use get_data(\"<file>\")):")
|
|
66
|
+
for d in list_data():
|
|
67
|
+
print(" -", d)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def show(name):
|
|
71
|
+
"""Print the full code of a practical."""
|
|
72
|
+
stem = _resolve(name)
|
|
73
|
+
if stem is None:
|
|
74
|
+
print(f"'{name}' not found. Run list_all() to see the available names.")
|
|
75
|
+
return
|
|
76
|
+
code = (resources.files(PKG_PRACTICALS) / f"{stem}.py").read_text(encoding="utf-8")
|
|
77
|
+
print(f"--- {stem} ---\n")
|
|
78
|
+
print(code)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def list_data():
|
|
82
|
+
"""Return the names of bundled data files."""
|
|
83
|
+
root = resources.files(PKG_DATA)
|
|
84
|
+
return sorted(e.name for e in root.iterdir()
|
|
85
|
+
if not e.name.startswith("__") and e.name != "")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def get_data(name=None, dest="."):
|
|
89
|
+
"""Copy a bundled data file into `dest` (current folder by default).
|
|
90
|
+
|
|
91
|
+
get_data() -> copies ALL data files here
|
|
92
|
+
get_data("student.csv") -> copies just that one
|
|
93
|
+
"""
|
|
94
|
+
available = list_data()
|
|
95
|
+
targets = available if name is None else [name]
|
|
96
|
+
os.makedirs(dest, exist_ok=True)
|
|
97
|
+
done = []
|
|
98
|
+
for fn in targets:
|
|
99
|
+
if fn not in available:
|
|
100
|
+
print(f"'{fn}' is not a bundled data file. Available: {', '.join(available)}")
|
|
101
|
+
continue
|
|
102
|
+
src = resources.files(PKG_DATA) / fn
|
|
103
|
+
out = os.path.join(dest, fn)
|
|
104
|
+
with resources.as_file(src) as p:
|
|
105
|
+
shutil.copyfile(p, out)
|
|
106
|
+
done.append(os.path.abspath(out))
|
|
107
|
+
for p in done:
|
|
108
|
+
print("Saved:", p)
|
|
109
|
+
return done[0] if len(done) == 1 else done
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main():
|
|
113
|
+
args = sys.argv[1:]
|
|
114
|
+
if not args:
|
|
115
|
+
print("Usage: sickittit_learno [list | show <name> | data [<file>]]")
|
|
116
|
+
return
|
|
117
|
+
cmd = args[0]
|
|
118
|
+
if cmd == "list":
|
|
119
|
+
list_all()
|
|
120
|
+
elif cmd == "show":
|
|
121
|
+
if len(args) < 2:
|
|
122
|
+
print("Usage: sickittit_learno show <name>")
|
|
123
|
+
else:
|
|
124
|
+
show(args[1])
|
|
125
|
+
elif cmd == "data":
|
|
126
|
+
get_data(args[1] if len(args) > 1 else None)
|
|
127
|
+
else:
|
|
128
|
+
print(f"Unknown command: {cmd}")
|
|
129
|
+
print("Usage: sickittit_learno [list | show <name> | data [<file>]]")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
main()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sickittit-learno
|
|
3
|
+
Version: 3.0.1
|
|
4
|
+
Summary: AI Practicals cheatsheet (print code + fetch ready-made data files)
|
|
5
|
+
Home-page: UNKNOWN
|
|
6
|
+
Author: Anant Prajapati
|
|
7
|
+
License: UNKNOWN
|
|
8
|
+
Platform: UNKNOWN
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
|
|
11
|
+
UNKNOWN
|
|
12
|
+
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
MANIFEST.in
|
|
2
|
+
setup.cfg
|
|
3
|
+
setup.py
|
|
4
|
+
sickittit_learno/__init__.py
|
|
5
|
+
sickittit_learno/practs.py
|
|
6
|
+
sickittit_learno.egg-info/PKG-INFO
|
|
7
|
+
sickittit_learno.egg-info/SOURCES.txt
|
|
8
|
+
sickittit_learno.egg-info/dependency_links.txt
|
|
9
|
+
sickittit_learno.egg-info/entry_points.txt
|
|
10
|
+
sickittit_learno.egg-info/top_level.txt
|
|
11
|
+
sickittit_learno/data/__init__.py
|
|
12
|
+
sickittit_learno/data/student.csv
|
|
13
|
+
sickittit_learno/data/student_marks.csv
|
|
14
|
+
sickittit_learno/practicals/__init__.py
|
|
15
|
+
sickittit_learno/practicals/p01_reflex_vacuum.py
|
|
16
|
+
sickittit_learno/practicals/p02_bfs_8puzzle.py
|
|
17
|
+
sickittit_learno/practicals/p03_dfs_waterjug.py
|
|
18
|
+
sickittit_learno/practicals/p04_ucs_citygraph.py
|
|
19
|
+
sickittit_learno/practicals/p05_greedy_8puzzle.py
|
|
20
|
+
sickittit_learno/practicals/p06_astar_8puzzle.py
|
|
21
|
+
sickittit_learno/practicals/p07_astar_romania.py
|
|
22
|
+
sickittit_learno/practicals/p08_bayes_medical.py
|
|
23
|
+
sickittit_learno/practicals/p09_naivebayes_weather.py
|
|
24
|
+
sickittit_learno/practicals/p10_bayesnet_burglary.py
|
|
25
|
+
sickittit_learno/practicals/p11_bayesnet_posterior.py
|
|
26
|
+
sickittit_learno/practicals/p12_1_ml_student_csv.py
|
|
27
|
+
sickittit_learno/practicals/p12_2_linreg_marks.py
|
|
28
|
+
sickittit_learno/practicals/p12_3_mnist_binary.py
|
|
29
|
+
sickittit_learno/practicals/p12_4_kfold_iris.py
|
|
30
|
+
sickittit_learno/practicals/p12_5_dtree_iris.py
|
|
31
|
+
sickittit_learno/practicals/p12_6_dtree_reg_marks.py
|
|
32
|
+
sickittit_learno/practicals/p12_7_knn_iris.py
|
|
33
|
+
sickittit_learno/practicals/p12_8_multiclass_dtree_iris.py
|
|
34
|
+
sickittit_learno/practicals/p13_ethics_bias_iris.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sickittit_learno
|