aviml 0.1.0__py3-none-any.whl

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.
aviml/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Educational AI search and machine learning examples."""
aviml/alphabeta.py ADDED
@@ -0,0 +1,35 @@
1
+ def alphabeta(leaves, depth, alpha, beta, is_max):
2
+ # Base case: reached leaf node
3
+ if depth == 0 or len(leaves) == 1:
4
+ return leaves[0]
5
+
6
+ mid = len(leaves) // 2
7
+ children = [leaves[:mid], leaves[mid:]] # Split into left and right subtrees
8
+
9
+ if is_max:
10
+ val = float('-inf')
11
+ for child in children:
12
+ val = max(val, alphabeta(child, depth - 1, alpha, beta, False))
13
+ alpha = max(alpha, val)
14
+ if beta <= alpha:
15
+ break # Beta cut-off
16
+ return val
17
+ else:
18
+ val = float('inf')
19
+ for child in children:
20
+ val = min(val, alphabeta(child, depth - 1, alpha, beta, True))
21
+ beta = min(beta, val)
22
+ if beta <= alpha:
23
+ break # Alpha cut-off
24
+ return val
25
+
26
+
27
+ def main():
28
+ leaves = list(map(int, input("Enter leaf values: ").split()))
29
+ depth = int(input("Enter tree depth: "))
30
+
31
+ print("Optimal Value:", alphabeta(leaves, depth, float('-inf'), float('inf'), True))
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
aviml/hillclimbing.py ADDED
@@ -0,0 +1,24 @@
1
+ def hill_climbing(f, x, step=0.01, max_iter=1000):
2
+ for _ in range(max_iter):
3
+ # Look at left and right neighbors, pick the best one
4
+ best_next = max([x - step, x + step], key=f)
5
+
6
+ if f(best_next) > f(x):
7
+ x = best_next # Climb up
8
+ else:
9
+ break # Reached peak (local maxima)
10
+
11
+ return x, f(x)
12
+
13
+
14
+ def main():
15
+ expr = input("Enter function of x (e.g., -x**2 + 4*x): ")
16
+ f = lambda x: eval(expr)
17
+ start = float(input("Enter starting value: "))
18
+
19
+ x_max, y_max = hill_climbing(f, start)
20
+ print(f"Maxima at x = {x_max:.4f}, value = {y_max:.4f}")
21
+
22
+
23
+ if __name__ == "__main__":
24
+ main()
aviml/kmeans.py ADDED
@@ -0,0 +1,27 @@
1
+ import numpy as np
2
+ from sklearn.datasets import load_iris
3
+
4
+
5
+ def main():
6
+ import matplotlib.pyplot as plt
7
+
8
+ X = load_iris().data
9
+ k = 3
10
+
11
+ centroids = X[:k].copy()
12
+ for _ in range(100):
13
+ dists = np.linalg.norm(X[:, None] - centroids, axis=2)
14
+ labels = np.argmin(dists, axis=1)
15
+ centroids = np.array([X[labels == i].mean(axis=0) for i in range(k)])
16
+
17
+ # Plot clusters and centroids using the first two features.
18
+ plt.scatter(X[:, 0], X[:, 1], c=labels)
19
+ plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', c='red', s=100)
20
+ plt.xlabel('Sepal Length')
21
+ plt.ylabel('Sepal Width')
22
+ plt.title('K-Means on Iris')
23
+ plt.show()
24
+
25
+
26
+ if __name__ == "__main__":
27
+ main()
aviml/knn.py ADDED
@@ -0,0 +1,21 @@
1
+ import numpy as np
2
+ from sklearn.datasets import load_iris
3
+ from sklearn.model_selection import train_test_split
4
+
5
+
6
+ def knn(X_train, y_train, x, k=3):
7
+ dists = np.linalg.norm(X_train - x, axis=1) # Euclidean distance to all points
8
+ k_labels = y_train[np.argsort(dists)[:k]] # Labels of k nearest neighbors
9
+ return np.bincount(k_labels).argmax() # Most frequent class label
10
+
11
+
12
+ def main():
13
+ iris = load_iris()
14
+ X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
15
+
16
+ y_pred = [knn(X_train, y_train, x, k=3) for x in X_test]
17
+ print(f"Accuracy: {np.mean(y_pred == y_test):.2f}")
18
+
19
+
20
+ if __name__ == "__main__":
21
+ main()
@@ -0,0 +1,38 @@
1
+ import numpy as np
2
+ from sklearn.datasets import load_iris
3
+
4
+
5
+ def sigmoid(z):
6
+ return 1.0 / (1.0 + np.exp(-z))
7
+
8
+
9
+ def main():
10
+ # 1. Load Iris (only Setosa=0 and Versicolor=1)
11
+ iris = load_iris()
12
+ mask = iris.target < 2
13
+ X, y = iris.data[mask], iris.target[mask]
14
+
15
+ # 2. Manual Standardization (no StandardScaler)
16
+ mean, std = X.mean(axis=0), X.std(axis=0)
17
+ X_std = (X - mean) / std
18
+
19
+ # 3. Manual Logistic Regression
20
+ w = np.zeros(X.shape[1])
21
+ b = 0.0
22
+ lr = 0.1
23
+
24
+ for _ in range(1000):
25
+ h = sigmoid(np.dot(X_std, w) + b)
26
+ w -= lr * np.dot(X_std.T, (h - y)) / len(y)
27
+ b -= lr * np.mean(h - y)
28
+
29
+ # 4. Predict on User Input
30
+ user_x = np.array(list(map(float, input("Enter 4 features: ").split())))
31
+ user_std = (user_x - mean) / std
32
+ prob = sigmoid(np.dot(user_std, w) + b)
33
+
34
+ print("Versicolor" if prob >= 0.5 else "Setosa")
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
aviml/naivebyes.py ADDED
@@ -0,0 +1,29 @@
1
+ import numpy as np
2
+ from sklearn.datasets import load_iris
3
+ from sklearn.model_selection import train_test_split
4
+
5
+
6
+ # Predict: log-posterior = log(prior) + sum(log(Gaussian PDF))
7
+ def predict(x, classes, mean, var, priors):
8
+ log_pdf = -0.5 * np.log(2 * np.pi * var) - ((x - mean) ** 2) / (2 * var)
9
+ posteriors = np.log(priors) + np.sum(log_pdf, axis=1)
10
+ return classes[np.argmax(posteriors)]
11
+
12
+
13
+ def main():
14
+ iris = load_iris()
15
+ X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=1)
16
+
17
+ # Compute the mean, variance, and prior for each class.
18
+ classes = np.unique(y_train)
19
+ mean = np.array([X_train[y_train == c].mean(axis=0) for c in classes])
20
+ var = np.array([X_train[y_train == c].var(axis=0) for c in classes])
21
+ priors = np.array([np.mean(y_train == c) for c in classes])
22
+
23
+ y_pred = np.array([predict(x, classes, mean, var, priors) for x in X_test])
24
+ print(f"Accuracy: {np.mean(y_pred == y_test):.4f}")
25
+ print("Predictions:", iris.target_names[y_pred])
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()
aviml/puzzle8.py ADDED
@@ -0,0 +1,54 @@
1
+ import heapq
2
+
3
+ # 1. Heuristic: Count misplaced tiles (ignoring 0)
4
+ def h(state, goal):
5
+ return sum(1 for i in range(9) if state[i] != 0 and state[i] != goal[i])
6
+
7
+ # 2. Generate valid neighbor states
8
+ def get_neighbors(state):
9
+ neighbors = []
10
+ idx = state.index(0) # Find blank tile (0)
11
+ r, c = divmod(idx, 3) # Convert 1D index to (row, col)
12
+
13
+ for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
14
+ nr, nc = r + dr, c + dc
15
+ if 0 <= nr < 3 and 0 <= nc < 3:
16
+ new_idx = nr * 3 + nc
17
+ lst = list(state)
18
+ lst[idx], lst[new_idx] = lst[new_idx], lst[idx]
19
+ neighbors.append(tuple(lst))
20
+ return neighbors
21
+
22
+ # 3. A* Search
23
+ def a_star(start, goal):
24
+ pq = [(h(start, goal), 0, start, [start])] # (f_score, g_score, state, path)
25
+ visited = set()
26
+
27
+ while pq:
28
+ f, g, curr, path = heapq.heappop(pq)
29
+ if curr == goal:
30
+ return path
31
+ if curr in visited:
32
+ continue
33
+ visited.add(curr)
34
+
35
+ for nxt in get_neighbors(curr):
36
+ if nxt not in visited:
37
+ heapq.heappush(pq, (g + 1 + h(nxt, goal), g + 1, nxt, path + [nxt]))
38
+ return None
39
+
40
+
41
+ def main():
42
+ start = tuple(map(int, input("Start (9 numbers): ").split()))
43
+ goal = tuple(map(int, input("Goal (9 numbers): ").split()))
44
+
45
+ solution = a_star(start, goal)
46
+ if solution:
47
+ for step in solution:
48
+ print(step[:3], "\n", step[3:6], "\n", step[6:], "\n")
49
+ else:
50
+ print("No solution")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
aviml/ttt.py ADDED
@@ -0,0 +1,46 @@
1
+ board = [' '] * 9
2
+ WINS = [(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)]
3
+
4
+ def win(p):
5
+ return any(board[a] == board[b] == board[c] == p for a, b, c in WINS)
6
+
7
+ def show():
8
+ for i in range(0, 9, 3):
9
+ print(" | ".join(board[i:i+3]))
10
+ print("-" * 9)
11
+
12
+ def dfs(is_ai):
13
+ if win('X'): return 1
14
+ if win('O'): return -1
15
+ if ' ' not in board: return 0
16
+
17
+ best = float('-inf') if is_ai else float('inf')
18
+ for i in range(9):
19
+ if board[i] == ' ':
20
+ board[i] = 'X' if is_ai else 'O'
21
+ score = dfs(not is_ai)
22
+ board[i] = ' '
23
+ best = max(best, score) if is_ai else min(best, score)
24
+ return best
25
+
26
+
27
+ def main():
28
+ board[:] = [' '] * 9
29
+ while True:
30
+ show()
31
+ move = int(input("Enter position (0-8): "))
32
+ board[move] = 'O'
33
+ if win('O') or ' ' not in board: break
34
+
35
+ # AI finds best move
36
+ best_move = max((i for i in range(9) if board[i] == ' '),
37
+ key=lambda i: (board.__setitem__(i, 'X'), s := dfs(False), board.__setitem__(i, ' '), s)[3])
38
+ board[best_move] = 'X'
39
+ if win('X') or ' ' not in board: break
40
+
41
+ show()
42
+ print("AI wins!" if win('X') else "You win!" if win('O') else "Draw!")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: aviml
3
+ Version: 0.1.0
4
+ Summary: Educational AI search and machine learning examples from AIML-LAB
5
+ Project-URL: Repository, https://github.com/99Aval/AIML-LAB
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: numpy
9
+ Requires-Dist: scikit-learn
10
+ Requires-Dist: matplotlib
11
+
12
+ # aviml
13
+
14
+ `aviml` contains eight educational AI and machine learning demos from AIML-LAB.
15
+
16
+ ```sh
17
+ python -m pip install aviml
18
+ python -m aviml.knn
19
+ ```
20
+
21
+ Run any demo with `python -m aviml.<module>`.
22
+
23
+ | Module | Demo |
24
+ | --- | --- |
25
+ | `puzzle8` | Solve an 8-puzzle with A* search. Enter nine space-separated numbers per board and use `0` for the blank. |
26
+ | `alphabeta` | Compute a minimax value with alpha–beta pruning. Enter leaf values and tree depth. |
27
+ | `hillclimbing` | Find a local maximum of a Python expression in `x`. Enter an expression you wrote or trust, then a starting value. |
28
+ | `ttt` | Play tic-tac-toe against a minimax opponent. Enter a board position from 0 to 8. |
29
+ | `kmeans` | Cluster the Iris dataset and display a plot. |
30
+ | `knn` | Evaluate k-nearest neighbors on the Iris dataset. |
31
+ | `logisticregression` | Classify an Iris flower as Setosa or Versicolor. Enter four space-separated features. |
32
+ | `naivebyes` | Evaluate Gaussian naive Bayes on the Iris dataset. |
33
+
34
+ You can also import functions directly. For example, an 8-puzzle one move from its goal has a two-state solution path.
35
+
36
+ ```python
37
+ from aviml.puzzle8 import a_star
38
+
39
+ start = (1, 2, 3, 4, 5, 6, 7, 0, 8)
40
+ goal = (1, 2, 3, 4, 5, 6, 7, 8, 0)
41
+ path = a_star(start, goal)
42
+ assert path == [start, goal]
43
+ ```
@@ -0,0 +1,13 @@
1
+ aviml/__init__.py,sha256=iPbW-cxVJFbM4eLkR64POwFAjhxiShinXmG4-CYQsZw,59
2
+ aviml/alphabeta.py,sha256=2vQJzss-RV9KBDxclPz1t8QTMeya7eFEUCHkKzg5HLk,1054
3
+ aviml/hillclimbing.py,sha256=CKIaIVcBm8knmmFiYdWPB3oPByZIIVAgF0Lz9p8aPRQ,667
4
+ aviml/kmeans.py,sha256=KAQKLXvi5zzQ7l7y8o-kwR4pzNWp5NEijPxkszemv-o,718
5
+ aviml/knn.py,sha256=IqSYWa8Xb_1yQhkzbvAhgWx6TWBpSdLBmYRMvKTfMnM,709
6
+ aviml/logisticregression.py,sha256=evLR1Nul4eMOzK_XoMgFHQ3EX5pQSCNCXQ64TXEPDQg,931
7
+ aviml/naivebyes.py,sha256=M8jhXN02BC_CwmuJ68IhuQwFQUY3hAi66GBf8gPmcI8,1081
8
+ aviml/puzzle8.py,sha256=EmYahaQaZRaZ5DA-VIGziri4IYxcEEa4vsTXen_hWuo,1551
9
+ aviml/ttt.py,sha256=fxYP9fijf9E6Y2Irbb1IS-cCAlGCkWREr3NToq0m5vo,1297
10
+ aviml-0.1.0.dist-info/METADATA,sha256=y7n2Y1mApZzNW8NFPkD1tU3PQTUESAnmUHAULR4IWSU,1605
11
+ aviml-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ aviml-0.1.0.dist-info/top_level.txt,sha256=uAkpauVJQhDqFD89L2RDQb-9BhBI-C5cKFZ5J2Naa5U,6
13
+ aviml-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ aviml