sckitlearn 1.0.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,3 @@
1
+ Metadata-Version: 2.4
2
+ Name: sckitlearn
3
+ Version: 1.0.0
@@ -0,0 +1,14 @@
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sckitlearn"
7
+ version = "1.0.0"
8
+
9
+ [tool.setuptools]
10
+ packages = ["sckitlearn"]
11
+ include-package-data = true
12
+
13
+ [tool.setuptools.package-data]
14
+ sckitlearn = ["*.ipynb", "datasets/*.csv"]
@@ -0,0 +1,40 @@
1
+ import random
2
+
3
+ temp = round(random.uniform(20,40),1)
4
+ motion = input("Motion detected (yes/no: )").lower()
5
+ dark = input("Is it dark (yes/no)").lower()
6
+ smoke = input("Smoke detected (yess/no)").lower()
7
+ occupancy = input("House occupied(yes/no)").lower()
8
+
9
+ if temp > 30:
10
+ ac="ON"
11
+ else:
12
+ ac="OF"
13
+
14
+ if motion == "yes" and dark == "yes":
15
+ light = "ON"
16
+ else:
17
+ light = "OF"
18
+
19
+ if smoke == "Yes":
20
+ alarm = "ON"
21
+ else:
22
+ alarm = "OF"
23
+
24
+ if occupancy == "no":
25
+ door = "Locked"
26
+ else:
27
+ door = "Unlocked"
28
+
29
+ print("\n Smart Home report")
30
+ print("Temp:" , temp)
31
+ print("Motion:", motion)
32
+ print("Dark:", dark)
33
+ print("Smoke:", smoke)
34
+ print("Occupancy:", occupancy)
35
+
36
+ print("\n--- ACTIONS ---")
37
+ print("AC:", ac)
38
+ print("Lights:", light)
39
+ print("Alarm:", alarm)
40
+ print("Door:", door)
@@ -0,0 +1,47 @@
1
+ import matplotlib.pyplot as plt
2
+
3
+ from sklearn.datasets import load_breast_cancer
4
+ from sklearn.preprocessing import StandardScaler
5
+ from sklearn.decomposition import PCA
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn.metrics import accuracy_score
9
+
10
+ data = load_breast_cancer()
11
+ X = data.data
12
+ y = data.target
13
+
14
+ sc = StandardScaler()
15
+ X = sc.fit_transform(X)
16
+
17
+ pca = PCA(n_components=2)
18
+ X_pca = pca.fit_transform(X)
19
+
20
+ print("Before PCA:", X.shape)
21
+ print("After PCA:", X_pca.shape)
22
+
23
+ plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y)
24
+ plt.xlabel("PC1")
25
+ plt.ylabel("PC2")
26
+ plt.title("PCA Visualization")
27
+ plt.show()
28
+
29
+ X_train, X_test, y_train, y_test = train_test_split(
30
+ X, y, test_size=0.2, random_state=42
31
+ )
32
+
33
+ model = LogisticRegression(max_iter=5000)
34
+ model.fit(X_train, y_train)
35
+ pred = model.predict(X_test)
36
+
37
+ print("Accuracy before PCA:", accuracy_score(y_test, pred))
38
+
39
+ # PCA data
40
+ Xp_train, Xp_test, yp_train, yp_test = train_test_split(
41
+ X_pca, y, test_size=0.2, random_state=42
42
+ )
43
+
44
+ model.fit(Xp_train, yp_train)
45
+ pred_pca = model.predict(Xp_test)
46
+
47
+ print("Accuracy after PCA:", accuracy_score(yp_test, pred_pca))
@@ -0,0 +1,56 @@
1
+ # PR11: Advanced ML and Model Optimization
2
+
3
+ import pandas as pd
4
+ from sklearn.datasets import load_breast_cancer
5
+ from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
6
+ from sklearn.svm import SVC
7
+ from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
8
+ from sklearn.metrics import accuracy_score
9
+
10
+ # Load dataset
11
+ data = load_breast_cancer()
12
+ X = data.data
13
+ y = data.target
14
+
15
+ # Split data
16
+ X_train, X_test, y_train, y_test = train_test_split(
17
+ X, y, test_size=0.2, random_state=42
18
+ )
19
+
20
+ # Models
21
+ models = {
22
+ "SVM": SVC(),
23
+ "Random Forest": RandomForestClassifier(random_state=42),
24
+ "AdaBoost": AdaBoostClassifier(random_state=42)
25
+ }
26
+
27
+ # Compare before optimization
28
+ for name, model in models.items():
29
+
30
+ model.fit(X_train, y_train)
31
+ pred = model.predict(X_test)
32
+
33
+ cv = cross_val_score(model, X_train, y_train, cv=5)
34
+
35
+ print("\n", name)
36
+ print("Before Optimization:", accuracy_score(y_test, pred))
37
+ print("Cross Validation:", cv.mean())
38
+
39
+ # Hyperparameter tuning
40
+ params = {
41
+ "SVM": {"C": [0.1, 1, 10]},
42
+ "Random Forest": {"n_estimators": [50, 100]},
43
+ "AdaBoost": {"n_estimators": [50, 100]}
44
+ }
45
+
46
+ # Grid Search and comparison
47
+ for name, model in models.items():
48
+
49
+ grid = GridSearchCV(model, params[name], cv=5)
50
+ grid.fit(X_train, y_train)
51
+
52
+ pred = grid.predict(X_test)
53
+
54
+ print("\n", name)
55
+ print("Best Parameters:", grid.best_params_)
56
+ print("After Optimization:", accuracy_score(y_test, pred))
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env python3
2
+ from collections import deque
3
+
4
+
5
+ # ----------------------------------------------------
6
+ # MAZE
7
+ # 0 = Path
8
+ # 1 = Obstacle
9
+ # * = Start
10
+ # # = End
11
+ # ----------------------------------------------------
12
+
13
+ maze = [
14
+ ["*" , "0","1","0"],
15
+ ["1" , "0" ,"1" ,"0"],
16
+ ["0" , "0" , "0" , "0"],
17
+ ["1" , "1" , "0" , "#"]
18
+ ]
19
+
20
+
21
+ # ----------------------------------------------------
22
+ # HARD-CODED START AND END POSITIONS
23
+ # ----------------------------------------------------
24
+
25
+ start = (0, 0)
26
+ end = (3, 3)
27
+
28
+ rows = len(maze)
29
+ cols = len(maze[0])
30
+
31
+
32
+ # ----------------------------------------------------
33
+ # VISITED ARRAY
34
+ # ----------------------------------------------------
35
+
36
+ visited = [[False for _ in range(cols)] for _ in range(rows)]
37
+
38
+
39
+ # ----------------------------------------------------
40
+ # PARENT ARRAY
41
+ #
42
+ # parent[row][col] stores the previous cell from
43
+ # which we reached the current cell.
44
+ # ----------------------------------------------------
45
+
46
+ parent = [[None for _ in range(cols)] for _ in range(rows)]
47
+ # ----------------------------------------------------
48
+ # DIRECTIONS
49
+ #
50
+ # Up = (-1,From (0,0):
51
+ # Down = (1, 0)
52
+ # Left = (0, -1)
53
+ # Right = (0, 1)
54
+ # ----------------------------------------------------
55
+
56
+ directions = [
57
+ (-1, 0),
58
+ (1, 0),
59
+ (0, -1),
60
+ (0, 1)
61
+ ]
62
+
63
+
64
+ # ----------------------------------------------------
65
+ # BFS QUEUE
66
+ # ----------------------------------------------------
67
+
68
+ queue = deque()
69
+
70
+ queue.append(start)
71
+ visited[start[0]][start[1]] = True
72
+
73
+ found = False
74
+
75
+
76
+ # ----------------------------------------------------
77
+ # BFS ALGORITHM
78
+ # ----------------------------------------------------
79
+
80
+ while queue:
81
+
82
+ current_row, current_col = queue.popleft()
83
+
84
+ # If we reached the destination
85
+ if (current_row, current_col) == end:
86
+ found = True
87
+ break
88
+
89
+ # Check all four directions
90
+ for dr, dc in directions:
91
+
92
+ new_row = current_row + dr
93
+ new_col = current_col + dc
94
+
95
+ # Check whether the new position is inside the maze
96
+ if (0 <= new_row < rows and
97
+ 0 <= new_col < cols):
98
+
99
+ # Check whether:
100
+ # 1. The cell has not been visited
101
+ # 2. The cell is not an obstacle
102
+ if (not visited[new_row][new_col] and
103
+ maze[new_row][new_col] != '1'):
104
+
105
+ # Mark as visited
106
+ visited[new_row][new_col] = True
107
+
108
+ # Store the previous cell
109
+ parent[new_row][new_col] = (
110
+ current_row,
111
+ current_col
112
+ )
113
+
114
+ # Add the cell to the queue
115
+ queue.append((new_row, new_col))
116
+
117
+
118
+ # ----------------------------------------------------
119
+ # CHECK WHETHER A PATH EXISTS
120
+ # ----------------------------------------------------
121
+
122
+ if not found:
123
+
124
+ print("No path exists from Start (*) to End (#).")
125
+
126
+ else:
127
+
128
+ # ------------------------------------------------
129
+ # RECONSTRUCT THE SHORTEST PATH
130
+ # ------------------------------------------------
131
+
132
+ current = end
133
+
134
+ while current != start:
135
+
136
+ row, col = current
137
+
138
+ # Mark shortest path
139
+ maze[row][col] = '.'
140
+
141
+ # Move to the previous cell
142
+ current = parent[row][col]
143
+
144
+
145
+ # Keep start and end symbols
146
+ maze[start[0]][start[1]] = '*'
147
+ maze[end[0]][end[1]] = '#'
148
+
149
+
150
+ # ------------------------------------------------
151
+ # PRINT THE SOLVED MAZE
152
+ # ------------------------------------------------
153
+
154
+ print("\nSolved Maze:\n")
155
+
156
+ for row in maze:
157
+ print(" ".join(row))
158
+
159
+
160
+ #DFS
161
+ #!/usr/bin/env python3
162
+
163
+
164
+ # ----------------------------------------------------
165
+ # MAZE
166
+ # 0 = Path
167
+ # 1 = Obstacle
168
+ # * = Start
169
+ # # = End
170
+ # ----------------------------------------------------
171
+
172
+ maze = [
173
+ ['*', '0', '1', '0'],
174
+ ['1', '0', '1', '0'],
175
+ ['0', '0', '0', '0'],
176
+ ['1', '1', '0', '#']
177
+ ]
178
+
179
+
180
+ # ----------------------------------------------------
181
+ # HARD-CODED START AND END POSITIONS
182
+ # ----------------------------------------------------
183
+
184
+ start = (0, 0)
185
+ end = (3, 3)
186
+
187
+ rows = len(maze)
188
+ cols = len(maze[0])
189
+
190
+
191
+ # ----------------------------------------------------
192
+ # VISITED ARRAY
193
+ # ----------------------------------------------------
194
+
195
+ visited = [[False for _ in range(cols)] for _ in range(rows)]
196
+
197
+
198
+ # ----------------------------------------------------
199
+ # PARENT ARRAY
200
+ #
201
+ # parent[row][col] stores the previous cell from
202
+ # which we reached the current cell.
203
+ # ----------------------------------------------------
204
+
205
+ parent = [[None for _ in range(cols)] for _ in range(rows)]
206
+
207
+
208
+ # ----------------------------------------------------
209
+ # DIRECTIONS
210
+ #
211
+ # Up = (-1, 0)
212
+ # Down = (1, 0)
213
+ # Left = (0, -1)
214
+ # Right = (0, 1)
215
+ # ----------------------------------------------------
216
+
217
+ directions = [
218
+ (-1, 0),
219
+ (1, 0),
220
+ (0, -1),
221
+ (0, 1)
222
+ ]
223
+
224
+
225
+ # ----------------------------------------------------
226
+ # DFS STACK
227
+ # ----------------------------------------------------
228
+
229
+ stack = []
230
+
231
+ stack.append(start)
232
+ visited[start[0]][start[1]] = True
233
+
234
+ found = False
235
+
236
+
237
+ # ----------------------------------------------------
238
+ # DFS ALGORITHM
239
+ # ----------------------------------------------------
240
+
241
+ while stack:
242
+
243
+ # Take the TOP element from the stack
244
+ current_row, current_col = stack.pop()
245
+
246
+ # If we reached the destination
247
+ if (current_row, current_col) == end:
248
+ found = True
249
+ break
250
+
251
+ # Check all four directions
252
+ for dr, dc in directions:
253
+
254
+ new_row = current_row + dr
255
+ new_col = current_col + dc
256
+
257
+ # Check whether the new position is inside the maze
258
+ if (0 <= new_row < rows and
259
+ 0 <= new_col < cols):
260
+
261
+ # Check whether:
262
+ # 1. The cell has not been visited
263
+ # 2. The cell is not an obstacle
264
+ if (not visited[new_row][new_col] and
265
+ maze[new_row][new_col] != '1'):
266
+
267
+ # Mark as visited
268
+ visited[new_row][new_col] = True
269
+
270
+ # Store the previous cell
271
+ parent[new_row][new_col] = (
272
+ current_row,
273
+ current_col
274
+ )
275
+
276
+ # Add the cell to the stack
277
+ stack.append((new_row, new_col))
278
+
279
+
280
+ # ----------------------------------------------------
281
+ # CHECK WHETHER A PATH EXISTS
282
+ # ----------------------------------------------------
283
+
284
+ if not found:
285
+
286
+ print("No path exists from Start (*) to End (#).")
287
+
288
+ else:
289
+
290
+ # ------------------------------------------------
291
+ # RECONSTRUCT THE PATH
292
+ # ------------------------------------------------
293
+
294
+ current = end
295
+
296
+ while current != start:
297
+
298
+ row, col = current
299
+
300
+ # Mark shortest/path found by DFS
301
+ maze[row][col] = '.'
302
+
303
+ # Move to the previous cell
304
+ current = parent[row][col]
305
+
306
+
307
+ # Keep start and end symbols
308
+ maze[start[0]][start[1]] = '*'
309
+ maze[end[0]][end[1]] = '#'
310
+
311
+
312
+ # ------------------------------------------------
313
+ # PRINT THE SOLVED MAZE
314
+ # ------------------------------------------------
315
+
316
+ print("\nDFS Path:\n")
317
+
318
+ for row in maze:
319
+ print(" ".join(row))
@@ -0,0 +1,191 @@
1
+ import heapq
2
+ import time
3
+
4
+ graph = {
5
+ 'A': [('B', 1), ('C', 4)],
6
+ 'B': [('D', 2), ('E', 5)],
7
+ 'C': [('F', 1)],
8
+ 'D': [('G', 3)],
9
+ 'E': [('G', 1)],
10
+ 'F': [('G', 2)],
11
+ 'G': []
12
+ }
13
+
14
+ heuristic = {
15
+ 'A': 6,
16
+ 'B': 4,
17
+ 'C': 3,
18
+ 'D': 3,
19
+ 'E': 1,
20
+ 'F': 2,
21
+ 'G': 0
22
+ }
23
+
24
+
25
+ def display_tree():
26
+ print("\n========== COMPLETE TREE ==========\n")
27
+
28
+ print(" A(6)")
29
+ print(" / \\")
30
+ print(" B(4) C(3)")
31
+ print(" / \\ \\")
32
+ print(" D(3) E(1) F(2)")
33
+ print(" | | |")
34
+ print(" G(0) G(0) G(0)")
35
+
36
+ print("\n====================================")
37
+ print("Format: Node(Heuristic)")
38
+
39
+
40
+ def greedy_best_first_search(start, goal):
41
+
42
+ priority_queue = []
43
+ visited = set()
44
+ nodes_explored = 0
45
+
46
+ heapq.heappush(priority_queue, (heuristic[start], start, [start]))
47
+
48
+ while priority_queue:
49
+
50
+ h, current, path = heapq.heappop(priority_queue)
51
+
52
+ if current in visited:
53
+ continue
54
+
55
+ visited.add(current)
56
+ nodes_explored += 1
57
+
58
+ if current == goal:
59
+ return path, nodes_explored
60
+
61
+ for neighbor, cost in graph[current]:
62
+ if neighbor not in visited:
63
+ heapq.heappush(
64
+ priority_queue,
65
+ (heuristic[neighbor], neighbor, path + [neighbor])
66
+ )
67
+
68
+ return None, nodes_explored
69
+
70
+
71
+ def find_cost(path):
72
+
73
+ cost = 0
74
+
75
+ for i in range(len(path) - 1):
76
+ for neighbor, edge_cost in graph[path[i]]:
77
+ if neighbor == path[i + 1]:
78
+ cost += edge_cost
79
+
80
+ return cost
81
+
82
+
83
+ display_tree()
84
+
85
+ start_time = time.perf_counter()
86
+
87
+ path, nodes = greedy_best_first_search('A', 'G')
88
+
89
+ end_time = time.perf_counter()
90
+
91
+ execution_time = end_time - start_time
92
+
93
+
94
+ print("\n====== GREEDY BEST FIRST SEARCH ======\n")
95
+
96
+ print("Start Node :", "A")
97
+ print("Goal Node :", "G")
98
+
99
+ if path:
100
+ print("Path :", " -> ".join(path))
101
+ print("Path Cost :", find_cost(path))
102
+ print("Nodes Explored :", nodes)
103
+ print("Execution Time :", round(execution_time, 6), "seconds")
104
+ else:
105
+ print("No path found")
106
+
107
+ print("\n======================================")
108
+
109
+ #A*
110
+ import heapq
111
+ import time
112
+
113
+ graph = {
114
+ 'A': [('B', 1), ('C', 1), ('D', 1)],
115
+ 'B': [('E', 1), ('F', 1)],
116
+ 'C': [('F', 1)],
117
+ 'D': [('G', 1)],
118
+ 'E': [('G', 1)],
119
+ 'F': [('G', 1)],
120
+ 'G': []
121
+ }
122
+
123
+ heuristic = {
124
+ 'A': 40,
125
+ 'B': 32,
126
+ 'C': 25,
127
+ 'D': 35,
128
+ 'E': 19,
129
+ 'F': 17,
130
+ 'G': 0
131
+ }
132
+
133
+
134
+ def a_star_search(start, goal):
135
+
136
+ visited = set()
137
+ priority_queue = []
138
+ nodes_explored = 0
139
+
140
+ heapq.heappush(
141
+ priority_queue,
142
+ (heuristic[start], 0, start, [start])
143
+ )
144
+
145
+ while priority_queue:
146
+
147
+ f, g, current, path = heapq.heappop(priority_queue)
148
+
149
+ if current in visited:
150
+ continue
151
+
152
+ visited.add(current)
153
+ nodes_explored += 1
154
+
155
+ if current == goal:
156
+ return path, g, nodes_explored
157
+
158
+ for neighbor, cost in graph[current]:
159
+
160
+ if neighbor not in visited:
161
+
162
+ new_g = g + cost
163
+ new_f = new_g + heuristic[neighbor]
164
+
165
+ heapq.heappush(
166
+ priority_queue,
167
+ (new_f, new_g, neighbor, path + [neighbor])
168
+ )
169
+
170
+ return None, 0, nodes_explored
171
+
172
+
173
+ start_time = time.perf_counter()
174
+
175
+ path, cost, nodes = a_star_search('A', 'G')
176
+
177
+ end_time = time.perf_counter()
178
+
179
+ execution_time = end_time - start_time
180
+
181
+
182
+ if path:
183
+
184
+ print("A* Search")
185
+ print("Path:", " -> ".join(path))
186
+ print("Path Cost:", cost)
187
+ print("Nodes Explored:", nodes)
188
+ print("Execution Time:", f"{execution_time:.2f}", "seconds")
189
+
190
+ else:
191
+ print("No path found")
@@ -0,0 +1,58 @@
1
+ # PR4: Knowledge Representation and Expert System
2
+
3
+ # Knowledge Base (IF-THEN rules)
4
+ rules = {
5
+ "fever": ["flu"],
6
+ "cough": ["flu"],
7
+ "flu": ["take_rest"],
8
+ "take_rest": ["recover"]
9
+ }
10
+
11
+ # Forward Chaining
12
+ def forward_chaining(facts):
13
+ print("\nForward Chaining:")
14
+
15
+ for fact in facts:
16
+ print("Known:", fact)
17
+
18
+ changed = True
19
+
20
+ while changed:
21
+ changed = False
22
+
23
+ for condition, results in rules.items():
24
+ if condition in facts:
25
+ for result in results:
26
+ if result not in facts:
27
+ facts.append(result)
28
+ print("Inferred:", result)
29
+ changed = True
30
+
31
+ print("Final Facts:", facts)
32
+
33
+
34
+ # Backward Chaining
35
+ def backward_chaining(goal, facts):
36
+ if goal in facts:
37
+ return True
38
+
39
+ for condition, results in rules.items():
40
+ if goal in results:
41
+ if backward_chaining(condition, facts):
42
+ return True
43
+
44
+ return False
45
+
46
+
47
+ # Main Program
48
+ facts = ["fever", "cough"]
49
+
50
+ forward_chaining(facts.copy())
51
+
52
+ goal = "recover"
53
+
54
+ print("\nBackward Chaining:")
55
+ if backward_chaining(goal, facts):
56
+ print(goal, "can be achieved")
57
+ else:
58
+ print(goal, "cannot be achieved")
@@ -0,0 +1,64 @@
1
+ # PR5: Data Preprocessing and EDA
2
+
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+
7
+ from sklearn.datasets import fetch_openml
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.preprocessing import LabelEncoder, StandardScaler
10
+
11
+ # Load Titanic dataset
12
+ data = fetch_openml("titanic", version=1, as_frame=True)
13
+ df = data.frame
14
+
15
+ # Select useful columns
16
+ df = df[["pclass", "sex", "age", "fare", "embarked", "survived"]]
17
+
18
+ # Data cleaning
19
+ df.drop_duplicates(inplace=True)
20
+
21
+ # Missing value handling
22
+ df["age"] = df["age"].fillna(df["age"].mean())
23
+ df["fare"] = df["fare"].fillna(df["fare"].mean())
24
+ df["embarked"] = df["embarked"].fillna(df["embarked"].mode()[0])
25
+
26
+ # Label Encoding
27
+ le = LabelEncoder()
28
+ df["sex"] = le.fit_transform(df["sex"])
29
+ df["survived"] = le.fit_transform(df["survived"])
30
+
31
+ # One-Hot Encoding
32
+ df = pd.get_dummies(df, columns=["embarked"], dtype=int)
33
+
34
+ # Statistical analysis
35
+ print("\nStatistical Analysis:")
36
+ print(df.describe())
37
+
38
+ # Histogram
39
+ df.hist(figsize=(10, 8))
40
+ plt.tight_layout()
41
+ plt.show()
42
+
43
+ # Boxplot
44
+ plt.figure(figsize=(8, 5))
45
+ sns.boxplot(data=df[["age", "fare"]])
46
+ plt.show()
47
+
48
+ # Split features and target
49
+ X = df.drop("survived", axis=1)
50
+ y = df["survived"]
51
+
52
+ X_train, X_test, y_train, y_test = train_test_split(
53
+ X, y, test_size=0.2, random_state=42
54
+ )
55
+
56
+ # Feature Scaling
57
+ sc = StandardScaler()
58
+ X_train = sc.fit_transform(X_train)
59
+ X_test = sc.transform(X_test)
60
+
61
+ print("\nTraining data:", X_train.shape)
62
+ print("Testing data:", X_test.shape)
63
+
64
+ print("\nPreprocessing Completed!")
@@ -0,0 +1,54 @@
1
+
2
+ import numpy as np
3
+ from sklearn.datasets import load_diabetes
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.linear_model import LinearRegression
6
+ from sklearn.preprocessing import PolynomialFeatures
7
+ from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
8
+
9
+ data = load_diabetes()
10
+
11
+ X = data.data[:, 2:3]
12
+ y = data.target
13
+
14
+ print("Dataset Loaded Successfully")
15
+ print("Shape:", X.shape)
16
+
17
+ X_train, X_test, y_train, y_test = train_test_split(
18
+ X, y, test_size=0.2, random_state=42
19
+ )
20
+
21
+ lr = LinearRegression()
22
+
23
+ lr.fit(X_train, y_train)
24
+
25
+ lr_pred = lr.predict(X_test)
26
+
27
+ print("Linear Regression")
28
+ print("MSE:", mean_squared_error(y_test, lr_pred))
29
+ print("MAE:", mean_absolute_error(y_test, lr_pred))
30
+ print("R2 Score:", r2_score(y_test, lr_pred))
31
+
32
+ poly = PolynomialFeatures(degree=2)
33
+
34
+ X_train_poly = poly.fit_transform(X_train)
35
+ X_test_poly = poly.transform(X_test)
36
+
37
+ pr = LinearRegression()
38
+
39
+ pr.fit(X_train_poly, y_train)
40
+
41
+ pr_pred = pr.predict(X_test_poly)
42
+
43
+ print("Polynomial Regression")
44
+ print("MSE:", mean_squared_error(y_test, pr_pred))
45
+ print("MAE:", mean_absolute_error(y_test, pr_pred))
46
+ print("R2 Score:", r2_score(y_test, pr_pred))
47
+
48
+ print("Linear Regression R2:", r2_score(y_test, lr_pred))
49
+ print("Polynomial Regression R2:", r2_score(y_test, pr_pred))
50
+
51
+ if r2_score(y_test, lr_pred) > r2_score(y_test, pr_pred):
52
+ print("Linear Regression is better")
53
+ else:
54
+ print("Polynomial Regression is better")
@@ -0,0 +1,79 @@
1
+ # S1: To perform Logistic Regression and K-Nearest Neighbors
2
+ import pandas as pd
3
+ from sklearn.datasets import load_breast_cancer
4
+
5
+ data = load_breast_cancer(as_frame=True)
6
+ df = data.frame
7
+
8
+ print("Successfully loaded dataset")
9
+ print(df.head())
10
+ print("Shape of dataset:", df.shape)
11
+
12
+ # S2: Separate X and Y
13
+ X = df.drop(columns='target')
14
+ y = df["target"]
15
+
16
+ print("X shape:", X.shape)
17
+ print("y shape:", y.shape)
18
+
19
+ # S3: Train-Test Split
20
+ from sklearn.model_selection import train_test_split
21
+
22
+ X_train, X_test, y_train, y_test = train_test_split(
23
+ X, y,
24
+ test_size=0.2,
25
+ random_state=42,
26
+ stratify=y
27
+ )
28
+
29
+ print("X_train shape:", X_train.shape)
30
+ print("X_test shape:", X_test.shape)
31
+ print("y_train shape:", y_train.shape)
32
+ print("y_test shape:", y_test.shape)
33
+
34
+ # S4: Feature Scaling
35
+ from sklearn.preprocessing import StandardScaler
36
+
37
+ scaler = StandardScaler()
38
+
39
+ X_train_scaled = scaler.fit_transform(X_train)
40
+ X_test_scaled = scaler.transform(X_test)
41
+
42
+ print("Before scaling:")
43
+ print(X_train.head())
44
+
45
+ print("\nAfter scaling:")
46
+ print(X_train_scaled[:5])
47
+
48
+ # S5: Logistic Regression
49
+ from sklearn.linear_model import LogisticRegression
50
+
51
+ log_model = LogisticRegression(max_iter=1000)
52
+ log_model.fit(X_train_scaled, y_train)
53
+
54
+ y_pred_log = log_model.predict(X_test_scaled)
55
+
56
+ print("Logistic Regression completed")
57
+ print("Predicted values:", y_pred_log[:10])
58
+
59
+ # Evaluation
60
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
61
+ from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
62
+ import matplotlib.pyplot as plt
63
+
64
+ accuracy_l = accuracy_score(y_test, y_pred_log)
65
+ precision_l = precision_score(y_test, y_pred_log)
66
+ recall_l = recall_score(y_test, y_pred_log)
67
+ f1_l = f1_score(y_test, y_pred_log)
68
+
69
+ print("\nLogistic Regression")
70
+ print("Accuracy :", accuracy_l)
71
+ print("Precision:", precision_l)
72
+ print("Recall :", recall_l)
73
+ print("F1 Score :", f1_l)
74
+
75
+ cm = confusion_matrix(y_test, y_pred_log)
76
+ disp = ConfusionMatrixDisplay(confusion_matrix=cm)
77
+ disp.plot()
78
+ plt.title("Logistic Regression Confusion Matrix")
79
+ plt.show()
@@ -0,0 +1,47 @@
1
+ import pandas as pd
2
+ from sklearn.datasets import load_breast_cancer
3
+ from sklearn.model_selection import train_test_split
4
+ from sklearn.tree import DecisionTreeClassifier
5
+ from sklearn.naive_bayes import GaussianNB
6
+ from sklearn.metrics import accuracy_score
7
+
8
+ # Load Dataset
9
+ data = load_breast_cancer()
10
+
11
+ X = data.data
12
+ y = data.target
13
+
14
+ print("Dataset Loaded Successfully")
15
+ print("Shape:", X.shape)
16
+
17
+ # Train-Test Split
18
+ X_train, X_test, y_train, y_test = train_test_split(
19
+ X, y, test_size=0.2, random_state=42
20
+ )
21
+
22
+ # Decision Tree
23
+ dt = DecisionTreeClassifier()
24
+
25
+ dt.fit(X_train, y_train)
26
+
27
+ dt_pred = dt.predict(X_test)
28
+
29
+ print("Decision Tree Accuracy:", accuracy_score(y_test, dt_pred))
30
+
31
+ # Naive Bayes
32
+ nb = GaussianNB()
33
+
34
+ nb.fit(X_train, y_train)
35
+
36
+ nb_pred = nb.predict(X_test)
37
+
38
+ print("Naive Bayes Accuracy:", accuracy_score(y_test, nb_pred))
39
+
40
+ # Comparison
41
+ print("Decision Tree:", accuracy_score(y_test, dt_pred))
42
+ print("Naive Bayes:", accuracy_score(y_test, nb_pred))
43
+
44
+ if accuracy_score(y_test, dt_pred) > accuracy_score(y_test, nb_pred):
45
+ print("Decision Tree is better")
46
+ else:
47
+ print("Naive Bayes is better")
@@ -0,0 +1,64 @@
1
+ import pandas as pd
2
+ import matplotlib.pyplot as plt
3
+
4
+ from sklearn.datasets import load_iris
5
+ from sklearn.preprocessing import StandardScaler
6
+ from sklearn.cluster import KMeans, AgglomerativeClustering
7
+ from scipy.cluster.hierarchy import dendrogram, linkage
8
+
9
+ # Load dataset
10
+ iris = load_iris()
11
+ X = iris.data
12
+
13
+ # Scaling
14
+ sc = StandardScaler()
15
+ X = sc.fit_transform(X)
16
+
17
+ # Elbow Method
18
+ wcss = []
19
+
20
+ for i in range(1, 11):
21
+ km = KMeans(n_clusters=i, random_state=42, n_init=10)
22
+ km.fit(X)
23
+ wcss.append(km.inertia_)
24
+
25
+ plt.plot(range(1, 11), wcss, marker='o')
26
+ plt.xlabel("Number of Clusters")
27
+ plt.ylabel("WCSS")
28
+ plt.title("Elbow Method")
29
+ plt.show()
30
+
31
+ # K-Means Clustering
32
+ km = KMeans(n_clusters=3, random_state=42, n_init=10)
33
+
34
+ y = km.fit_predict(X)
35
+
36
+ print("K-Means Clusters:")
37
+ print(y)
38
+
39
+ # Dendrogram
40
+ z = linkage(X, method='ward')
41
+
42
+ dendrogram(z, truncate_mode='lastp', p=20)
43
+
44
+ plt.title("Dendrogram")
45
+ plt.xlabel("Data Points")
46
+ plt.ylabel("Distance")
47
+ plt.show()
48
+
49
+ # Hierarchical Clustering
50
+ hc = AgglomerativeClustering(n_clusters=3)
51
+
52
+ y_hc = hc.fit_predict(X)
53
+
54
+ print("Hierarchical Clusters:")
55
+ print(y_hc)
56
+
57
+ # Analyze Generated Clusters
58
+ df = pd.DataFrame(iris.data, columns=iris.feature_names)
59
+
60
+ df['KMeans'] = y
61
+ df['Hierarchical'] = y_hc
62
+
63
+ print(df.groupby('KMeans').mean())
64
+ print(df.groupby('Hierarchical').mean())
File without changes
@@ -0,0 +1,3 @@
1
+ Metadata-Version: 2.4
2
+ Name: sckitlearn
3
+ Version: 1.0.0
@@ -0,0 +1,17 @@
1
+ pyproject.toml
2
+ sckitlearn/PR1.py
3
+ sckitlearn/PR10.py
4
+ sckitlearn/PR11.py
5
+ sckitlearn/PR2.py
6
+ sckitlearn/PR3.py
7
+ sckitlearn/PR4.py
8
+ sckitlearn/PR5.py
9
+ sckitlearn/PR6.py
10
+ sckitlearn/PR7.py
11
+ sckitlearn/PR8.py
12
+ sckitlearn/PR9.py
13
+ sckitlearn/__init__.py
14
+ sckitlearn.egg-info/PKG-INFO
15
+ sckitlearn.egg-info/SOURCES.txt
16
+ sckitlearn.egg-info/dependency_links.txt
17
+ sckitlearn.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ sckitlearn
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+