examcodes 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.
- examcodes/__init__.py +1 -0
- examcodes/core.py +56 -0
- examcodes/programs.py +276 -0
- examcodes-0.1.0.dist-info/METADATA +15 -0
- examcodes-0.1.0.dist-info/RECORD +8 -0
- examcodes-0.1.0.dist-info/WHEEL +5 -0
- examcodes-0.1.0.dist-info/licenses/LICENSE +21 -0
- examcodes-0.1.0.dist-info/top_level.txt +1 -0
examcodes/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .core import *
|
examcodes/core.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from .programs import programs
|
|
2
|
+
|
|
3
|
+
# Mapping of program numbers to their titles
|
|
4
|
+
PROGRAM_TITLES = {
|
|
5
|
+
1: "EDA on California Housing",
|
|
6
|
+
2: "PCA on Iris Dataset",
|
|
7
|
+
3: "Find-S Algorithm",
|
|
8
|
+
4: "k-NN Classification",
|
|
9
|
+
5: "Locally Weighted Regression",
|
|
10
|
+
6: "Regression Models",
|
|
11
|
+
7: "Decision Tree Classification",
|
|
12
|
+
8: "Correlation Matrix and Pair Plot"
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
def get(num):
|
|
16
|
+
"""
|
|
17
|
+
Prints the complete Python code for the requested program number.
|
|
18
|
+
"""
|
|
19
|
+
if num in programs:
|
|
20
|
+
print(programs[num].strip())
|
|
21
|
+
else:
|
|
22
|
+
print(f"Error: Program {num} not found. Available programs are 1 to {len(programs)}.")
|
|
23
|
+
|
|
24
|
+
def run(num):
|
|
25
|
+
"""
|
|
26
|
+
Executes the selected program directly.
|
|
27
|
+
"""
|
|
28
|
+
if num in programs:
|
|
29
|
+
print(f"--- Running Program {num}: {PROGRAM_TITLES[num]} ---")
|
|
30
|
+
try:
|
|
31
|
+
# We execute the program in an isolated global namespace
|
|
32
|
+
exec(programs[num], {})
|
|
33
|
+
except Exception as e:
|
|
34
|
+
print(f"An error occurred while running the program: {e}")
|
|
35
|
+
else:
|
|
36
|
+
print(f"Error: Program {num} not found. Available programs are 1 to {len(programs)}.")
|
|
37
|
+
|
|
38
|
+
def list_programs():
|
|
39
|
+
"""
|
|
40
|
+
Displays all available programs.
|
|
41
|
+
"""
|
|
42
|
+
for num, title in PROGRAM_TITLES.items():
|
|
43
|
+
print(f"{num} - {title}")
|
|
44
|
+
|
|
45
|
+
def search(keyword):
|
|
46
|
+
"""
|
|
47
|
+
Searches programs by keyword.
|
|
48
|
+
"""
|
|
49
|
+
keyword_lower = keyword.lower()
|
|
50
|
+
matches = {num: title for num, title in PROGRAM_TITLES.items() if keyword_lower in title.lower()}
|
|
51
|
+
|
|
52
|
+
if matches:
|
|
53
|
+
for num, title in matches.items():
|
|
54
|
+
print(f"{num} - {title}")
|
|
55
|
+
else:
|
|
56
|
+
print(f"No programs found matching '{keyword}'.")
|
examcodes/programs.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
programs = {
|
|
2
|
+
|
|
3
|
+
1: """
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import numpy as np
|
|
6
|
+
import seaborn as sns
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
from sklearn.datasets import fetch_california_housing
|
|
9
|
+
|
|
10
|
+
# Load
|
|
11
|
+
df = fetch_california_housing(as_frame=True).frame
|
|
12
|
+
num_cols = df.select_dtypes(include=np.number).columns
|
|
13
|
+
|
|
14
|
+
# Histograms + Boxplots in one loop
|
|
15
|
+
for plot_type in ['hist', 'box']:
|
|
16
|
+
fig, axes = plt.subplots(3, 3, figsize=(15, 10))
|
|
17
|
+
for ax, col in zip(axes.flatten(), num_cols):
|
|
18
|
+
if plot_type == 'hist':
|
|
19
|
+
sns.histplot(df[col], kde=True, bins=30, color='blue', ax=ax)
|
|
20
|
+
else:
|
|
21
|
+
sns.boxplot(x=df[col], color='orange', ax=ax)
|
|
22
|
+
ax.set_title(f'{"Distribution" if plot_type == "hist" else "Box Plot"} of {col}')
|
|
23
|
+
plt.tight_layout()
|
|
24
|
+
plt.show()
|
|
25
|
+
|
|
26
|
+
# Outliers via IQR
|
|
27
|
+
print("Outliers Detection:")
|
|
28
|
+
for col in num_cols:
|
|
29
|
+
Q1, Q3 = df[col].quantile([0.25, 0.75])
|
|
30
|
+
IQR = Q3 - Q1
|
|
31
|
+
n = ((df[col] < Q1 - 1.5*IQR) | (df[col] > Q3 + 1.5*IQR)).sum()
|
|
32
|
+
print(f" {col}: {n} outliers")
|
|
33
|
+
|
|
34
|
+
print("\\nDataset Summary:")
|
|
35
|
+
print(df.describe())
|
|
36
|
+
""",
|
|
37
|
+
|
|
38
|
+
2: """
|
|
39
|
+
import numpy as np
|
|
40
|
+
from sklearn.datasets import load_iris
|
|
41
|
+
from sklearn.decomposition import PCA
|
|
42
|
+
import matplotlib.pyplot as plt
|
|
43
|
+
|
|
44
|
+
iris = load_iris()
|
|
45
|
+
reduced = PCA(n_components=2).fit_transform(iris.data)
|
|
46
|
+
|
|
47
|
+
for i, name in enumerate(iris.target_names):
|
|
48
|
+
mask = iris.target == i
|
|
49
|
+
plt.scatter(reduced[mask, 0], reduced[mask, 1], label=name, color='rgb'[i])
|
|
50
|
+
|
|
51
|
+
plt.title('PCA on Iris Dataset')
|
|
52
|
+
plt.xlabel('PC1')
|
|
53
|
+
plt.ylabel('PC2')
|
|
54
|
+
plt.legend()
|
|
55
|
+
plt.grid()
|
|
56
|
+
plt.show()
|
|
57
|
+
""",
|
|
58
|
+
|
|
59
|
+
3: """
|
|
60
|
+
import pandas as pd
|
|
61
|
+
|
|
62
|
+
def find_s(path):
|
|
63
|
+
df = pd.read_csv(path)
|
|
64
|
+
h = ['?'] * (len(df.columns) - 1)
|
|
65
|
+
|
|
66
|
+
for _, row in df[df.iloc[:, -1] == 'Yes'].iterrows():
|
|
67
|
+
|
|
68
|
+
for i, v in enumerate(row[:-1]):
|
|
69
|
+
|
|
70
|
+
if h[i] not in ('?', v):
|
|
71
|
+
h[i] = '?'
|
|
72
|
+
else:
|
|
73
|
+
h[i] = v
|
|
74
|
+
|
|
75
|
+
return h
|
|
76
|
+
|
|
77
|
+
print(find_s('training_data.csv'))
|
|
78
|
+
""",
|
|
79
|
+
|
|
80
|
+
4: """
|
|
81
|
+
import numpy as np
|
|
82
|
+
import matplotlib.pyplot as plt
|
|
83
|
+
from collections import Counter
|
|
84
|
+
|
|
85
|
+
np.random.seed(42)
|
|
86
|
+
|
|
87
|
+
data = np.random.rand(100)
|
|
88
|
+
|
|
89
|
+
train, test = data[:50], data[50:]
|
|
90
|
+
|
|
91
|
+
train_labels = ["Class1" if x <= 0.5 else "Class2" for x in train]
|
|
92
|
+
|
|
93
|
+
def knn(train, labels, point, k):
|
|
94
|
+
|
|
95
|
+
neighbors = sorted(zip(abs(train - point), labels))[:k]
|
|
96
|
+
|
|
97
|
+
return Counter(l for _, l in neighbors).most_common(1)[0][0]
|
|
98
|
+
|
|
99
|
+
print("--- k-Nearest Neighbors Classification ---")
|
|
100
|
+
|
|
101
|
+
for k in [1, 2, 3, 4, 5, 20, 30]:
|
|
102
|
+
|
|
103
|
+
preds = [knn(train, train_labels, x, k) for x in test]
|
|
104
|
+
|
|
105
|
+
print(f"Results for k = {k}:")
|
|
106
|
+
|
|
107
|
+
for i, (val, label) in enumerate(zip(test, preds), start=51):
|
|
108
|
+
print(f"Point x{i} (value: {val:.4f}) is classified as {label}")
|
|
109
|
+
|
|
110
|
+
train_colors = ["blue" if l == "Class1" else "red" for l in train_labels]
|
|
111
|
+
|
|
112
|
+
test_colors = ["blue" if l == "Class1" else "red" for l in preds]
|
|
113
|
+
|
|
114
|
+
plt.figure(figsize=(10, 4))
|
|
115
|
+
|
|
116
|
+
plt.scatter(train, [0]*50, c=train_colors, marker="o", label="Train")
|
|
117
|
+
|
|
118
|
+
plt.scatter(test, [1]*50, c=test_colors, marker="x", label="Test")
|
|
119
|
+
|
|
120
|
+
plt.title(f"k-NN (k={k})")
|
|
121
|
+
|
|
122
|
+
plt.xlabel("Value")
|
|
123
|
+
|
|
124
|
+
plt.yticks([0,1],["Train","Test"])
|
|
125
|
+
|
|
126
|
+
plt.legend()
|
|
127
|
+
|
|
128
|
+
plt.grid(True)
|
|
129
|
+
|
|
130
|
+
plt.show()
|
|
131
|
+
""",
|
|
132
|
+
|
|
133
|
+
5: """
|
|
134
|
+
import numpy as np
|
|
135
|
+
import matplotlib.pyplot as plt
|
|
136
|
+
|
|
137
|
+
np.random.seed(42)
|
|
138
|
+
|
|
139
|
+
X = np.linspace(0, 2*np.pi, 100)
|
|
140
|
+
|
|
141
|
+
y = np.sin(X) + 0.1*np.random.randn(100)
|
|
142
|
+
|
|
143
|
+
Xb = np.c_[np.ones(100), X]
|
|
144
|
+
|
|
145
|
+
xt = np.linspace(0, 2*np.pi, 200)
|
|
146
|
+
|
|
147
|
+
xb = np.c_[np.ones(200), xt]
|
|
148
|
+
|
|
149
|
+
def lwr(x, tau=0.5):
|
|
150
|
+
|
|
151
|
+
w = np.diag(np.exp(-np.sum((Xb-x)**2, axis=1)/(2*tau**2)))
|
|
152
|
+
|
|
153
|
+
t = np.linalg.inv(Xb.T@w@Xb)@Xb.T@w@y
|
|
154
|
+
|
|
155
|
+
return x@t
|
|
156
|
+
|
|
157
|
+
y_pred = [lwr(x) for x in xb]
|
|
158
|
+
|
|
159
|
+
plt.scatter(X, y, c='red', alpha=0.7, label='Data')
|
|
160
|
+
|
|
161
|
+
plt.plot(xt, y_pred, c='blue', label='LWR')
|
|
162
|
+
|
|
163
|
+
plt.legend()
|
|
164
|
+
|
|
165
|
+
plt.grid(alpha=0.3)
|
|
166
|
+
|
|
167
|
+
plt.show()
|
|
168
|
+
""",
|
|
169
|
+
|
|
170
|
+
6: """
|
|
171
|
+
import pandas as pd
|
|
172
|
+
import matplotlib.pyplot as plt
|
|
173
|
+
from sklearn.datasets import fetch_california_housing
|
|
174
|
+
from sklearn.model_selection import train_test_split
|
|
175
|
+
from sklearn.linear_model import LinearRegression
|
|
176
|
+
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
|
177
|
+
from sklearn.pipeline import make_pipeline
|
|
178
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
179
|
+
|
|
180
|
+
def run(model, Xtr, Xte, ytr, yte, title, scatter=False):
|
|
181
|
+
|
|
182
|
+
model.fit(Xtr, ytr)
|
|
183
|
+
|
|
184
|
+
yp = model.predict(Xte)
|
|
185
|
+
|
|
186
|
+
print(f"{title} | MSE: {mean_squared_error(yte,yp):.3f} | R2: {r2_score(yte,yp):.3f}")
|
|
187
|
+
|
|
188
|
+
plt.scatter(Xte, yte, c='blue', label='Actual')
|
|
189
|
+
|
|
190
|
+
plt.scatter(Xte, yp, c='red', label='Predicted') if scatter else plt.plot(Xte, yp, c='red', label='Predicted')
|
|
191
|
+
|
|
192
|
+
plt.title(title)
|
|
193
|
+
|
|
194
|
+
plt.legend()
|
|
195
|
+
|
|
196
|
+
plt.show()
|
|
197
|
+
|
|
198
|
+
housing = fetch_california_housing(as_frame=True)
|
|
199
|
+
|
|
200
|
+
X, y = housing.data[["AveRooms"]], housing.target
|
|
201
|
+
|
|
202
|
+
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
203
|
+
|
|
204
|
+
run(LinearRegression(), Xtr, Xte, ytr, yte, "Linear Regression - California")
|
|
205
|
+
""",
|
|
206
|
+
|
|
207
|
+
7: """
|
|
208
|
+
import numpy as np
|
|
209
|
+
import matplotlib.pyplot as plt
|
|
210
|
+
from sklearn.datasets import load_breast_cancer
|
|
211
|
+
from sklearn.model_selection import train_test_split
|
|
212
|
+
from sklearn.tree import DecisionTreeClassifier, plot_tree
|
|
213
|
+
from sklearn.metrics import accuracy_score
|
|
214
|
+
|
|
215
|
+
data = load_breast_cancer()
|
|
216
|
+
|
|
217
|
+
Xtr, Xte, ytr, yte = train_test_split(
|
|
218
|
+
data.data,
|
|
219
|
+
data.target,
|
|
220
|
+
test_size=0.2,
|
|
221
|
+
random_state=42
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
clf = DecisionTreeClassifier(random_state=42).fit(Xtr, ytr)
|
|
225
|
+
|
|
226
|
+
print(f"Accuracy: {accuracy_score(yte, clf.predict(Xte))*100:.2f}%")
|
|
227
|
+
|
|
228
|
+
print(f"Sample prediction: {'Benign' if clf.predict([Xte[0]])[0] == 1 else 'Malignant'}")
|
|
229
|
+
|
|
230
|
+
plt.figure(figsize=(12, 8))
|
|
231
|
+
|
|
232
|
+
plot_tree(
|
|
233
|
+
clf,
|
|
234
|
+
filled=True,
|
|
235
|
+
feature_names=data.feature_names,
|
|
236
|
+
class_names=data.target_names
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
plt.title("Decision Tree - Breast Cancer")
|
|
240
|
+
|
|
241
|
+
plt.show()
|
|
242
|
+
""",
|
|
243
|
+
|
|
244
|
+
8: """
|
|
245
|
+
import pandas as pd
|
|
246
|
+
import seaborn as sns
|
|
247
|
+
import matplotlib.pyplot as plt
|
|
248
|
+
from sklearn.datasets import fetch_california_housing
|
|
249
|
+
|
|
250
|
+
california_data = fetch_california_housing(as_frame=True)
|
|
251
|
+
|
|
252
|
+
data = california_data.frame
|
|
253
|
+
|
|
254
|
+
correlation_matrix = data.corr()
|
|
255
|
+
|
|
256
|
+
plt.figure(figsize=(10, 8))
|
|
257
|
+
|
|
258
|
+
sns.heatmap(
|
|
259
|
+
correlation_matrix,
|
|
260
|
+
annot=True,
|
|
261
|
+
cmap='coolwarm',
|
|
262
|
+
fmt='.2f',
|
|
263
|
+
linewidths=0.5
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
plt.title('Correlation Matrix of California Housing Features')
|
|
267
|
+
|
|
268
|
+
plt.show()
|
|
269
|
+
|
|
270
|
+
sns.pairplot(data, diag_kind='kde', plot_kws={'alpha': 0.5})
|
|
271
|
+
|
|
272
|
+
plt.suptitle('Pair Plot of California Housing Features', y=1.02)
|
|
273
|
+
|
|
274
|
+
plt.show()
|
|
275
|
+
"""
|
|
276
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: examcodes
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: VTU 6th Semester Machine Learning Lab programs retrieval package
|
|
5
|
+
Author: VTU Student
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.6
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Dynamic: author
|
|
12
|
+
Dynamic: classifier
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
Dynamic: requires-python
|
|
15
|
+
Dynamic: summary
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
examcodes/__init__.py,sha256=K0kNy26Vm6A-1V5lST3ily6yVsNLUbiqk6AZDFm2nJI,20
|
|
2
|
+
examcodes/core.py,sha256=NeN88P5pZfm32NG_NwSK2AzJ5KZ-kWH1HetL2xX_DEU,1665
|
|
3
|
+
examcodes/programs.py,sha256=DysneuyoiVBmL3mI51PCxQtTriZBYexgVTrXDJlAaMM,6255
|
|
4
|
+
examcodes-0.1.0.dist-info/licenses/LICENSE,sha256=vd0Gccwf41dWgbKRFyeWRo81qJ_PPftHAbEtfzurImE,1068
|
|
5
|
+
examcodes-0.1.0.dist-info/METADATA,sha256=TKuHgF-n41f7aSSx52PCDZ3ZnMfi_z55u7AXsB0ZZcE,453
|
|
6
|
+
examcodes-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
examcodes-0.1.0.dist-info/top_level.txt,sha256=b0t5CTUu5Yde_df6YcdTUsgu4OOD3phngOKKEitxP-4,10
|
|
8
|
+
examcodes-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VTU Student
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
examcodes
|