rvce-aiml-lab 0.1.0__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.
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.4
2
+ Name: rvce-aiml-lab
3
+ Version: 0.1.0
4
+ Summary: AI and machine learning lab demos for RVCE's fifth semester
5
+ Project-URL: Repository, https://github.com/Goooble/rvce-aiml-lab
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: matplotlib
9
+ Requires-Dist: numpy
10
+ Requires-Dist: scikit-learn
11
+ Requires-Dist: seaborn
12
+
13
+ # RVCE AIML Lab Programs
14
+
15
+ Eight Python demos for the RVCE fifth-semester AI and machine learning lab.
16
+
17
+ ## Install
18
+
19
+ Install the package directly from GitHub with
20
+ `python -m pip install git+https://github.com/Goooble/rvce-aiml-lab.git`.
21
+
22
+ Install from a source checkout with `python -m pip install .`. If you have a
23
+ built wheel, install it with
24
+ `python -m pip install dist/rvce_aiml_lab-0.1.0-py3-none-any.whl`.
25
+
26
+ Once the package is published to PyPI, install it with
27
+ `python -m pip install rvce-aiml-lab`.
28
+
29
+ ## Run
30
+
31
+ Use `python -m rvce_aiml_lab.<module>` with one of the module names below.
32
+ For example, `python -m rvce_aiml_lab.astar` runs the A* puzzle demo.
33
+
34
+ | Module | Demo |
35
+ | --- | --- |
36
+ | `ab` | Minimax with alpha-beta pruning |
37
+ | `astar` | A* search for an 8-puzzle |
38
+ | `bay` | Gaussian naive Bayes classification |
39
+ | `climb` | Hill climbing with an interactive starting point |
40
+ | `kmeans` | K-means clustering with a plot |
41
+ | `knn` | K-nearest neighbors classification with a confusion matrix |
42
+ | `mini` | Interactive tic-tac-toe against a minimax player |
43
+ | `reg` | Logistic regression with a plot |
44
+
45
+ ## Build a release
46
+
47
+ ```sh
48
+ python -m pip install build twine
49
+ python -m build
50
+ python -m twine check dist/*
51
+ ```
52
+
53
+ With PyPI credentials configured, publish the release with
54
+ `python -m twine upload dist/*`.
@@ -0,0 +1,42 @@
1
+ # RVCE AIML Lab Programs
2
+
3
+ Eight Python demos for the RVCE fifth-semester AI and machine learning lab.
4
+
5
+ ## Install
6
+
7
+ Install the package directly from GitHub with
8
+ `python -m pip install git+https://github.com/Goooble/rvce-aiml-lab.git`.
9
+
10
+ Install from a source checkout with `python -m pip install .`. If you have a
11
+ built wheel, install it with
12
+ `python -m pip install dist/rvce_aiml_lab-0.1.0-py3-none-any.whl`.
13
+
14
+ Once the package is published to PyPI, install it with
15
+ `python -m pip install rvce-aiml-lab`.
16
+
17
+ ## Run
18
+
19
+ Use `python -m rvce_aiml_lab.<module>` with one of the module names below.
20
+ For example, `python -m rvce_aiml_lab.astar` runs the A* puzzle demo.
21
+
22
+ | Module | Demo |
23
+ | --- | --- |
24
+ | `ab` | Minimax with alpha-beta pruning |
25
+ | `astar` | A* search for an 8-puzzle |
26
+ | `bay` | Gaussian naive Bayes classification |
27
+ | `climb` | Hill climbing with an interactive starting point |
28
+ | `kmeans` | K-means clustering with a plot |
29
+ | `knn` | K-nearest neighbors classification with a confusion matrix |
30
+ | `mini` | Interactive tic-tac-toe against a minimax player |
31
+ | `reg` | Logistic regression with a plot |
32
+
33
+ ## Build a release
34
+
35
+ ```sh
36
+ python -m pip install build twine
37
+ python -m build
38
+ python -m twine check dist/*
39
+ ```
40
+
41
+ With PyPI credentials configured, publish the release with
42
+ `python -m twine upload dist/*`.
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rvce-aiml-lab"
7
+ version = "0.1.0"
8
+ description = "AI and machine learning lab demos for RVCE's fifth semester"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ dependencies = [
12
+ "matplotlib",
13
+ "numpy",
14
+ "scikit-learn",
15
+ "seaborn",
16
+ ]
17
+
18
+ [project.urls]
19
+ Repository = "https://github.com/Goooble/rvce-aiml-lab"
20
+
21
+ [tool.setuptools]
22
+ packages = ["rvce_aiml_lab"]
@@ -0,0 +1 @@
1
+ """RVCE fifth-semester AI and machine learning lab demos."""
@@ -0,0 +1,32 @@
1
+ MAX,MIN=1000,-1000
2
+
3
+ def minmax(depth,nodeIndex,maximizing_player,values,alpha,beta):
4
+ if depth==3:
5
+ return values[nodeIndex]
6
+ if maximizing_player:
7
+ best=MIN
8
+ for i in range(0,2):
9
+ val=minmax(depth+1,nodeIndex*2+i,False,values,alpha,beta)
10
+ best=max(best,val)
11
+ alpha=max(alpha,best)
12
+ if beta<=alpha:
13
+ break
14
+ return best
15
+ else:
16
+ best=MAX
17
+ for i in range(0,2):
18
+ val=minmax(depth+1,nodeIndex*2+i,True,values,alpha,beta)
19
+ best=min(best,val)
20
+ beta=min(beta,best)
21
+ if beta<=alpha:
22
+ break
23
+ return best
24
+
25
+
26
+ def main():
27
+ values=[3, 5, 6, 9, 1, 2, 0, -1]
28
+ print("The optimal value is ",minmax(0,0,True,values,MIN,MAX))
29
+
30
+
31
+ if __name__ == "__main__":
32
+ main()
@@ -0,0 +1,87 @@
1
+ def print_state(state):
2
+ for row in state:
3
+ print(row)
4
+ print()
5
+
6
+
7
+ def heuristic(state, goal):
8
+ h = 0
9
+ for i in range(3):
10
+ for j in range(3):
11
+ if state[i][j] != 0 and state[i][j] != goal[i][j]:
12
+ h += 1
13
+ return h
14
+
15
+
16
+ def get_moves(state):
17
+ moves = []
18
+
19
+ # search
20
+ for i in range(3):
21
+ for j in range(3):
22
+ if state[i][j] == 0:
23
+ x, y = i, j
24
+
25
+ directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
26
+
27
+ for dx, dy in directions: #######
28
+ nx, ny = x + dx, y + dy
29
+
30
+ if 0 <= nx < 3 and 0 <= ny < 3:
31
+ new = [row.copy() for row in state] ###
32
+ new[x][y], new[nx][ny] = new[nx][ny], new[x][y]
33
+ moves.append(new)
34
+
35
+ return moves
36
+
37
+
38
+ def a_star(start, goal):
39
+ OPEN = [(heuristic(start, goal), 0, start)]
40
+ CLOSED = []
41
+
42
+ while OPEN:
43
+ current = min(OPEN)
44
+ OPEN.remove(current)
45
+
46
+ f, g, state = current
47
+
48
+ if state in CLOSED:
49
+ continue
50
+
51
+ CLOSED.append(state)
52
+ print_state(state)
53
+
54
+ if state == goal:
55
+ print("Solution found!")
56
+ return
57
+
58
+ for next_state in get_moves(state):
59
+ if next_state not in CLOSED:
60
+ new_g = g + 1
61
+ new_f = new_g + heuristic(next_state, goal)
62
+
63
+ OPEN.append((new_f, new_g, next_state))
64
+
65
+ print("No solution found")
66
+
67
+
68
+ def main():
69
+ start = [
70
+ [1, 2, 3],
71
+ [8, 0, 4],
72
+ [7, 6, 5]
73
+ ]
74
+
75
+ goal = [
76
+ [2, 8, 1],
77
+ [0, 4, 3],
78
+ [7, 6, 5]
79
+ ]
80
+
81
+ a_star(start, goal)
82
+
83
+ # heuristic cannot decrease by more than the cost of a single move.
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
@@ -0,0 +1,79 @@
1
+ import numpy as np
2
+
3
+
4
+ def calculate_mean(values):
5
+ return sum(values) / len(values)
6
+
7
+ def calculate_std(values, mean):
8
+ total = 0
9
+ for v in values:
10
+ total += (v - mean) ** 2
11
+ return (total / len(values)) ** 0.5
12
+
13
+ def probability(x, mean, std):
14
+ exponent = -(x - mean)**2 / (2 * std**2)
15
+ return np.exp(exponent) / (std * np.sqrt(2 * np.pi))
16
+
17
+ def fit(x, y):
18
+ model = {}
19
+
20
+ # samples wtr to each label
21
+ for label in set(y):
22
+ samples = x[y == label]
23
+ prior = len(samples) / len(x)
24
+
25
+ means = []
26
+ stds = []
27
+
28
+ for i in range(x.shape[1]):
29
+ values = samples[:, i]
30
+ mean = calculate_mean(values)
31
+ std = calculate_std(values, mean)
32
+
33
+ means.append(mean)
34
+ stds.append(std)
35
+
36
+ model[label] = (prior, means, stds)
37
+
38
+ return model
39
+
40
+ def predictOne(x, model):
41
+ scores = {}
42
+
43
+ for label in model:
44
+ prior, means, stds = model[label]
45
+ prob = prior
46
+ # all the features
47
+ for i in range(len(x)):
48
+ prob *= probability(x[i], means[i], stds[i])
49
+
50
+ scores[label] = prob
51
+
52
+ return max(scores, key=scores.get)
53
+
54
+
55
+ def main():
56
+ from sklearn.datasets import load_iris
57
+ from sklearn.model_selection import train_test_split
58
+
59
+ iris = load_iris()
60
+ x = iris.data
61
+ y = (iris.target == 2) * 1
62
+
63
+ x_train, x_test, y_train, y_test = train_test_split(
64
+ x, y, test_size=0.2, random_state=42
65
+ )
66
+
67
+ model = fit(x_train, y_train)
68
+
69
+ y_pred = []
70
+ for sample in x_test:
71
+ y_pred.append(predictOne(sample, model))
72
+
73
+ print("Predicted:", y_pred)
74
+ print("Actual:", y_test)
75
+ print("Accuracy:", np.mean(y_pred == y_test))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
@@ -0,0 +1,35 @@
1
+ def hill_climbing(func, start, step=0.01, iterations=1000):
2
+ x = start
3
+
4
+ for i in range(iterations):
5
+ current = func(x)
6
+ left = func(x - step)
7
+ right = func(x + step)
8
+
9
+ if right > current and right >= left:
10
+ x = x + step
11
+
12
+ elif left > current and left > right:
13
+ x = x - step
14
+
15
+ else:
16
+ break
17
+
18
+ return x, func(x)
19
+
20
+
21
+ def func(x):
22
+ return -x**2 + 6*x + 7
23
+
24
+
25
+ def main():
26
+ start = float(input("Enter starting point: "))
27
+
28
+ maxima, value = hill_climbing(func, start)
29
+
30
+ print("Maximum at x =", maxima)
31
+ print("Maximum value =", value)
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
@@ -0,0 +1,82 @@
1
+ import numpy as np
2
+
3
+
4
+ # Calculate Euclidean distance between two points
5
+ def distance(a, b):
6
+ total = 0
7
+ for i in range(len(a)):
8
+ total += (a[i] - b[i]) ** 2
9
+ return total ** 0.5
10
+
11
+ # Find the index of the closest centroid
12
+ def closest_cluster(point, centroids):
13
+ distances = []
14
+
15
+ # Calculate distance from every centroid
16
+ for c in centroids:
17
+ distances.append(distance(point, c))
18
+
19
+ # Return index of the minimum distance
20
+ return np.argmin(distances)
21
+
22
+ # Train the K-Means model
23
+ def fit(x, k=3, max_iters=100):
24
+
25
+ # Randomly select k distinct points as initial centroids
26
+ indices = np.random.choice(len(x), k, replace=False)
27
+ centroids = x[indices].copy()
28
+
29
+ for i in range(max_iters):
30
+
31
+ # Create k empty clusters
32
+ clusters = [[] for j in range(k)]
33
+
34
+ # Assign each point to its nearest centroid
35
+ for point in x:
36
+ label = closest_cluster(point, centroids)
37
+ clusters[label].append(point)
38
+
39
+ # Update the centroid of each cluster
40
+ for j in range(k):
41
+
42
+ # Avoid calculating the mean of an empty cluster
43
+ if len(clusters[j]) > 0:
44
+
45
+ # Calculate mean of each feature separately
46
+ centroids[j] = np.mean(clusters[j], axis=0)
47
+
48
+ # Return the final centroids after all iterations
49
+ return centroids
50
+
51
+
52
+ def main():
53
+ from sklearn import datasets
54
+ import matplotlib.pyplot as plt
55
+
56
+ # Generate 300 data points belonging to 3 groups
57
+ x, y = datasets.make_blobs(
58
+ n_samples=300, centers=3,
59
+ cluster_std=1, random_state=42
60
+ )
61
+
62
+ # Train the model
63
+ centroids = fit(x)
64
+
65
+ # Assign each point to its closest final centroid
66
+ y_pred = []
67
+ for point in x:
68
+ y_pred.append(closest_cluster(point, centroids))
69
+
70
+ # Plot points with colours based on predicted cluster labels
71
+ plt.scatter(x[:, 0], x[:, 1], c=y_pred)
72
+
73
+ # Plot the centroids as red crosses
74
+ for c in centroids:
75
+ plt.plot(c[0], c[1], marker='x', color='red')
76
+
77
+ # Display the graph
78
+ plt.show()
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
@@ -0,0 +1,52 @@
1
+ from sklearn import datasets
2
+ from sklearn.model_selection import train_test_split
3
+ from collections import Counter
4
+ import numpy as np
5
+
6
+ iris = datasets.load_iris()
7
+ x = iris.data
8
+ y = iris.target
9
+
10
+ x_train, x_test, y_train, y_test = train_test_split(
11
+ x, y, test_size=0.2, random_state=42
12
+ )
13
+
14
+ def distance(a, b):
15
+ total = 0
16
+ for i in range(len(a)):
17
+ total += (a[i] - b[i]) ** 2
18
+ return total ** 0.5
19
+
20
+ def predictOne(x, k):
21
+ distances = []
22
+ for trainInst in x_train:
23
+ distances.append(distance(x, trainInst))
24
+
25
+ k_indices = np.argsort(distances)[:k]
26
+
27
+ k_labels = []
28
+ for i in k_indices:
29
+ k_labels.append(y_train[i])
30
+
31
+ ctr = Counter(k_labels)
32
+ return ctr.most_common(1)[0][0]
33
+
34
+
35
+ def main():
36
+ from sklearn.metrics import confusion_matrix
37
+ import seaborn as sns
38
+ import matplotlib.pyplot as plt
39
+
40
+ y_pred = []
41
+ for xInst in x_test:
42
+ y_pred.append(predictOne(xInst, 3))
43
+
44
+ print(np.mean(y_pred == y_test))
45
+
46
+ cm = confusion_matrix(y_test, y_pred)
47
+ sns.heatmap(cm, annot=True)
48
+ plt.show()
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
@@ -0,0 +1,111 @@
1
+
2
+ def winner(b, p):
3
+ for i in range(3):
4
+ if b[i][0] == b[i][1] == b[i][2] == p: # all equals
5
+ return True
6
+ if b[0][i] == b[1][i] == b[2][i] == p:
7
+ return True
8
+
9
+ if b[0][0] == b[1][1] == b[2][2] == p:
10
+ return True
11
+ if b[0][2] == b[1][1] == b[2][0] == p:
12
+ return True
13
+ return False
14
+
15
+
16
+ def full(b):
17
+ for row in b:
18
+ if ' ' in row:
19
+ return False
20
+ return True
21
+
22
+
23
+ def minimax(b, maximizing):
24
+ if winner(b, 'O'):
25
+ return 1
26
+ if winner(b, 'X'):
27
+ return -1
28
+ if full(b):
29
+ return 0
30
+
31
+ if maximizing:
32
+ best = -100
33
+ player = 'O'
34
+ else:
35
+ best = 100
36
+ player = 'X'
37
+
38
+ for i in range(3):
39
+ for j in range(3):
40
+ if b[i][j] == ' ':
41
+ b[i][j] = player
42
+ score = minimax(b, not maximizing)
43
+ b[i][j] = ' '
44
+
45
+ if maximizing:
46
+ best = max(best, score)
47
+ else:
48
+ best = min(best, score)
49
+
50
+ return best
51
+
52
+
53
+ def best_move(b):
54
+ best = -100
55
+ move = None
56
+
57
+ for i in range(3):
58
+ for j in range(3):
59
+ if b[i][j] == ' ':
60
+ b[i][j] = 'O'
61
+ score = minimax(b, False)
62
+ b[i][j] = ' '
63
+
64
+ if score > best:
65
+ best = score
66
+ move = (i, j)
67
+
68
+ return move
69
+
70
+
71
+ def main():
72
+ board = [[' ', ' ', ' '],
73
+ [' ', ' ', ' '],
74
+ [' ', ' ', ' ']]
75
+
76
+ while True:
77
+ #print
78
+ for row in board:
79
+ print(row) # you can print row directly
80
+ # check
81
+ if winner(board, 'X') or winner(board, 'O') or full(board):
82
+ break
83
+ # input
84
+ r = int(input("Row (0-2): "))
85
+ c = int(input("Column (0-2): "))
86
+ # set input
87
+ if r < 0 or r > 2 or c < 0 or c > 2 or board[r][c] != ' ': # many or
88
+ print("Invalid move")
89
+ continue
90
+
91
+ board[r][c] = 'X'
92
+ # check winner
93
+ if winner(board, 'X') or full(board):
94
+ break
95
+ # get move
96
+ i, j = best_move(board) # deconstruct
97
+ board[i][j] = 'O'
98
+
99
+ for row in board:
100
+ print(row)
101
+
102
+ if winner(board, 'X'):
103
+ print("You win!")
104
+ elif winner(board, 'O'):
105
+ print("AI wins!")
106
+ else:
107
+ print("Draw!")
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
@@ -0,0 +1,60 @@
1
+ import numpy as np
2
+
3
+
4
+ def sigmoid(z):
5
+ return 1.0 / (1.0 + np.exp(-z))
6
+
7
+ def cost(h, y):
8
+ return -(y * np.log(h) + (1-y) * np.log(1-h))
9
+
10
+ def gradient(x, h, y):
11
+ return np.dot(x.T, h-y) / y.shape[0]
12
+
13
+ def fit(x, y, num_iterations=200, learning_rate=0.01):
14
+ weights = np.zeros(x.shape[1])
15
+
16
+ for i in range(num_iterations):
17
+ z = np.dot(x, weights)
18
+ h = sigmoid(z)
19
+ grad = gradient(x, h, y)
20
+ weights = weights - learning_rate * grad
21
+
22
+ return weights
23
+
24
+ def predict(x, weights):
25
+ z = np.dot(x, weights)
26
+ return (sigmoid(z) > 0.5) * 1
27
+
28
+
29
+ def main():
30
+ from sklearn import datasets
31
+ from sklearn.model_selection import train_test_split
32
+ from sklearn.preprocessing import StandardScaler
33
+ import matplotlib.pyplot as plt
34
+
35
+ iris = datasets.load_iris()
36
+ x = iris.data[:, :2]
37
+ y = (iris.target != 0) * 1
38
+
39
+ sc = StandardScaler()
40
+ x = sc.fit_transform(x)
41
+ print(x[:5])
42
+
43
+ x_train, x_test, y_train, y_test = train_test_split(
44
+ x, y, test_size=0.4, random_state=42
45
+ )
46
+
47
+ weights = fit(x_train, y_train)
48
+ y_pred = predict(x_test, weights)
49
+
50
+ print(np.mean(y_pred == y_test))
51
+
52
+ plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train)
53
+ plt.title('Logistic Regression Decision Boundaries')
54
+ plt.xlabel('Sepal length')
55
+ plt.ylabel('Sepal width')
56
+ plt.show()
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.4
2
+ Name: rvce-aiml-lab
3
+ Version: 0.1.0
4
+ Summary: AI and machine learning lab demos for RVCE's fifth semester
5
+ Project-URL: Repository, https://github.com/Goooble/rvce-aiml-lab
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: matplotlib
9
+ Requires-Dist: numpy
10
+ Requires-Dist: scikit-learn
11
+ Requires-Dist: seaborn
12
+
13
+ # RVCE AIML Lab Programs
14
+
15
+ Eight Python demos for the RVCE fifth-semester AI and machine learning lab.
16
+
17
+ ## Install
18
+
19
+ Install the package directly from GitHub with
20
+ `python -m pip install git+https://github.com/Goooble/rvce-aiml-lab.git`.
21
+
22
+ Install from a source checkout with `python -m pip install .`. If you have a
23
+ built wheel, install it with
24
+ `python -m pip install dist/rvce_aiml_lab-0.1.0-py3-none-any.whl`.
25
+
26
+ Once the package is published to PyPI, install it with
27
+ `python -m pip install rvce-aiml-lab`.
28
+
29
+ ## Run
30
+
31
+ Use `python -m rvce_aiml_lab.<module>` with one of the module names below.
32
+ For example, `python -m rvce_aiml_lab.astar` runs the A* puzzle demo.
33
+
34
+ | Module | Demo |
35
+ | --- | --- |
36
+ | `ab` | Minimax with alpha-beta pruning |
37
+ | `astar` | A* search for an 8-puzzle |
38
+ | `bay` | Gaussian naive Bayes classification |
39
+ | `climb` | Hill climbing with an interactive starting point |
40
+ | `kmeans` | K-means clustering with a plot |
41
+ | `knn` | K-nearest neighbors classification with a confusion matrix |
42
+ | `mini` | Interactive tic-tac-toe against a minimax player |
43
+ | `reg` | Logistic regression with a plot |
44
+
45
+ ## Build a release
46
+
47
+ ```sh
48
+ python -m pip install build twine
49
+ python -m build
50
+ python -m twine check dist/*
51
+ ```
52
+
53
+ With PyPI credentials configured, publish the release with
54
+ `python -m twine upload dist/*`.
@@ -0,0 +1,16 @@
1
+ README.md
2
+ pyproject.toml
3
+ rvce_aiml_lab/__init__.py
4
+ rvce_aiml_lab/ab.py
5
+ rvce_aiml_lab/astar.py
6
+ rvce_aiml_lab/bay.py
7
+ rvce_aiml_lab/climb.py
8
+ rvce_aiml_lab/kmeans.py
9
+ rvce_aiml_lab/knn.py
10
+ rvce_aiml_lab/mini.py
11
+ rvce_aiml_lab/reg.py
12
+ rvce_aiml_lab.egg-info/PKG-INFO
13
+ rvce_aiml_lab.egg-info/SOURCES.txt
14
+ rvce_aiml_lab.egg-info/dependency_links.txt
15
+ rvce_aiml_lab.egg-info/requires.txt
16
+ rvce_aiml_lab.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ matplotlib
2
+ numpy
3
+ scikit-learn
4
+ seaborn
@@ -0,0 +1 @@
1
+ rvce_aiml_lab
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+