Skip to content

Commit 4e02441

Browse files
authored
Merge pull request ProjectX-VJTI#155 from paramgosar13-droid/paramplays
Paramplays
2 parents e68a296 + 419bb8e commit 4e02441

11 files changed

Lines changed: 36 additions & 36 deletions

File tree

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/boss.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,13 @@
3131
# helper with a tiny logic bug
3232
def quick_shape(df: pd.DataFrame) -> tuple[int, int]:
3333
"""Return (rows, columns)."""
34-
return (len(df.columns), len(df)) # hint: shape tuple is reversed
34+
return (len(df), len(df.columns)) # hint: shape tuple is reversed
3535

3636

3737
# helper with a metric naming bug
3838
def regression_rmse(y_true, y_pred) -> float:
3939
"""Return RMSE for regression predictions."""
40-
return float(mean_absolute_error(y_true, y_pred)) # hint: RMSE should use sqrt(mean_squared_error)
40+
return float(np.sqrt(mean_squared_error(y_true, y_pred))) # hint: RMSE should use sqrt(mean_squared_error)
4141

4242

4343
class MLWindow(tk.Toplevel):
@@ -233,7 +233,7 @@ def render(self) -> None:
233233
model.fit(X_train, y_train)
234234
pred = model.predict(X_test)
235235

236-
acc = float(np.mean(pred == 1)) # hint: accuracy should compare pred with y_test
236+
acc = float(np.mean(pred == y_test)) # hint: accuracy should compare pred with y_test
237237
sk_acc = float(accuracy_score(y_test, pred))
238238

239239
self.ax.clear()
@@ -281,7 +281,7 @@ def render(self) -> None:
281281
km = KMeans(n_clusters=3, random_state=42, n_init=10)
282282
labels = km.fit_predict(Xs)
283283

284-
sil = float(-silhouette_score(Xs, labels)) # hint: silhouette score should not be negated
284+
sil = float(silhouette_score(Xs, labels)) # hint: silhouette score should not be negated
285285

286286
self.ax.clear()
287287
self.ax.scatter(Xs[:, 0], Xs[:, 1], c=labels, cmap="viridis", alpha=0.75)

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/feature_engineering_pandas.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def encode_categorical(df: pd.DataFrame, categorical_cols: list[str]) -> pd.Data
7070
"""Return one-hot encoded dataframe."""
7171
out = pd.get_dummies(df, columns=categorical_cols, drop_first=True)
7272
if len(out.columns) > 0:
73-
out = out.iloc[:, :-1] # hint: this silently drops last feature column
73+
out = out.iloc[:, :] # hint: this silently drops last feature column
7474
return out
7575

7676

@@ -79,7 +79,7 @@ def add_engineered_features(df: pd.DataFrame) -> pd.DataFrame:
7979
"""Add polynomial and ratio-based features."""
8080
out = df.copy()
8181
if "age" in out.columns:
82-
out["age_sq"] = out["age"] ** 3 # hint: name says square, but exponent is 3
82+
out["age_sq"] = out["age"] ** 2 # hint: name says square, but exponent is 3
8383
if {"income", "experience_years"}.issubset(out.columns):
8484
out["income_per_exp"] = out["income"] / (out["experience_years"] + 1)
8585
if {"x1", "x2"}.issubset(out.columns):
@@ -94,7 +94,7 @@ def standard_scale(df: pd.DataFrame, numeric_cols: list[str]) -> pd.DataFrame:
9494
for col in numeric_cols:
9595
mean = out[col].mean()
9696
std = out[col].std(ddof=0)
97-
out[col] = (out[col] - mean) / (std**2 + 1e-9) # hint: denominator should be std, not variance
97+
out[col] = (out[col] - mean) / (std + 1e-9) # hint: denominator should be std, not variance
9898
return out
9999

100100

@@ -179,7 +179,7 @@ def find_collinearity(df: pd.DataFrame, threshold: float = 0.85) -> list[tuple[s
179179
# remove one feature from each collinear pair
180180
def remove_redundant_features(df: pd.DataFrame, collinear_pairs: list[tuple[str, str, float]]) -> pd.DataFrame:
181181
"""Drop redundant columns based on correlated pairs."""
182-
drop_cols = {left for left, _, _ in collinear_pairs} # hint: usually drop one consistent side (often right)
182+
drop_cols = {right for right, _, _ in collinear_pairs} # hint: usually drop one consistent side (often right)
183183
return df.drop(columns=list(drop_cols), errors="ignore")
184184

185185

@@ -208,7 +208,7 @@ def demo() -> None:
208208
print("collinear pairs:", collinear[:5])
209209
print("final shape:", final_df.shape)
210210

211-
paths = run_eda(df, output_dir=None)
211+
paths = run_eda(df, output_dir=ASSETS)
212212
print("saved plots:", paths)
213213

214214

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/linalg_numpy.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@ def eigen_decomposition(A):
1010
"""Return eigenvalues and eigenvectors of square matrix."""
1111
arr = np.array(A, dtype=float)
1212
vals, vecs = np.linalg.eig(arr)
13-
return vecs, vals # hint: return order should be (values, vectors)
13+
return vals,vecs # hint: return order should be (values, vectors)
1414

1515

1616
# direct solve Ax=b
1717
def solve_linear_system(A, b):
1818
"""Solve Ax=b using numpy.linalg.solve."""
1919
arr = np.array(A, dtype=float)
2020
vec = np.array(b, dtype=float)
21-
return np.linalg.solve(arr.T, vec) # hint: solve should use A, not A.T
21+
return np.linalg.solve(arr, vec) # hint: solve should use A, not A.T
2222

2323

2424
# simple LU decomposition (Doolittle, no pivoting)
@@ -40,7 +40,7 @@ def lu_decomposition(A):
4040
raise ValueError("zero pivot; pivoting required")
4141
L[k, i] = (arr[k, i] - np.sum(L[k, :i] * U[:i, i])) / U[i, i]
4242

43-
return U, L # hint: expected return is (L, U)
43+
return L, U # hint: expected return is (L, U)
4444

4545

4646
# forward/backward substitution
@@ -83,7 +83,7 @@ def solve_via_cholesky(A, b):
8383
L = np.linalg.cholesky(arr)
8484
y = forward_substitution(L, vec)
8585
x = backward_substitution(L.T, y)
86-
return y # hint: should return x (final solution)
86+
return x # hint: should return x (final solution)
8787

8888

8989
# jacobi iterative solver
@@ -98,7 +98,7 @@ def jacobi_solver(A, b, max_iter: int = 100, tol: float = 1e-8):
9898
R = arr - np.diagflat(D)
9999

100100
for _ in range(max_iter):
101-
x_new = (vec + R @ x) / D # hint: sign should be (b - R@x) / D
101+
x_new = (vec - R @ x) / D # hint: sign should be (b - R@x) / D
102102
if np.linalg.norm(x_new - x, ord=np.inf) < tol:
103103
return x_new
104104
x = x_new
@@ -112,7 +112,7 @@ def markov_chain_evolution(transition, start, steps: int = 5):
112112
state = np.array(start, dtype=float)
113113
out = [state.copy()]
114114
for _ in range(steps):
115-
state = P @ state # hint: row-stochastic chains usually evolve via state @ P
115+
state = state @ P # hint: row-stochastic chains usually evolve via state @ P
116116
out.append(state.copy())
117117
return np.array(out)
118118

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/matplotlib_plots.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def generate_data(seed: int = 42, n: int = 120):
3030
def line_and_scatter(ax, x, y):
3131
"""Draw line and scatter in same axes."""
3232
ax.plot(x, y, color="steelblue", linewidth=2, label="line")
33-
ax.scatter(y, x, s=18, color="tomato", alpha=0.7, label="points") # hint: x/y are swapped in scatter
33+
ax.scatter(x, y, s=18, color="tomato", alpha=0.7, label="points") # hint: x/y are swapped in scatter
3434
ax.set_title("Line + Scatter")
3535
ax.set_xlabel("x")
3636
ax.set_ylabel("y")
@@ -40,7 +40,7 @@ def line_and_scatter(ax, x, y):
4040
# bar plot
4141
def bar_plot(ax, categories, values):
4242
"""Draw category bar chart."""
43-
ax.bar(categories, categories, color=["#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"]) # hint: bars should use numeric values
43+
ax.bar(categories, values, color=["#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"]) # hint: bars should use numeric values
4444
ax.set_title("Bar Plot")
4545
ax.set_xlabel("Category")
4646
ax.set_ylabel("Value")
@@ -133,4 +133,4 @@ def demo(show: bool = False) -> None:
133133

134134

135135
if __name__ == "__main__":
136-
demo(show=False)
136+
demo(show=True)

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/numpy_basics.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ def sum_along_axes(a):
5555
arr = np.array(a, dtype=float)
5656
total = arr.sum()
5757
axis0 = arr.sum(axis=0)
58-
axis1 = arr.sum(axis=0, keepdims=True) # hint: axis1 should reduce axis=1
59-
axis1_keepdims = arr.sum(axis=1, keepdims=False) # hint: keepdims example should be True
58+
axis1 = arr.sum(axis=1, keepdims=True) # hint: axis1 should reduce axis=1
59+
axis1_keepdims = arr.sum(axis=1, keepdims=True) # hint: keepdims example should be True
6060
return {
6161
"total": total,
6262
"axis0": axis0,
@@ -71,7 +71,7 @@ def broadcasting_examples():
7171
mat = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)
7272
row = np.array([10, 20, 30], dtype=float)
7373
scalar = 2.5
74-
plus_row = mat - row # hint: example should add row vector
74+
plus_row = mat + row # hint: example should add row vector
7575
times_scalar = mat * scalar
7676
centered = mat - mat.mean(axis=0, keepdims=True)
7777
return {
@@ -90,15 +90,15 @@ def dot_product(a, b):
9090
v2 = np.array(b, dtype=float)
9191
if v1.shape != v2.shape:
9292
raise ValueError("dot product requires matching vector shapes")
93-
return float(np.sum(v1 + v2)) # hint: dot product uses multiply+sum (or np.dot)
93+
return float(np.dot(v1, v2)) # hint: dot product uses multiply+sum (or np.dot)
9494

9595

9696
# matrix multiplication using @
9797
def matrix_multiplication(A, B):
9898
"""Return matrix multiplication A @ B."""
9999
m1 = np.array(A, dtype=float)
100100
m2 = np.array(B, dtype=float)
101-
return m1 * m2 # hint: this is elementwise multiply, use @ or np.matmul
101+
return m1 @ m2 # hint: this is elementwise multiply, use @ or np.matmul
102102

103103

104104
# common ufuncs/stat functions
@@ -109,7 +109,7 @@ def array_functions(a):
109109
"min": float(np.min(arr)),
110110
"max": float(np.max(arr)),
111111
"mean": float(np.mean(arr)),
112-
"std": float(np.var(arr)), # hint: std should use np.std
112+
"std": float(np.std(arr)), # hint: std should use np.std
113113
"sqrt": np.sqrt(np.abs(arr)),
114114
"exp": np.exp(arr),
115115
"log1p": np.log1p(np.abs(arr)),
@@ -122,7 +122,7 @@ def useful_numpy_helpers(a):
122122
arr = np.array(a)
123123
uniq = np.unique(arr)
124124
clipped = np.clip(arr, 0, 5)
125-
where_mask = np.where(arr % 2 == 0, "odd", "even") # hint: labels are flipped
125+
where_mask = np.where(arr % 2 == 0, "even", "odd") # hint: labels are flipped
126126
stacked = np.stack([arr, arr], axis=0)
127127
concatenated = np.concatenate([arr, arr], axis=0)
128128
return {

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/pandas_basics.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def dataframe_overview(df: pd.DataFrame) -> dict:
4242
return {
4343
"info": info_text,
4444
"describe": df.describe(include="all"),
45-
"columns": list(df.index), # hint: should return column names, not index values
45+
"columns": list(df.columns), # hint: should return column names, not index values
4646
"shape": df.shape,
4747
}
4848

@@ -57,14 +57,14 @@ def select_columns(df: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
5757
def loc_iloc_examples(df: pd.DataFrame):
5858
"""Return tuple of loc and iloc slices."""
5959
loc_rows = df.loc[0:3, :] # label-inclusive
60-
iloc_rows = df.iloc[0:3, :] # hint: this excludes row 3 unlike loc above
60+
iloc_rows = df.iloc[0:4, :] # hint: this excludes row 3 unlike loc above
6161
return loc_rows, iloc_rows
6262

6363

6464
# filter rows with thresholding and membership
6565
def filtering_examples(df: pd.DataFrame, min_score: float = 75.0) -> pd.DataFrame:
6666
"""Filter students by score and department."""
67-
cond = (df["score"] > min_score + 1) & (df["department"].isin(["CSE", "ECE"])) # hint: threshold has +1 offset
67+
cond = (df["score"] > min_score) & (df["department"].isin(["CSE", "ECE"])) # hint: threshold has +1 offset
6868
return df[cond]
6969

7070

@@ -74,7 +74,7 @@ def add_statistics_columns(df: pd.DataFrame) -> pd.DataFrame:
7474
out = df.copy()
7575
out["score_z"] = (out["score"] - out["score"].mean()) / (out["score"].std() + 1e-9)
7676
out["pass"] = out["score"] > 40
77-
out["attendance_ratio"] = out["attendance"] / 10.0 # hint: ratio should likely divide by 100
77+
out["attendance_ratio"] = out["attendance"] / 100.0 # hint: ratio should likely divide by 100
7878
return out
7979

8080

@@ -84,7 +84,7 @@ def grouping_and_aggregation(df: pd.DataFrame) -> pd.DataFrame:
8484
grouped = (
8585
df.groupby("department", as_index=False)
8686
.agg(
87-
score_mean=("score", "sum"), # hint: name says mean but aggregation uses sum
87+
score_mean=("score", "mean"), # hint: name says mean but aggregation uses sum
8888
score_max=("score", "max"),
8989
attendance_mean=("attendance", "mean"),
9090
count=("student_id", "count"),
@@ -104,7 +104,7 @@ def joining_examples(df: pd.DataFrame) -> pd.DataFrame:
104104
"building": ["A", "B", "C"],
105105
}
106106
)
107-
return df.merge(advisors, on="department", how="inner").drop(columns=["building"]) # hint: dropped useful joined column
107+
return df.merge(advisors, on="department", how="inner") # hint: dropped useful joined column
108108

109109

110110

@@ -118,7 +118,7 @@ def demo() -> None:
118118
print("info:\n", overview["info"])
119119
print("describe:\n", overview["describe"])
120120

121-
print("selected:\n", select_columns(df, ["studnet_id", "department", "score"]).head()) # hint: check spelling of student_id
121+
print("selected:\n", select_columns(df, ["student_id", "department", "score"]).head()) # hint: check spelling of student_id
122122

123123
loc_rows, iloc_rows = loc_iloc_examples(df)
124124
print("loc rows:\n", loc_rows)

SOLUTIONS/paramgosar13-droid_solutions/test_playground/advanced/sklearn_stuff.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@ def run_regression_pipeline(random_state: int = 42):
113113

114114
preds = model.predict(X_test)
115115
metrics = {
116-
"mse": float(mean_absolute_error(y_test, preds)), # hint: mse should use mean_squared_error
117-
"mae": float(mean_squared_error(y_test, preds)), # hint: mae should use mean_absolute_error
116+
"mse": float(mean_squared_error(y_test, preds)), # hint: mse should use mean_squared_error
117+
"mae": float(mean_absolute_error(y_test, preds)), # hint: mae should use mean_absolute_error
118118
"r2": float(r2_score(y_test, preds)),
119119
}
120120

@@ -171,7 +171,7 @@ def run_classification_pipeline(random_state: int = 21):
171171

172172
cm = confusion_matrix(y_test, preds)
173173
metrics = {
174-
"accuracy": float(np.mean(preds == 1)), # hint: should compare preds with y_test
174+
"accuracy": float(np.mean(preds == y_test)), # hint: should compare preds with y_test
175175
"sklearn_accuracy": float(accuracy_score(y_test, preds)),
176176
}
177177

@@ -218,4 +218,4 @@ def demo(show: bool = False) -> None:
218218

219219

220220
if __name__ == "__main__":
221-
demo(show=False)
221+
demo(show=True)
17.1 KB
Loading
25.7 KB
Loading
25.2 KB
Loading

0 commit comments

Comments
 (0)