fomltools 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.
- fomltools/__init__.py +10 -0
- fomltools/labs/__init__.py +5 -0
- fomltools/labs/lab01.py +210 -0
- fomltools/labs/lab02.py +233 -0
- fomltools/labs/lab03.py +62 -0
- fomltools/labs/lab04.py +81 -0
- fomltools/labs/lab05.py +171 -0
- fomltools/labs/lab06.py +174 -0
- fomltools/labs/lab07.py +192 -0
- fomltools/labs/lab08.py +202 -0
- fomltools/labs/lab09.py +335 -0
- fomltools/labs/lab10.py +111 -0
- fomltools/labs/lab11.py +103 -0
- fomltools/labs/lab12.py +68 -0
- fomltools/labs/lab14.py +251 -0
- fomltools-0.1.0.dist-info/METADATA +43 -0
- fomltools-0.1.0.dist-info/RECORD +20 -0
- fomltools-0.1.0.dist-info/WHEEL +5 -0
- fomltools-0.1.0.dist-info/licenses/LICENSE +21 -0
- fomltools-0.1.0.dist-info/top_level.txt +1 -0
fomltools/labs/lab11.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Lab 11 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
from sklearn.cluster import KMeans
|
|
7
|
+
from sklearn.datasets import load_wine
|
|
8
|
+
from sklearn.preprocessing import StandardScaler
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
# Load the Wine dataset
|
|
12
|
+
|
|
13
|
+
wine = load_wine()
|
|
14
|
+
|
|
15
|
+
X = pd.DataFrame(wine.data, columns=wine.feature_names)
|
|
16
|
+
display(X.head())
|
|
17
|
+
print("\nDataset shape: ", X.shape)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Perform Standard Scaling
|
|
21
|
+
scaler = StandardScaler()
|
|
22
|
+
|
|
23
|
+
X_scaled = scaler.fit_transform(X)
|
|
24
|
+
|
|
25
|
+
# Finding kmeans
|
|
26
|
+
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
|
|
27
|
+
|
|
28
|
+
kmeans.fit(X_scaled)
|
|
29
|
+
|
|
30
|
+
print("Cluster Labels: ")
|
|
31
|
+
print(kmeans.labels_)
|
|
32
|
+
print("Cluster Centroids: ")
|
|
33
|
+
print(kmeans.cluster_centers_)
|
|
34
|
+
|
|
35
|
+
X['Cluster'] = kmeans.labels_
|
|
36
|
+
display(X.head(10))
|
|
37
|
+
|
|
38
|
+
print(X['Cluster'].value_counts())
|
|
39
|
+
|
|
40
|
+
# PLotting the Cluster
|
|
41
|
+
plt.scatter(X['alcohol'], X['color_intensity'], c=X['Cluster'], cmap='plasma')
|
|
42
|
+
plt.xlabel('Alcohol')
|
|
43
|
+
plt.ylabel('Color Intensity')
|
|
44
|
+
plt.title('K-Means Clustering of Wine Dataset')
|
|
45
|
+
|
|
46
|
+
plt.show()
|
|
47
|
+
|
|
48
|
+
import numpy as np
|
|
49
|
+
|
|
50
|
+
# Sample Data
|
|
51
|
+
X = np.array([[1,2],[1,4],[2,3],[2,5],[8,2],[8,4],[9,3],[9,5]])
|
|
52
|
+
|
|
53
|
+
# Plot original data
|
|
54
|
+
plt.scatter(X[:,0], X[:,1])
|
|
55
|
+
plt.xlabel('X1')
|
|
56
|
+
plt.ylabel('X2')
|
|
57
|
+
plt.title('Original Data')
|
|
58
|
+
plt.show()
|
|
59
|
+
|
|
60
|
+
# K-means clustering
|
|
61
|
+
kmeans2 = KMeans(n_clusters=2, random_state=42, n_init=10)
|
|
62
|
+
|
|
63
|
+
kmeans2.fit(X)
|
|
64
|
+
print("Cluster Labels: ")
|
|
65
|
+
print(kmeans2.labels_)
|
|
66
|
+
print("Cluster Centroids: ")
|
|
67
|
+
print(kmeans2.cluster_centers_)
|
|
68
|
+
|
|
69
|
+
# PLotting the Cluster
|
|
70
|
+
plt.scatter(X[:,0], X[:,1], c=kmeans2.labels_)
|
|
71
|
+
plt.xlabel('X1')
|
|
72
|
+
plt.ylabel('X2')
|
|
73
|
+
plt.title('Data after K-Means Clustering')
|
|
74
|
+
|
|
75
|
+
plt.show()
|
|
76
|
+
|
|
77
|
+
# Practice Question
|
|
78
|
+
# Data: [[1,1],[1,3],[2,2],[2,4],[5,7],[6,6],[6,8],[7,7],[9,1],[9,3],[10,2],[10,4]]. Perform K-means clustering with: K=3
|
|
79
|
+
|
|
80
|
+
X2 = np.array([[1,1],[1,3],[2,2],[2,4],[5,7],[6,6],[6,8],[7,7],[9,1],[9,3],[10,2],[10,4]])
|
|
81
|
+
|
|
82
|
+
# Plot original data
|
|
83
|
+
plt.scatter(X2[:,0], X2[:,1])
|
|
84
|
+
plt.xlabel('X1')
|
|
85
|
+
plt.ylabel('X2')
|
|
86
|
+
plt.title('Original Data')
|
|
87
|
+
plt.show()
|
|
88
|
+
|
|
89
|
+
# K-means clustering
|
|
90
|
+
kmeans3 = KMeans(n_clusters=3, random_state=42, n_init=10)
|
|
91
|
+
|
|
92
|
+
kmeans3.fit(X2)
|
|
93
|
+
print("Cluster Labels: ")
|
|
94
|
+
print(kmeans3.labels_)
|
|
95
|
+
print("Cluster Centroids: ")
|
|
96
|
+
print(kmeans3.cluster_centers_)
|
|
97
|
+
|
|
98
|
+
plt.scatter(X2[:,0], X2[:,1], c=kmeans3.labels_)
|
|
99
|
+
plt.xlabel('X1')
|
|
100
|
+
plt.ylabel('X2')
|
|
101
|
+
plt.title('Data after K-Means Clustering')
|
|
102
|
+
|
|
103
|
+
plt.show()
|
fomltools/labs/lab12.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Lab 12 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
|
|
9
|
+
from sklearn.datasets import load_iris
|
|
10
|
+
from sklearn.preprocessing import StandardScaler
|
|
11
|
+
from sklearn.cluster import AgglomerativeClustering
|
|
12
|
+
from sklearn.metrics import silhouette_score
|
|
13
|
+
from scipy.cluster.hierarchy import linkage, dendrogram
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# Load Dataset
|
|
18
|
+
iris = load_iris()
|
|
19
|
+
X = pd.DataFrame (iris.data, columns=iris.feature_names)
|
|
20
|
+
y = iris.target
|
|
21
|
+
print(X.shape)
|
|
22
|
+
X.head()
|
|
23
|
+
|
|
24
|
+
# Standardize
|
|
25
|
+
scaler = StandardScaler()
|
|
26
|
+
X_scaled = scaler.fit_transform(X)
|
|
27
|
+
|
|
28
|
+
# Dendogram
|
|
29
|
+
Z = linkage(X_scaled, method = "ward")
|
|
30
|
+
|
|
31
|
+
plt.figure(figsize=(12, 6))
|
|
32
|
+
dendrogram(Z)
|
|
33
|
+
plt.title("Agglomerative Clustering Dendrogram")
|
|
34
|
+
plt.xlabel("Observations")
|
|
35
|
+
plt.ylabel("Merge Distance")
|
|
36
|
+
plt.show()
|
|
37
|
+
|
|
38
|
+
# Compare Linkage Methods
|
|
39
|
+
|
|
40
|
+
methods = ['single','complete','average', 'ward']
|
|
41
|
+
results = []
|
|
42
|
+
|
|
43
|
+
for method in methods:
|
|
44
|
+
model = AgglomerativeClustering(n_clusters=3, linkage=method)
|
|
45
|
+
labels = model.fit_predict(X_scaled)
|
|
46
|
+
score = silhouette_score(X_scaled, labels)
|
|
47
|
+
results.append([method, score])
|
|
48
|
+
|
|
49
|
+
pd.DataFrame(results, columns=["Linkage", "Silhouette Score"])
|
|
50
|
+
# silhouette scored is used to find out the efficiency of clustering.
|
|
51
|
+
#The higher the score, the better the clustering.
|
|
52
|
+
#The silhouette score ranges from -1 to 1, where a score close to 1 indicates
|
|
53
|
+
#that the samples are well clustered, a score close to 0 indicates that the
|
|
54
|
+
#samples are on or very close to the decision boundary between two neighboring
|
|
55
|
+
#clusters, and a score close to -1 indicates that the samples might have been
|
|
56
|
+
#assigned to the wrong cluster.
|
|
57
|
+
|
|
58
|
+
model = AgglomerativeClustering(n_clusters=3, linkage='ward')
|
|
59
|
+
labels = model.fit_predict(X_scaled)
|
|
60
|
+
|
|
61
|
+
plt.figure(figsize=(12, 6))
|
|
62
|
+
plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=labels)
|
|
63
|
+
plt.xlabel("Standardized Sepal length")
|
|
64
|
+
plt.ylabel("Standardized Sepal Width")
|
|
65
|
+
plt.title("Ward Agglomerative Clustering")
|
|
66
|
+
plt.show()
|
|
67
|
+
|
|
68
|
+
pd.crosstab(y,labels,rownames=['Actual Class'],colnames=['Cluster'])
|
fomltools/labs/lab14.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Lab 14 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
#!pip -q install ucimlrepo statsmodels
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import warnings
|
|
9
|
+
warnings.filterwarnings("ignore")
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
from ucimlrepo import fetch_ucirepo
|
|
14
|
+
from sklearn.model_selection import train_test_split, KFold, GridSearchCV
|
|
15
|
+
from sklearn.pipeline import Pipeline
|
|
16
|
+
from sklearn.preprocessing import StandardScaler
|
|
17
|
+
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
|
|
18
|
+
from sklearn.linear_model import LinearRegression, Ridge
|
|
19
|
+
from sklearn.neighbors import KNeighborsRegressor
|
|
20
|
+
from sklearn.svm import SVR
|
|
21
|
+
from sklearn.tree import DecisionTreeRegressor
|
|
22
|
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
|
|
23
|
+
from sklearn.neural_network import MLPRegressor
|
|
24
|
+
from statsmodels.stats.outliers_influence import variance_inflation_factor
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
concrete = fetch_ucirepo(id=165)
|
|
28
|
+
X = concrete.data.features.copy()
|
|
29
|
+
y = concrete.data.targets.iloc[:,0].copy()
|
|
30
|
+
X.columns=["Cement","Slag","Fly_Ash","Water",
|
|
31
|
+
"Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Age"]
|
|
32
|
+
y.name="Strength"
|
|
33
|
+
df=X.copy(); df["Strength"]=y
|
|
34
|
+
print("Dataset shape:", df.shape)
|
|
35
|
+
df.head()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
print("DATA TYPES")
|
|
39
|
+
print(df.dtypes)
|
|
40
|
+
print("\nMISSING VALUES")
|
|
41
|
+
print(df.isnull().sum())
|
|
42
|
+
print("\nDUPLICATE ROWS")
|
|
43
|
+
print(df.duplicated().sum())
|
|
44
|
+
print("\nNEGATIVE VALUES")
|
|
45
|
+
print((df.select_dtypes(include=np.number)<0).sum())
|
|
46
|
+
print("\nSUMMARY STATISTICS")
|
|
47
|
+
display(df.describe().round(2))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
before=len(df)
|
|
51
|
+
df=df.drop_duplicates().reset_index(drop=True)
|
|
52
|
+
after=len(df)
|
|
53
|
+
print("Rows before:",before)
|
|
54
|
+
print("Rows after :",after)
|
|
55
|
+
X=df.drop(columns="Strength")
|
|
56
|
+
y=df["Strength"].copy()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
df.hist(figsize=(14,10), bins=25)
|
|
60
|
+
plt.suptitle("Feature and Target Distributions", y=1.02)
|
|
61
|
+
plt.tight_layout(); plt.show()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
for col in df.columns:
|
|
65
|
+
plt.figure(figsize=(7,2.8))
|
|
66
|
+
plt.boxplot(df[col], vert=False)
|
|
67
|
+
plt.title(f"Boxplot: {col}")
|
|
68
|
+
plt.xlabel(col)
|
|
69
|
+
plt.tight_layout(); plt.show()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
corr=df.corr(numeric_only=True)
|
|
73
|
+
plt.figure(figsize=(10,8))
|
|
74
|
+
plt.imshow(corr, aspect="auto")
|
|
75
|
+
plt.colorbar()
|
|
76
|
+
plt.xticks(range(len(corr.columns)), corr.columns, rotation=90)
|
|
77
|
+
plt.yticks(range(len(corr.columns)), corr.columns)
|
|
78
|
+
plt.title("Correlation Matrix")
|
|
79
|
+
plt.tight_layout(); plt.show()
|
|
80
|
+
display(corr.round(3))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
target_corr=corr["Strength"].sort_values(ascending=False)
|
|
84
|
+
plt.figure(figsize=(9,5))
|
|
85
|
+
target_corr.drop("Strength").plot(kind="bar")
|
|
86
|
+
plt.title("Correlation of Original Features with Strength")
|
|
87
|
+
plt.ylabel("Correlation")
|
|
88
|
+
plt.xticks(rotation=45)
|
|
89
|
+
plt.tight_layout(); plt.show()
|
|
90
|
+
display(target_corr.to_frame("Correlation").round(3))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
X_train_raw,X_test_raw,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state=42)
|
|
94
|
+
print("Training rows:",len(X_train_raw))
|
|
95
|
+
print("Testing rows :",len(X_test_raw))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def engineer_features(X):
|
|
99
|
+
X=X.copy(); eps=1e-8
|
|
100
|
+
binder=X["Cement"]+X["Slag"]+X["Fly_Ash"]
|
|
101
|
+
scm=X["Slag"]+X["Fly_Ash"]
|
|
102
|
+
total_agg=X["Coarse_Aggregate"]+X["Fine_Aggregate"]
|
|
103
|
+
X["Water_Binder_Ratio"]=X["Water"]/(binder+eps)
|
|
104
|
+
X["SCM_Fraction"]=scm/(binder+eps)
|
|
105
|
+
X["Cement_Fraction"]=X["Cement"]/(binder+eps)
|
|
106
|
+
X["Aggregate_Binder_Ratio"]=total_agg/(binder+eps)
|
|
107
|
+
X["Superplasticizer_Binder_Ratio"]=X["Superplasticizer"]/(binder+eps)
|
|
108
|
+
X["Log_Age"]=np.log1p(X["Age"])
|
|
109
|
+
return X
|
|
110
|
+
X_train_eng_full=engineer_features(X_train_raw)
|
|
111
|
+
X_test_eng_full=engineer_features(X_test_raw)
|
|
112
|
+
print("Original feature count:",X_train_raw.shape[1])
|
|
113
|
+
print("After engineering:",X_train_eng_full.shape[1])
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
original_features=["Cement","Slag","Fly_Ash","Water","Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Age"]
|
|
117
|
+
engineered_reduced_features=["Cement","Slag","Fly_Ash","Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Water_Binder_Ratio","SCM_Fraction","Aggregate_Binder_Ratio","Log_Age"]
|
|
118
|
+
X_train_original=X_train_raw[original_features].copy(); X_test_original=X_test_raw[original_features].copy()
|
|
119
|
+
X_train_engineered=X_train_eng_full[engineered_reduced_features].copy(); X_test_engineered=X_test_eng_full[engineered_reduced_features].copy()
|
|
120
|
+
print("Original:",len(original_features))
|
|
121
|
+
print("Engineered reduced:",len(engineered_reduced_features))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def calculate_vif(X):
|
|
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) for i in range(Xn.shape[1])]
|
|
128
|
+
return out.sort_values("VIF",ascending=False).reset_index(drop=True)
|
|
129
|
+
display(calculate_vif(X_train_engineered).round(2))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
vif_reduced_features=["Cement","Slag","Fly_Ash","Superplasticizer","Coarse_Aggregate","Fine_Aggregate","Water_Binder_Ratio","Log_Age"]
|
|
133
|
+
X_train_vif=X_train_eng_full[vif_reduced_features].copy(); X_test_vif=X_test_eng_full[vif_reduced_features].copy()
|
|
134
|
+
print("VIF-reduced feature count:",len(vif_reduced_features))
|
|
135
|
+
display(calculate_vif(X_train_vif).round(2))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
cv=KFold(n_splits=5,shuffle=True,random_state=42)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
model_configs={
|
|
142
|
+
"Linear Regression":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",LinearRegression())]),"params":{}},
|
|
143
|
+
"Ridge":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",Ridge())]),"params":{"model__alpha":[0.01,0.1,1,10,100]}},
|
|
144
|
+
"KNN":{"pipeline":Pipeline([("scaler",StandardScaler()),("model",KNeighborsRegressor())]),"params":{"model__n_neighbors":[3,5,7,9,11],"model__weights":["uniform","distance"],"model__p":[1,2]}},
|
|
145
|
+
"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]}},
|
|
146
|
+
"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]}},
|
|
147
|
+
"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]}},
|
|
148
|
+
"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]}},
|
|
149
|
+
"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]}},
|
|
150
|
+
"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]}}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def evaluate_models(Xtr,Xte,ytr,yte,feature_set_name):
|
|
155
|
+
results=[]; best_models={}
|
|
156
|
+
for model_name,cfg in model_configs.items():
|
|
157
|
+
print("\n"+"="*80); print(feature_set_name,"|",model_name); print("="*80)
|
|
158
|
+
grid=GridSearchCV(cfg["pipeline"],cfg["params"],cv=cv,scoring="neg_root_mean_squared_error",n_jobs=-1,refit=True)
|
|
159
|
+
grid.fit(Xtr,ytr)
|
|
160
|
+
best=grid.best_estimator_; best_models[model_name]=best
|
|
161
|
+
pred=best.predict(Xte)
|
|
162
|
+
cv_rmse=-grid.best_score_
|
|
163
|
+
rmse=mean_squared_error(yte,pred)**0.5
|
|
164
|
+
mae=mean_absolute_error(yte,pred)
|
|
165
|
+
r2=r2_score(yte,pred)
|
|
166
|
+
print("Best parameters:",grid.best_params_)
|
|
167
|
+
print(f"CV RMSE : {cv_rmse:.4f}")
|
|
168
|
+
print(f"Test RMSE : {rmse:.4f}")
|
|
169
|
+
print(f"Test MAE : {mae:.4f}")
|
|
170
|
+
print(f"Test R2 : {r2:.4f}")
|
|
171
|
+
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})
|
|
172
|
+
return pd.DataFrame(results),best_models
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
results_original,models_original=evaluate_models(X_train_original,X_test_original,y_train,y_test,"Original")
|
|
176
|
+
display(results_original.sort_values("Test_RMSE").reset_index(drop=True))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
results_engineered,models_engineered=evaluate_models(X_train_engineered,X_test_engineered,y_train,y_test,"Engineered_Reduced")
|
|
180
|
+
display(results_engineered.sort_values("Test_RMSE").reset_index(drop=True))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
results_vif,models_vif=evaluate_models(X_train_vif,X_test_vif,y_train,y_test,"VIF_Reduced")
|
|
184
|
+
display(results_vif.sort_values("Test_RMSE").reset_index(drop=True))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
results_all=pd.concat([results_original,results_engineered,results_vif],ignore_index=True)
|
|
188
|
+
results_all=results_all.sort_values(["Test_RMSE","Test_R2"],ascending=[True,False]).reset_index(drop=True)
|
|
189
|
+
display(results_all)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
plot_df=results_all.copy(); plot_df["Label"]=plot_df["Model"]+" | "+plot_df["Feature_Set"]
|
|
193
|
+
plot_df=plot_df.sort_values("Test_RMSE")
|
|
194
|
+
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()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
plot_df=results_all.copy(); plot_df["Label"]=plot_df["Model"]+" | "+plot_df["Feature_Set"]
|
|
198
|
+
plot_df=plot_df.sort_values("Test_R2")
|
|
199
|
+
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()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# Select the configuration using CROSS-VALIDATION performance only.
|
|
203
|
+
# The test set is not used to choose the model.
|
|
204
|
+
selection_table = results_all.sort_values(
|
|
205
|
+
["CV_RMSE", "Test_RMSE"],
|
|
206
|
+
ascending=[True, True]
|
|
207
|
+
).reset_index(drop=True)
|
|
208
|
+
|
|
209
|
+
best_row = selection_table.iloc[0]
|
|
210
|
+
best_feature_set = best_row["Feature_Set"]
|
|
211
|
+
best_model_name = best_row["Model"]
|
|
212
|
+
|
|
213
|
+
if best_feature_set == "Original":
|
|
214
|
+
final_model = models_original[best_model_name]
|
|
215
|
+
final_X_test = X_test_original
|
|
216
|
+
elif best_feature_set == "Engineered_Reduced":
|
|
217
|
+
final_model = models_engineered[best_model_name]
|
|
218
|
+
final_X_test = X_test_engineered
|
|
219
|
+
else:
|
|
220
|
+
final_model = models_vif[best_model_name]
|
|
221
|
+
final_X_test = X_test_vif
|
|
222
|
+
|
|
223
|
+
print("Selected using lowest CV RMSE")
|
|
224
|
+
print("Best model:", best_model_name)
|
|
225
|
+
print("Best feature set:", best_feature_set)
|
|
226
|
+
print("\nSelected result:")
|
|
227
|
+
display(best_row.to_frame().T)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
y_pred_best=final_model.predict(final_X_test)
|
|
231
|
+
plt.figure(figsize=(7,7)); plt.scatter(y_test,y_pred_best,alpha=0.65)
|
|
232
|
+
low=min(y_test.min(),y_pred_best.min()); high=max(y_test.max(),y_pred_best.max())
|
|
233
|
+
plt.plot([low,high],[low,high],linestyle="--")
|
|
234
|
+
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()
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
residuals=y_test.values-y_pred_best
|
|
238
|
+
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()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
new_mix=pd.DataFrame({"Cement":[350],"Slag":[80],"Fly_Ash":[50],"Water":[180],"Superplasticizer":[8],"Coarse_Aggregate":[1000],"Fine_Aggregate":[750],"Age":[28]})
|
|
242
|
+
display(new_mix)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
new_mix_eng=engineer_features(new_mix)
|
|
246
|
+
if best_feature_set=="Original": new_mix_final=new_mix[original_features]
|
|
247
|
+
elif best_feature_set=="Engineered_Reduced": new_mix_final=new_mix_eng[engineered_reduced_features]
|
|
248
|
+
else: new_mix_final=new_mix_eng[vif_reduced_features]
|
|
249
|
+
predicted_strength=final_model.predict(new_mix_final)[0]
|
|
250
|
+
print(f"Predicted Concrete Compressive Strength = {predicted_strength:.2f} MPa")
|
|
251
|
+
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fomltools
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Foundations of Machine Learning lab utilities and experiments
|
|
5
|
+
Author: Janak Chauhan
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://pypi.org/
|
|
8
|
+
Keywords: machine-learning,foml,data-science,numpy,scikit-learn,jupyter
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# FOML Tools
|
|
18
|
+
|
|
19
|
+
Python package containing the code from the uploaded Foundations of Machine Learning (FOML) lab notebooks.
|
|
20
|
+
|
|
21
|
+
## Included labs
|
|
22
|
+
|
|
23
|
+
Labs 1-12 and 14 are included. Lab 13 was not present in the uploaded files.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
pip install fomltools
|
|
28
|
+
|
|
29
|
+
## Run a lab
|
|
30
|
+
|
|
31
|
+
import fomltools
|
|
32
|
+
fomltools.run_lab(4)
|
|
33
|
+
|
|
34
|
+
Or:
|
|
35
|
+
|
|
36
|
+
from fomltools.labs import lab06
|
|
37
|
+
lab06.run()
|
|
38
|
+
|
|
39
|
+
## Lab dependencies
|
|
40
|
+
|
|
41
|
+
pip install numpy pandas matplotlib scikit-learn scipy statsmodels ucimlrepo opencv-python tensorflow
|
|
42
|
+
|
|
43
|
+
The original notebooks are included in the source archive for reference. Some labs use external datasets or local files such as the `pics` folder in Lab 9.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
fomltools/__init__.py,sha256=N0KeOchhNzqE4IPAmuphVXp1K8uUzbfqcN92ws0lzaQ,369
|
|
2
|
+
fomltools/labs/__init__.py,sha256=04xZne1PgBh9YiKMKENSbDFBc9w5XqLKJlu1khWHs2c,110
|
|
3
|
+
fomltools/labs/lab01.py,sha256=s0P-L2dUCvp8hORm9VkXiY_31aXlIr_pOQ8qdyH9uTU,4518
|
|
4
|
+
fomltools/labs/lab02.py,sha256=3L3ckOhZaHFTPlJ6kGa7qucJMsx6JjlWtpeGR7WbHSw,5405
|
|
5
|
+
fomltools/labs/lab03.py,sha256=tNouou2gvXmlRmcX3Hockci-mKVVmp0xNyb0dVSVpxw,1380
|
|
6
|
+
fomltools/labs/lab04.py,sha256=TNNAB3IcWSNeHB8Zints1cyU9PYeWAGZaOt9WB_GKWo,1648
|
|
7
|
+
fomltools/labs/lab05.py,sha256=YQ3K2cQw61WlKNt-IMuGTriTxfbqgTyV0OyMFDirxCs,3545
|
|
8
|
+
fomltools/labs/lab06.py,sha256=gFxwzNSQyLaaEynVxcr0RmWvkEAVw6kJb40JV_IMApc,4331
|
|
9
|
+
fomltools/labs/lab07.py,sha256=ZcaYUlK8TTGzajfqYhPob4sR3EqF9qwTCA3WXdfNQwM,7207
|
|
10
|
+
fomltools/labs/lab08.py,sha256=dTcdotnjSMp1AXbmAnjibpIhq7E7EkeRqefjFu5ewW4,6728
|
|
11
|
+
fomltools/labs/lab09.py,sha256=9xgheGxT40_evwuJa9edTOgSw_wXWX7CibZhsAN4sfA,9387
|
|
12
|
+
fomltools/labs/lab10.py,sha256=LOdMoy-4VTKDDip-NDkhfA6IAr1B-fzcZudVe4sFS1s,2594
|
|
13
|
+
fomltools/labs/lab11.py,sha256=TLTAsqBR8D4Pkz6oiz0WKkwFlpYYcHVccMDkEuXDT9U,2645
|
|
14
|
+
fomltools/labs/lab12.py,sha256=QC_0Tl236xYezcz3k1Wh53vyfD4eFnl-k969F3r3uWg,2284
|
|
15
|
+
fomltools/labs/lab14.py,sha256=2Hk-nZkWCmQXmJZ1Hi_Q9eRV2gSeGGDBsT5vEJE9TFE,12266
|
|
16
|
+
fomltools-0.1.0.dist-info/licenses/LICENSE,sha256=QXn8CiPk6DVzNDgzrC-uC059hspBddfTuQG1NxOjqKQ,1070
|
|
17
|
+
fomltools-0.1.0.dist-info/METADATA,sha256=b_Cm_v74I2drIdFDojxe82ocdSTpIWTQmgfxX8vOTz8,1230
|
|
18
|
+
fomltools-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
19
|
+
fomltools-0.1.0.dist-info/top_level.txt,sha256=eRf1WV4DyxDhuGdI8apC7TCpOrseBpPHJtFcIo20dTQ,10
|
|
20
|
+
fomltools-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Janak Chauhan
|
|
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
|
+
fomltools
|