sjlearn 0.3.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.
Files changed (42) hide show
  1. set/__init__.py +57 -0
  2. set/clustering.py +136 -0
  3. set/codebook.py +243 -0
  4. set/labs_code/activation_functions.py +124 -0
  5. set/labs_code/lab01_numpy_basics.py +150 -0
  6. set/labs_code/lab02_batch_gradient_descent.py +107 -0
  7. set/labs_code/lab03_linear_regression.py +66 -0
  8. set/labs_code/lab04_logistic_regression.py +78 -0
  9. set/labs_code/lab05_forward_propagation.py +161 -0
  10. set/labs_code/lab06_backward_propagation.py +175 -0
  11. set/labs_code/lab07_tensorflow_keras.py +84 -0
  12. set/labs_code/lab08_pca.py +82 -0
  13. set/labs_code/lab09_image_pca.py +129 -0
  14. set/labs_code/lab10_lda.py +101 -0
  15. set/labs_code/lab11_kmeans.py +57 -0
  16. set/labs_code/lab12_agglomerative.py +59 -0
  17. set/labs_code/lab13_svm_svc.py +128 -0
  18. set/labs_code/lab14_concrete.py +269 -0
  19. set/regression.py +284 -0
  20. set/theory/activation_functions.md +23 -0
  21. set/theory/agglomerative.md +8 -0
  22. set/theory/backward_propagation.md +64 -0
  23. set/theory/batch_gradient_descent.md +63 -0
  24. set/theory/concrete_regression.md +8 -0
  25. set/theory/cross_validation.md +10 -0
  26. set/theory/forward_propagation.md +43 -0
  27. set/theory/image_pca.md +22 -0
  28. set/theory/kmeans.md +10 -0
  29. set/theory/knn.md +8 -0
  30. set/theory/lda.md +20 -0
  31. set/theory/linear_regression.md +35 -0
  32. set/theory/logistic_regression.md +48 -0
  33. set/theory/machine_learning.md +42 -0
  34. set/theory/neural_network.md +42 -0
  35. set/theory/numpy_basics.md +7 -0
  36. set/theory/pca.md +24 -0
  37. set/theory/svm.md +8 -0
  38. set/theory/tensorflow_keras.md +21 -0
  39. sjlearn-0.3.0.dist-info/METADATA +64 -0
  40. sjlearn-0.3.0.dist-info/RECORD +42 -0
  41. sjlearn-0.3.0.dist-info/WHEEL +4 -0
  42. sjlearn-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,128 @@
1
+ # TOPIC: svm
2
+ # LAB: 13
3
+ # TITLE: Lab 13 - SVM / SVC: LinearSVC, linear/RBF/polynomial kernels, effect of C and gamma, diabetes as classification
4
+ # TAGS: svm, svc, linearsvc, kernel, rbf, polynomial, support vectors, c, gamma, classification
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import matplotlib.pyplot as plt
9
+ from sklearn.datasets import load_breast_cancer, load_diabetes
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.svm import SVC, LinearSVC
13
+ from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
14
+
15
+ # ---------------- load dataset ----------------
16
+ data = load_breast_cancer()
17
+ x = pd.DataFrame(data.data, columns=data.feature_names)
18
+ y = data.target
19
+ print("Shape:", x.shape)
20
+ print("Classes:", data.target_names)
21
+
22
+ # ---------------- split ----------------
23
+ x_train, x_test, y_train, y_test = train_test_split(
24
+ x, y, test_size=0.2, random_state=42, stratify=y)
25
+ print("training shape:", x_train.shape)
26
+ print("test shape:", x_test.shape)
27
+
28
+ # ---------------- standardize the features ----------------
29
+ scaler = StandardScaler()
30
+ x_train_scaled = scaler.fit_transform(x_train)
31
+ x_test_scaled = scaler.transform(x_test)
32
+
33
+ # ---------------- Part A: Linear SVM using LinearSVC ----------------
34
+ linear_svm = LinearSVC(C=1.0, random_state=42, max_iter=10000)
35
+ linear_svm.fit(x_train_scaled, y_train)
36
+ train_pred_linear = linear_svm.predict(x_train_scaled)
37
+ test_pred_linear = linear_svm.predict(x_test_scaled)
38
+ print("Training accuracy:", accuracy_score(y_train, train_pred_linear))
39
+ print("Testing accuracy:", accuracy_score(y_test, test_pred_linear))
40
+
41
+ print("confusion matrix:")
42
+ print(confusion_matrix(y_test, test_pred_linear))
43
+ print("classification report:")
44
+ print(classification_report(y_test, test_pred_linear, target_names=data.target_names))
45
+
46
+ # ---------------- Part B: Support vector classifier using SVC ----------------
47
+ svc_linear = SVC(kernel="linear", C=1.0) # linear kernel
48
+ svc_linear.fit(x_train_scaled, y_train)
49
+ svc_linear_pred = svc_linear.predict(x_test_scaled)
50
+ print("Linear SVC Accuracy:", accuracy_score(y_test, svc_linear_pred))
51
+ print("Support vectors per class:", svc_linear.n_support_)
52
+
53
+ svc_rbf = SVC(kernel="rbf", C=1.0, gamma="scale") # RBF kernel
54
+ svc_rbf.fit(x_train_scaled, y_train)
55
+ svc_rbf_pred = svc_rbf.predict(x_test_scaled)
56
+ print("RBF SVC Accuracy:", accuracy_score(y_test, svc_rbf_pred))
57
+ print("Support vectors per class:", svc_rbf.n_support_)
58
+
59
+ svc_poly = SVC(kernel="poly", degree=3, C=1.0, gamma="scale") # polynomial kernel
60
+ svc_poly.fit(x_train_scaled, y_train)
61
+ svc_poly_pred = svc_poly.predict(x_test_scaled)
62
+ print("Polynomial SVC Accuracy:", accuracy_score(y_test, svc_poly_pred))
63
+ print("Support vectors per class:", svc_poly.n_support_)
64
+
65
+ # confusion matrices for rbf and poly (a TODO in the notebook)
66
+ print("RBF:\n", confusion_matrix(y_test, svc_rbf_pred))
67
+ print("Poly:\n", confusion_matrix(y_test, svc_poly_pred))
68
+
69
+ # ---------------- effect of C ----------------
70
+ # small C: wider margin, less tolerance for error | large C: narrower margin, bigger penalty
71
+ for c_value in [0.01, 0.1, 1, 10, 100]:
72
+ model = SVC(kernel="rbf", C=c_value, gamma="scale")
73
+ model.fit(x_train_scaled, y_train)
74
+ pred = model.predict(x_test_scaled)
75
+ print("C =", c_value, "Accuracy =", accuracy_score(y_test, pred))
76
+
77
+ # ---------------- effect of gamma ----------------
78
+ # small gamma: smoother decision boundary | large gamma: more complex decision boundary
79
+ for gamma_value in [0.01, 0.1, 1, 10, 100]:
80
+ model1 = SVC(kernel="rbf", C=1, gamma=gamma_value)
81
+ model1.fit(x_train_scaled, y_train)
82
+ pred1 = model1.predict(x_test_scaled)
83
+ print("gamma =", gamma_value, "Accuracy =", accuracy_score(y_test, pred1))
84
+
85
+ # ======================================================================
86
+ # Task: diabetes is a regression dataset - turn it into classification and apply SVC
87
+ # ======================================================================
88
+ data = load_diabetes()
89
+ x = pd.DataFrame(data.data, columns=data.feature_names)
90
+ y = (data.target > np.median(data.target)).astype(int)
91
+ print("Shape:", x.shape)
92
+ print("Classes:", np.unique(y, return_counts=True))
93
+ print("Median target value:", np.median(data.target))
94
+
95
+ x_train, x_test, y_train, y_test = train_test_split(
96
+ x, y, test_size=0.2, random_state=42, stratify=y)
97
+ print("Training shape:", x_train.shape, " Test shape:", x_test.shape)
98
+
99
+ scaler = StandardScaler()
100
+ x_train_scaled = scaler.fit_transform(x_train)
101
+ x_test_scaled = scaler.transform(x_test)
102
+
103
+ svc_linear = SVC(kernel="linear", C=1.0)
104
+ svc_linear.fit(x_train_scaled, y_train)
105
+ svc_linear_pred = svc_linear.predict(x_test_scaled)
106
+ print("Linear SVC Accuracy:", accuracy_score(y_test, svc_linear_pred))
107
+ print(confusion_matrix(y_test, svc_linear_pred))
108
+ print(classification_report(y_test, svc_linear_pred, target_names=["At/below median", "Above median"]))
109
+ print("Support vectors per class:", svc_linear.n_support_)
110
+
111
+ svc_rbf = SVC(kernel="rbf", C=1.0, gamma="scale")
112
+ svc_rbf.fit(x_train_scaled, y_train)
113
+ svc_rbf_pred = svc_rbf.predict(x_test_scaled)
114
+ print("RBF SVC Accuracy:", accuracy_score(y_test, svc_rbf_pred))
115
+ print(confusion_matrix(y_test, svc_rbf_pred))
116
+ print("Support vectors per class:", svc_rbf.n_support_)
117
+
118
+ svc_poly = SVC(kernel="poly", degree=3, C=1.0, gamma="scale")
119
+ svc_poly.fit(x_train_scaled, y_train)
120
+ svc_poly_pred = svc_poly.predict(x_test_scaled)
121
+ print("Polynomial SVC Accuracy:", accuracy_score(y_test, svc_poly_pred))
122
+ print(confusion_matrix(y_test, svc_poly_pred))
123
+ print("Support vectors per class:", svc_poly.n_support_)
124
+
125
+ print("Kernel comparison:")
126
+ print("Linear:", accuracy_score(y_test, svc_linear_pred))
127
+ print("RBF:", accuracy_score(y_test, svc_rbf_pred))
128
+ print("Polynomial:", accuracy_score(y_test, svc_poly_pred))
@@ -0,0 +1,269 @@
1
+ # TOPIC: concrete_regression
2
+ # LAB: 14
3
+ # TITLE: Concrete strength: EDA, feature engineering, VIF, 9 models + GridSearchCV, final model, prediction
4
+ # TAGS: regression, concrete, feature engineering, vif, gridsearch, cross validation, random forest, gradient boosting
5
+ # NEEDS: pip install ucimlrepo statsmodels (and internet to download the UCI data)
6
+ # NOTE: the full grid search is slow. Same code is available as functions: set.regression
7
+
8
+ try:
9
+ display
10
+ except NameError: # running outside Jupyter
11
+ display = print
12
+
13
+
14
+ # ---------- 1. Install required packages ----------
15
+
16
+ # ---------- 2. Import libraries ----------
17
+ import warnings
18
+ warnings.filterwarnings("ignore")
19
+ import numpy as np
20
+ import pandas as pd
21
+ import matplotlib.pyplot as plt
22
+ from ucimlrepo import fetch_ucirepo
23
+ from sklearn.model_selection import train_test_split, KFold, GridSearchCV
24
+ from sklearn.pipeline import Pipeline
25
+ from sklearn.preprocessing import StandardScaler
26
+ from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
27
+ from sklearn.linear_model import LinearRegression, Ridge
28
+ from sklearn.neighbors import KNeighborsRegressor
29
+ from sklearn.svm import SVR
30
+ from sklearn.tree import DecisionTreeRegressor
31
+ from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
32
+ from sklearn.neural_network import MLPRegressor
33
+ from statsmodels.stats.outliers_influence import variance_inflation_factor
34
+
35
+
36
+ # ---------- 3. Load the UCI dataset ----------
37
+ concrete = fetch_ucirepo(id=165)
38
+ X = concrete.data.features.copy()
39
+ y = concrete.data.targets.iloc[:,0].copy()
40
+ X.columns=["Cement","Slag","Fly_Ash","Water",
41
+ "Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Age"]
42
+ y.name="Strength"
43
+ df=X.copy(); df["Strength"]=y
44
+ print("Dataset shape:", df.shape)
45
+ df.head()
46
+
47
+
48
+ # ---------- 4. Data cleaning and quality checks ----------
49
+ print("DATA TYPES")
50
+ print(df.dtypes)
51
+ print("\nMISSING VALUES")
52
+ print(df.isnull().sum())
53
+ print("\nDUPLICATE ROWS")
54
+ print(df.duplicated().sum())
55
+ print("\nNEGATIVE VALUES")
56
+ print((df.select_dtypes(include=np.number)<0).sum())
57
+ print("\nSUMMARY STATISTICS")
58
+ display(df.describe().round(2))
59
+
60
+ before=len(df)
61
+ df=df.drop_duplicates().reset_index(drop=True)
62
+ after=len(df)
63
+ print("Rows before:",before)
64
+ print("Rows after :",after)
65
+ X=df.drop(columns="Strength")
66
+ y=df["Strength"].copy()
67
+
68
+ df.hist(figsize=(14,10), bins=25)
69
+ plt.suptitle("Feature and Target Distributions", y=1.02)
70
+ plt.tight_layout(); plt.show()
71
+
72
+ for col in df.columns:
73
+ plt.figure(figsize=(7,2.8))
74
+ plt.boxplot(df[col], vert=False)
75
+ plt.title(f"Boxplot: {col}")
76
+ plt.xlabel(col)
77
+ plt.tight_layout(); plt.show()
78
+
79
+
80
+ # ---------- 7. EDA — correlation matrix ----------
81
+ corr=df.corr(numeric_only=True)
82
+ plt.figure(figsize=(10,8))
83
+ plt.imshow(corr, aspect="auto")
84
+ plt.colorbar()
85
+ plt.xticks(range(len(corr.columns)), corr.columns, rotation=90)
86
+ plt.yticks(range(len(corr.columns)), corr.columns)
87
+ plt.title("Correlation Matrix")
88
+ plt.tight_layout(); plt.show()
89
+ display(corr.round(3))
90
+
91
+
92
+ # ---------- 8. Correlation with target ----------
93
+ target_corr=corr["Strength"].sort_values(ascending=False)
94
+ plt.figure(figsize=(9,5))
95
+ target_corr.drop("Strength").plot(kind="bar")
96
+ plt.title("Correlation of Original Features with Strength")
97
+ plt.ylabel("Correlation")
98
+ plt.xticks(rotation=45)
99
+ plt.tight_layout(); plt.show()
100
+ display(target_corr.to_frame("Correlation").round(3))
101
+
102
+
103
+ # ---------- 9. Train-test split ----------
104
+ X_train_raw,X_test_raw,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state=42)
105
+ print("Training rows:",len(X_train_raw))
106
+ print("Testing rows :",len(X_test_raw))
107
+
108
+ def engineer_features(X):
109
+ X=X.copy(); eps=1e-8
110
+ binder=X["Cement"]+X["Slag"]+X["Fly_Ash"]
111
+ scm=X["Slag"]+X["Fly_Ash"]
112
+ total_agg=X["Coarse_Aggregate"]+X["Fine_Aggregate"]
113
+ X["Water_Binder_Ratio"]=X["Water"]/(binder+eps)
114
+ X["SCM_Fraction"]=scm/(binder+eps)
115
+ X["Cement_Fraction"]=X["Cement"]/(binder+eps)
116
+ X["Aggregate_Binder_Ratio"]=total_agg/(binder+eps)
117
+ X["Superplasticizer_Binder_Ratio"]=X["Superplasticizer"]/(binder+eps)
118
+ X["Log_Age"]=np.log1p(X["Age"])
119
+ return X
120
+ X_train_eng_full=engineer_features(X_train_raw)
121
+ X_test_eng_full=engineer_features(X_test_raw)
122
+ print("Original feature count:",X_train_raw.shape[1])
123
+ print("After engineering:",X_train_eng_full.shape[1])
124
+
125
+
126
+ # ---------- 11. Define three feature sets ----------
127
+ original_features=["Cement","Slag","Fly_Ash","Water","Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Age"]
128
+ engineered_reduced_features=["Cement","Slag","Fly_Ash","Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Water_Binder_Ratio","SCM_Fraction","Aggregate_Binder_Ratio","Log_Age"]
129
+ X_train_original=X_train_raw[original_features].copy(); X_test_original=X_test_raw[original_features].copy()
130
+ X_train_engineered=X_train_eng_full[engineered_reduced_features].copy(); X_test_engineered=X_test_eng_full[engineered_reduced_features].copy()
131
+ print("Original:",len(original_features))
132
+ print("Engineered reduced:",len(engineered_reduced_features))
133
+
134
+ def calculate_vif(X):
135
+ Xn=X.select_dtypes(include=np.number).copy()
136
+ out=pd.DataFrame({"Feature":Xn.columns})
137
+ out["VIF"]=[variance_inflation_factor(Xn.values,i) for i in range(Xn.shape[1])]
138
+ return out.sort_values("VIF",ascending=False).reset_index(drop=True)
139
+ display(calculate_vif(X_train_engineered).round(2))
140
+
141
+ vif_reduced_features=["Cement","Slag","Fly_Ash","Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Water_Binder_Ratio","Log_Age"]
142
+ X_train_vif=X_train_eng_full[vif_reduced_features].copy(); X_test_vif=X_test_eng_full[vif_reduced_features].copy()
143
+ print("VIF-reduced feature count:",len(vif_reduced_features))
144
+ display(calculate_vif(X_train_vif).round(2))
145
+
146
+
147
+ # ---------- 15. 5-fold cross-validation ----------
148
+ cv=KFold(n_splits=5,shuffle=True,random_state=42)
149
+
150
+
151
+ # ---------- 16. Models and hyperparameter grids ----------
152
+ model_configs={
153
+ "Linear Regression":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",LinearRegression())]),"params":{}},
154
+ "Ridge":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",Ridge())]),"params":{"model__alpha":[0.01,0.1,1,10,100]}},
155
+ "KNN":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",KNeighborsRegressor())]),"params":{"model__n_neighbors":[3,5,7,9,11],"model__weights":["uniform","distance"],"model__p":[1,2]}},
156
+ "SVR":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",SVR())]),"params":{"model__C":[1,10,100,500],"model__gamma":["scale",0.01,0.1],"model__epsilon":[0.01,0.1,0.2]}},
157
+ "Decision Tree":{"pipeline":Pipeline([("model",DecisionTreeRegressor(random_state=42))]),"params":{"model__max_depth":[None,4,6,8,10,15],"model__min_samples_split":[2,5,10],"model__min_samples_leaf":[1,2,4]}},
158
+ "Random Forest":{"pipeline":Pipeline([("model",RandomForestRegressor(random_state=42,n_jobs=-1))]),"params":{"model__n_estimators":[100,200],"model__max_depth":[None,8,15],"model__min_samples_leaf":[1,2,4],"model__max_features":["sqrt",1.0]}},
159
+ "Gradient Boosting":{"pipeline":Pipeline([("model",GradientBoostingRegressor(random_state=42))]),"params":{"model__n_estimators":[100,200],"model__learning_rate":[0.03,0.05,0.1],"model__max_depth":[2,3,4],"model__subsample":[0.8,1.0]}},
160
+ "AdaBoost":{"pipeline":Pipeline([("model",AdaBoostRegressor(random_state=42))]),"params":{"model__n_estimators":[50,100,200],"model__learning_rate":[0.01,0.05,0.1,0.5]}},
161
+ "ANN":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",MLPRegressor(random_state=42,max_iter=3000,early_stopping=True))]),"params":{"model__hidden_layer_sizes":[(32,),(64,),(64,32),(100,50)],"model__activation":["relu","tanh"],"model__alpha":[0.0001,0.001,0.01],"model__learning_rate_init":[0.001,0.01]}}
162
+ }
163
+
164
+
165
+ # ---------- 17. Tuning and evaluation function ----------
166
+ def evaluate_models(Xtr,Xte,ytr,yte,feature_set_name):
167
+ results=[]; best_models={}
168
+ for model_name,cfg in model_configs.items():
169
+ print("\n"+"="*80); print(feature_set_name,"|",model_name); print("="*80)
170
+ grid=GridSearchCV(cfg["pipeline"],cfg["params"],cv=cv,scoring="neg_root_mean_squared_error",n_jobs=-1,refit=True)
171
+ grid.fit(Xtr,ytr)
172
+ best=grid.best_estimator_; best_models[model_name]=best
173
+ pred=best.predict(Xte)
174
+ cv_rmse=-grid.best_score_
175
+ rmse=mean_squared_error(yte,pred)**0.5
176
+ mae=mean_absolute_error(yte,pred)
177
+ r2=r2_score(yte,pred)
178
+ print("Best parameters:",grid.best_params_)
179
+ print(f"CV RMSE : {cv_rmse:.4f}")
180
+ print(f"Test RMSE : {rmse:.4f}")
181
+ print(f"Test MAE : {mae:.4f}")
182
+ print(f"Test R2 : {r2:.4f}")
183
+ results.append({"Feature_Set":feature_set_name,"Model":model_name,"Best_Parameters":str(grid.best_params_),"CV_RMSE":cv_rmse,"Test_RMSE":rmse,"Test_MAE":mae,"Test_R2":r2})
184
+ return pd.DataFrame(results),best_models
185
+
186
+
187
+ # ---------- 18. Experiment A — Original features ----------
188
+ results_original,models_original=evaluate_models(X_train_original,X_test_original,y_train,y_test,"Original")
189
+ display(results_original.sort_values("Test_RMSE").reset_index(drop=True))
190
+
191
+
192
+ # ---------- 19. Experiment B — Engineered reduced features ----------
193
+ results_engineered,models_engineered=evaluate_models(X_train_engineered,X_test_engineered,y_train,y_test,"Engineered_Reduced")
194
+ display(results_engineered.sort_values("Test_RMSE").reset_index(drop=True))
195
+
196
+
197
+ # ---------- 20. Experiment C — VIF-reduced features ----------
198
+ results_vif,models_vif=evaluate_models(X_train_vif,X_test_vif,y_train,y_test,"VIF_Reduced")
199
+ display(results_vif.sort_values("Test_RMSE").reset_index(drop=True))
200
+
201
+
202
+ # ---------- 21. Final comparison table ----------
203
+ results_all=pd.concat([results_original,results_engineered,results_vif],ignore_index=True)
204
+ results_all=results_all.sort_values(["Test_RMSE","Test_R2"],ascending=[True,False]).reset_index(drop=True)
205
+ display(results_all)
206
+
207
+
208
+ # ---------- 22. RMSE comparison ----------
209
+ plot_df=results_all.copy(); plot_df["Label"]=plot_df["Model"]+" | "+plot_df["Feature_Set"]
210
+ plot_df=plot_df.sort_values("Test_RMSE")
211
+ plt.figure(figsize=(12,9)); plt.barh(plot_df["Label"],plot_df["Test_RMSE"]); plt.xlabel("Test RMSE"); plt.ylabel("Model / Feature Set"); plt.title("Model Comparison by Test RMSE"); plt.tight_layout(); plt.show()
212
+
213
+
214
+ # ---------- 23. R² comparison ----------
215
+ plot_df=results_all.copy(); plot_df["Label"]=plot_df["Model"]+" | "+plot_df["Feature_Set"]
216
+ plot_df=plot_df.sort_values("Test_R2")
217
+ plt.figure(figsize=(12,9)); plt.barh(plot_df["Label"],plot_df["Test_R2"]); plt.xlabel("Test R2"); plt.ylabel("Model / Feature Set"); plt.title("Model Comparison by Test R2"); plt.tight_layout(); plt.show()
218
+
219
+ # Select the configuration using CROSS-VALIDATION performance only.
220
+ # The test set is not used to choose the model.
221
+ selection_table = results_all.sort_values(
222
+ ["CV_RMSE", "Test_RMSE"],
223
+ ascending=[True, True]
224
+ ).reset_index(drop=True)
225
+
226
+ best_row = selection_table.iloc[0]
227
+ best_feature_set = best_row["Feature_Set"]
228
+ best_model_name = best_row["Model"]
229
+
230
+ if best_feature_set == "Original":
231
+ final_model = models_original[best_model_name]
232
+ final_X_test = X_test_original
233
+ elif best_feature_set == "Engineered_Reduced":
234
+ final_model = models_engineered[best_model_name]
235
+ final_X_test = X_test_engineered
236
+ else:
237
+ final_model = models_vif[best_model_name]
238
+ final_X_test = X_test_vif
239
+
240
+ print("Selected using lowest CV RMSE")
241
+ print("Best model:", best_model_name)
242
+ print("Best feature set:", best_feature_set)
243
+ print("\nSelected result:")
244
+ display(best_row.to_frame().T)
245
+
246
+
247
+ # ---------- 25. Actual vs predicted ----------
248
+ y_pred_best=final_model.predict(final_X_test)
249
+ plt.figure(figsize=(7,7)); plt.scatter(y_test,y_pred_best,alpha=0.65)
250
+ low=min(y_test.min(),y_pred_best.min()); high=max(y_test.max(),y_pred_best.max())
251
+ plt.plot([low,high],[low,high],linestyle="--")
252
+ plt.xlabel("Actual Strength (MPa)"); plt.ylabel("Predicted Strength (MPa)"); plt.title(f"Actual vs Predicted\n{best_model_name} | {best_feature_set}"); plt.grid(True); plt.tight_layout(); plt.show()
253
+
254
+
255
+ # ---------- 26. Residual plot ----------
256
+ residuals=y_test.values-y_pred_best
257
+ plt.figure(figsize=(8,5)); plt.scatter(y_pred_best,residuals,alpha=0.65); plt.axhline(0,linestyle="--"); plt.xlabel("Predicted Strength (MPa)"); plt.ylabel("Residual"); plt.title("Residual Plot"); plt.grid(True); plt.tight_layout(); plt.show()
258
+
259
+
260
+ # ---------- 27. Predict a new concrete mixture ----------
261
+ new_mix=pd.DataFrame({"Cement":[350],"Slag":[80],"Fly_Ash":[50],"Water":[180],"Superplasticizer":[8],"Coarse_Aggregate":[1000],"Fine_Aggregate":[750],"Age":[28]})
262
+ display(new_mix)
263
+
264
+ new_mix_eng=engineer_features(new_mix)
265
+ if best_feature_set=="Original": new_mix_final=new_mix[original_features]
266
+ elif best_feature_set=="Engineered_Reduced": new_mix_final=new_mix_eng[engineered_reduced_features]
267
+ else: new_mix_final=new_mix_eng[vif_reduced_features]
268
+ predicted_strength=final_model.predict(new_mix_final)[0]
269
+ print(f"Predicted Concrete Compressive Strength = {predicted_strength:.2f} MPa")
set/regression.py ADDED
@@ -0,0 +1,284 @@
1
+ """Concrete compressive-strength regression workflow (Lab 14).
2
+
3
+ ``load_concrete`` needs the optional ``ucimlrepo`` package and
4
+ ``calculate_vif`` needs ``statsmodels``: pip install "set[regression]"
5
+ """
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+ from sklearn.model_selection import KFold, GridSearchCV
11
+ from sklearn.pipeline import Pipeline
12
+ from sklearn.preprocessing import StandardScaler
13
+ from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
14
+ from sklearn.linear_model import LinearRegression, Ridge
15
+ from sklearn.neighbors import KNeighborsRegressor
16
+ from sklearn.svm import SVR
17
+ from sklearn.tree import DecisionTreeRegressor
18
+ from sklearn.ensemble import (RandomForestRegressor, GradientBoostingRegressor,
19
+ AdaBoostRegressor)
20
+ from sklearn.neural_network import MLPRegressor
21
+
22
+ COLUMN_NAMES = ["Cement", "Slag", "Fly_Ash", "Water", "Superplasticizer",
23
+ "Coarse_Aggregate", "Fine_Aggregate", "Age"]
24
+
25
+ ORIGINAL_FEATURES = list(COLUMN_NAMES)
26
+
27
+ ENGINEERED_REDUCED_FEATURES = [
28
+ "Cement", "Slag", "Fly_Ash", "Superplasticizer", "Coarse_Aggregate",
29
+ "Fine_Aggregate", "Water_Binder_Ratio", "SCM_Fraction",
30
+ "Aggregate_Binder_Ratio", "Log_Age",
31
+ ]
32
+
33
+ VIF_REDUCED_FEATURES = [
34
+ "Cement", "Slag", "Fly_Ash", "Superplasticizer", "Coarse_Aggregate",
35
+ "Fine_Aggregate", "Water_Binder_Ratio", "Log_Age",
36
+ ]
37
+
38
+ _FEATURE_SETS = {
39
+ "Original": ORIGINAL_FEATURES,
40
+ "Engineered_Reduced": ENGINEERED_REDUCED_FEATURES,
41
+ "VIF_Reduced": VIF_REDUCED_FEATURES,
42
+ }
43
+
44
+
45
+ # --------------------------------------------------------------------------
46
+ # Data
47
+ # --------------------------------------------------------------------------
48
+ def load_concrete():
49
+ """Download the UCI Concrete Compressive Strength data (id=165).
50
+
51
+ Returns a DataFrame with the 8 features and a ``Strength`` column.
52
+ """
53
+ try:
54
+ from ucimlrepo import fetch_ucirepo
55
+ except ImportError as e:
56
+ raise ImportError(
57
+ 'load_concrete() needs ucimlrepo: pip install "set[regression]"'
58
+ ) from e
59
+ concrete = fetch_ucirepo(id=165)
60
+ X = concrete.data.features.copy()
61
+ y = concrete.data.targets.iloc[:, 0].copy()
62
+ X.columns = COLUMN_NAMES
63
+ y.name = "Strength"
64
+ df = X.copy()
65
+ df["Strength"] = y
66
+ return df
67
+
68
+
69
+ def clean_data(df, verbose=True):
70
+ """Drop duplicate rows and return (X, y). Prints basic quality checks."""
71
+ if verbose:
72
+ print("Missing values:", int(df.isnull().sum().sum()))
73
+ print("Duplicate rows:", int(df.duplicated().sum()))
74
+ neg = (df.select_dtypes(include=np.number) < 0).sum().sum()
75
+ print("Negative values:", int(neg))
76
+ before = len(df)
77
+ df = df.drop_duplicates().reset_index(drop=True)
78
+ if verbose:
79
+ print(f"Rows before: {before} | after: {len(df)}")
80
+ return df.drop(columns="Strength"), df["Strength"].copy()
81
+
82
+
83
+ def engineer_features(X):
84
+ """Add binder-based ratios and Log_Age (6 new columns)."""
85
+ X = X.copy()
86
+ eps = 1e-8
87
+ binder = X["Cement"] + X["Slag"] + X["Fly_Ash"]
88
+ scm = X["Slag"] + X["Fly_Ash"]
89
+ total_agg = X["Coarse_Aggregate"] + X["Fine_Aggregate"]
90
+ X["Water_Binder_Ratio"] = X["Water"] / (binder + eps)
91
+ X["SCM_Fraction"] = scm / (binder + eps)
92
+ X["Cement_Fraction"] = X["Cement"] / (binder + eps)
93
+ X["Aggregate_Binder_Ratio"] = total_agg / (binder + eps)
94
+ X["Superplasticizer_Binder_Ratio"] = X["Superplasticizer"] / (binder + eps)
95
+ X["Log_Age"] = np.log1p(X["Age"])
96
+ return X
97
+
98
+
99
+ def select_feature_sets(X_train_raw, X_test_raw):
100
+ """Build the three feature sets used in Lab 14.
101
+
102
+ Returns dict: name -> (X_train, X_test) for Original, Engineered_Reduced
103
+ and VIF_Reduced.
104
+ """
105
+ tr_eng = engineer_features(X_train_raw)
106
+ te_eng = engineer_features(X_test_raw)
107
+ return {
108
+ "Original": (X_train_raw[ORIGINAL_FEATURES].copy(),
109
+ X_test_raw[ORIGINAL_FEATURES].copy()),
110
+ "Engineered_Reduced": (tr_eng[ENGINEERED_REDUCED_FEATURES].copy(),
111
+ te_eng[ENGINEERED_REDUCED_FEATURES].copy()),
112
+ "VIF_Reduced": (tr_eng[VIF_REDUCED_FEATURES].copy(),
113
+ te_eng[VIF_REDUCED_FEATURES].copy()),
114
+ }
115
+
116
+
117
+ def calculate_vif(X):
118
+ """Variance Inflation Factor for each numeric column (needs statsmodels)."""
119
+ try:
120
+ from statsmodels.stats.outliers_influence import variance_inflation_factor
121
+ except ImportError as e:
122
+ raise ImportError(
123
+ 'calculate_vif() needs statsmodels: pip install "set[regression]"'
124
+ ) from e
125
+ Xn = X.select_dtypes(include=np.number).copy()
126
+ out = pd.DataFrame({"Feature": Xn.columns})
127
+ out["VIF"] = [variance_inflation_factor(Xn.values, i)
128
+ for i in range(Xn.shape[1])]
129
+ return out.sort_values("VIF", ascending=False).reset_index(drop=True)
130
+
131
+
132
+ # --------------------------------------------------------------------------
133
+ # Models
134
+ # --------------------------------------------------------------------------
135
+ def get_model_configs():
136
+ """The 9 models and hyper-parameter grids from Lab 14."""
137
+ def scaled(model):
138
+ return Pipeline([("scaler", StandardScaler()), ("model", model)])
139
+
140
+ def plain(model):
141
+ return Pipeline([("model", model)])
142
+
143
+ return {
144
+ "Linear Regression": {"pipeline": scaled(LinearRegression()), "params": {}},
145
+ "Ridge": {"pipeline": scaled(Ridge()),
146
+ "params": {"model__alpha": [0.01, 0.1, 1, 10, 100]}},
147
+ "KNN": {"pipeline": scaled(KNeighborsRegressor()),
148
+ "params": {"model__n_neighbors": [3, 5, 7, 9, 11],
149
+ "model__weights": ["uniform", "distance"],
150
+ "model__p": [1, 2]}},
151
+ "SVR": {"pipeline": scaled(SVR()),
152
+ "params": {"model__C": [1, 10, 100, 500],
153
+ "model__gamma": ["scale", 0.01, 0.1],
154
+ "model__epsilon": [0.01, 0.1, 0.2]}},
155
+ "Decision Tree": {"pipeline": plain(DecisionTreeRegressor(random_state=42)),
156
+ "params": {"model__max_depth": [None, 4, 6, 8, 10, 15],
157
+ "model__min_samples_split": [2, 5, 10],
158
+ "model__min_samples_leaf": [1, 2, 4]}},
159
+ "Random Forest": {"pipeline": plain(RandomForestRegressor(random_state=42, n_jobs=-1)),
160
+ "params": {"model__n_estimators": [100, 200],
161
+ "model__max_depth": [None, 8, 15],
162
+ "model__min_samples_leaf": [1, 2, 4],
163
+ "model__max_features": ["sqrt", 1.0]}},
164
+ "Gradient Boosting": {"pipeline": plain(GradientBoostingRegressor(random_state=42)),
165
+ "params": {"model__n_estimators": [100, 200],
166
+ "model__learning_rate": [0.03, 0.05, 0.1],
167
+ "model__max_depth": [2, 3, 4],
168
+ "model__subsample": [0.8, 1.0]}},
169
+ "AdaBoost": {"pipeline": plain(AdaBoostRegressor(random_state=42)),
170
+ "params": {"model__n_estimators": [50, 100, 200],
171
+ "model__learning_rate": [0.01, 0.05, 0.1, 0.5]}},
172
+ "ANN": {"pipeline": scaled(MLPRegressor(random_state=42, max_iter=3000,
173
+ early_stopping=True)),
174
+ "params": {"model__hidden_layer_sizes": [(32,), (64,), (64, 32), (100, 50)],
175
+ "model__activation": ["relu", "tanh"],
176
+ "model__alpha": [0.0001, 0.001, 0.01],
177
+ "model__learning_rate_init": [0.001, 0.01]}},
178
+ }
179
+
180
+
181
+ def evaluate_models(X_train, X_test, y_train, y_test, feature_set_name,
182
+ model_configs=None, cv=None, verbose=True):
183
+ """Grid-search every model with 5-fold CV and score on the test set.
184
+
185
+ Parameters
186
+ ----------
187
+ model_configs : dict, optional
188
+ Defaults to ``get_model_configs()``. Pass a subset (or smaller grids)
189
+ for a quick run.
190
+
191
+ Returns
192
+ -------
193
+ results : DataFrame (CV_RMSE, Test_RMSE, Test_MAE, Test_R2 per model)
194
+ best_models : dict model name -> fitted best pipeline
195
+ """
196
+ if model_configs is None:
197
+ model_configs = get_model_configs()
198
+ if cv is None:
199
+ cv = KFold(n_splits=5, shuffle=True, random_state=42)
200
+
201
+ results, best_models = [], {}
202
+ for name, cfg in model_configs.items():
203
+ grid = GridSearchCV(cfg["pipeline"], cfg["params"], cv=cv,
204
+ scoring="neg_root_mean_squared_error",
205
+ n_jobs=-1, refit=True)
206
+ grid.fit(X_train, y_train)
207
+ best = grid.best_estimator_
208
+ best_models[name] = best
209
+ pred = best.predict(X_test)
210
+ row = {
211
+ "Feature_Set": feature_set_name,
212
+ "Model": name,
213
+ "Best_Parameters": str(grid.best_params_),
214
+ "CV_RMSE": -grid.best_score_,
215
+ "Test_RMSE": mean_squared_error(y_test, pred) ** 0.5,
216
+ "Test_MAE": mean_absolute_error(y_test, pred),
217
+ "Test_R2": r2_score(y_test, pred),
218
+ }
219
+ results.append(row)
220
+ if verbose:
221
+ print(f"{feature_set_name} | {name}: CV RMSE={row['CV_RMSE']:.4f} "
222
+ f"Test RMSE={row['Test_RMSE']:.4f} R2={row['Test_R2']:.4f}")
223
+ return pd.DataFrame(results), best_models
224
+
225
+
226
+ def select_best_model(results_all, models_by_set):
227
+ """Pick the final model by lowest CV RMSE (not by test score).
228
+
229
+ Parameters
230
+ ----------
231
+ results_all : concatenated results DataFrames from ``evaluate_models``
232
+ models_by_set : dict feature-set name -> best_models dict
233
+
234
+ Returns (final_model, feature_set_name, model_name, best_row)
235
+ """
236
+ table = results_all.sort_values(["CV_RMSE", "Test_RMSE"]).reset_index(drop=True)
237
+ row = table.iloc[0]
238
+ fs, name = row["Feature_Set"], row["Model"]
239
+ return models_by_set[fs][name], fs, name, row
240
+
241
+
242
+ # --------------------------------------------------------------------------
243
+ # Plots and prediction
244
+ # --------------------------------------------------------------------------
245
+ def plot_actual_vs_predicted(y_true, y_pred, title="Actual vs Predicted", show=True):
246
+ y_true = np.asarray(y_true)
247
+ plt.figure(figsize=(7, 7))
248
+ plt.scatter(y_true, y_pred, alpha=0.65)
249
+ low, high = min(y_true.min(), y_pred.min()), max(y_true.max(), y_pred.max())
250
+ plt.plot([low, high], [low, high], linestyle="--")
251
+ plt.xlabel("Actual Strength (MPa)")
252
+ plt.ylabel("Predicted Strength (MPa)")
253
+ plt.title(title)
254
+ plt.grid(True)
255
+ plt.tight_layout()
256
+ if show:
257
+ plt.show()
258
+
259
+
260
+ def plot_residuals(y_true, y_pred, show=True):
261
+ residuals = np.asarray(y_true) - np.asarray(y_pred)
262
+ plt.figure(figsize=(8, 5))
263
+ plt.scatter(y_pred, residuals, alpha=0.65)
264
+ plt.axhline(0, linestyle="--")
265
+ plt.xlabel("Predicted Strength (MPa)")
266
+ plt.ylabel("Residual")
267
+ plt.title("Residual Plot")
268
+ plt.grid(True)
269
+ plt.tight_layout()
270
+ if show:
271
+ plt.show()
272
+ return residuals
273
+
274
+
275
+ def predict_new_mix(model, feature_set_name, mix):
276
+ """Predict strength (MPa) for a new mixture.
277
+
278
+ ``mix`` is a dict or one-row DataFrame with the 8 raw columns:
279
+ Cement, Slag, Fly_Ash, Water, Superplasticizer, Coarse_Aggregate,
280
+ Fine_Aggregate, Age.
281
+ """
282
+ mix = pd.DataFrame(mix) if not isinstance(mix, pd.DataFrame) else mix
283
+ cols = _FEATURE_SETS[feature_set_name]
284
+ return float(model.predict(engineer_features(mix)[cols])[0])