sml-practicals-toolkit 1.0.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.
sllearn/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ from .polyfeatures import polyfeatures
2
+ from .svc import svc
3
+ from .ridge import ridge
4
+ from .lasso import lasso
5
+ from .gaussianmixture import gaussianmixture
6
+ from .logisticregression import logisticregression
7
+ from .logisticregression import logisticregression
@@ -0,0 +1,63 @@
1
+
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.datasets import make_blobs
5
+ from sklearn.mixture import GaussianMixture
6
+
7
+
8
+ def gaussianmixture():
9
+
10
+ # Step 1: Generate synthetic data
11
+ n_samples = 600
12
+ true_means = np.array([[0, 0], [5, 5], [0, 5]])
13
+
14
+ X, y_true = make_blobs(
15
+ n_samples=n_samples,
16
+ centers=true_means,
17
+ cluster_std=[0.8, 1.0, 0.6],
18
+ random_state=42
19
+ )
20
+
21
+ # Step 2: Apply Gaussian Mixture Model
22
+ gmm = GaussianMixture(
23
+ n_components=3,
24
+ covariance_type='full',
25
+ random_state=42
26
+ )
27
+
28
+ gmm.fit(X)
29
+ y_pred = gmm.predict(X)
30
+
31
+ # Step 3: Compare actual and estimated means
32
+ print("=== True Means ===")
33
+ print(true_means)
34
+
35
+ print("\n=== Estimated Means ===")
36
+ print(gmm.means_)
37
+
38
+ print("\n=== Estimated Covariances ===")
39
+ for i, cov in enumerate(gmm.covariances_):
40
+ print(f"Cluster {i+1} covariance matrix:\n{cov}\n")
41
+
42
+ # Step 4: Plot actual and predicted clusters
43
+ plt.figure(figsize=(10, 5))
44
+
45
+ plt.subplot(1, 2, 1)
46
+ plt.title("Actual Clusters")
47
+ plt.scatter(X[:, 0], X[:, 1], c=y_true, s=30, cmap='viridis')
48
+ plt.scatter(
49
+ true_means[:, 0], true_means[:, 1],
50
+ c='red', marker='x', s=200, label='True Means'
51
+ )
52
+ plt.legend()
53
+
54
+ plt.subplot(1, 2, 2)
55
+ plt.title("GMM Predicted Clusters")
56
+ plt.scatter(X[:, 0], X[:, 1], c=y_pred, s=30, cmap='viridis')
57
+ plt.scatter(
58
+ gmm.means_[:, 0], gmm.means_[:, 1],
59
+ c='red', marker='x', s=200, label='Estimated Means'
60
+ )
61
+ plt.legend()
62
+
63
+ plt.show()
sllearn/lasso.py ADDED
@@ -0,0 +1,90 @@
1
+
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.datasets import load_diabetes
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.linear_model import Ridge, Lasso
7
+ from sklearn.metrics import mean_squared_error, r2_score
8
+ from sklearn.preprocessing import StandardScaler
9
+
10
+
11
+ def lasso():
12
+
13
+ # Load dataset
14
+ diabetes = load_diabetes()
15
+ X = diabetes.data
16
+ y = diabetes.target
17
+
18
+ # Split dataset
19
+ X_train, X_test, y_train, y_test = train_test_split(
20
+ X, y, test_size=0.2, random_state=42
21
+ )
22
+
23
+ # Standardize features
24
+ scaler = StandardScaler()
25
+ X_train = scaler.fit_transform(X_train)
26
+ X_test = scaler.transform(X_test)
27
+
28
+ # Regularization with alpha = 1
29
+ alpha = 1
30
+
31
+ # Ridge Regression
32
+ ridge = Ridge(alpha=alpha)
33
+ ridge.fit(X_train, y_train)
34
+ y_pred_ridge = ridge.predict(X_test)
35
+
36
+ # LASSO Regression
37
+ lasso = Lasso(alpha=alpha)
38
+ lasso.fit(X_train, y_train)
39
+ y_pred_lasso = lasso.predict(X_test)
40
+
41
+ # Evaluate models
42
+ print("===== Ridge Regression =====")
43
+ print("R2 Score:", r2_score(y_test, y_pred_ridge))
44
+ print("MSE:", mean_squared_error(y_test, y_pred_ridge))
45
+ print("Coefficients:", ridge.coef_)
46
+
47
+ print("\n===== LASSO Regression =====")
48
+ print("R2 Score:", r2_score(y_test, y_pred_lasso))
49
+ print("MSE:", mean_squared_error(y_test, y_pred_lasso))
50
+ print("Coefficients:", lasso.coef_)
51
+
52
+ # Compare coefficients
53
+ plt.plot(ridge.coef_, 'bo-', label='Ridge')
54
+ plt.plot(lasso.coef_, 'ro-', label='LASSO')
55
+ plt.axhline(0, color='gray', linestyle='--')
56
+ plt.xlabel("Feature Index")
57
+ plt.ylabel("Coefficient Value")
58
+ plt.title("Ridge vs LASSO")
59
+ plt.legend()
60
+ plt.show()
61
+
62
+ # Repeat with alpha = 10
63
+ alpha = 10
64
+
65
+ ridge = Ridge(alpha=alpha)
66
+ ridge.fit(X_train, y_train)
67
+ y_pred_ridge = ridge.predict(X_test)
68
+
69
+ lasso = Lasso(alpha=alpha)
70
+ lasso.fit(X_train, y_train)
71
+ y_pred_lasso = lasso.predict(X_test)
72
+
73
+ print("\n===== Ridge Regression (alpha=10) =====")
74
+ print("R2 Score:", r2_score(y_test, y_pred_ridge))
75
+ print("MSE:", mean_squared_error(y_test, y_pred_ridge))
76
+ print("Coefficients:", ridge.coef_)
77
+
78
+ print("\n===== LASSO Regression (alpha=10) =====")
79
+ print("R2 Score:", r2_score(y_test, y_pred_lasso))
80
+ print("MSE:", mean_squared_error(y_test, y_pred_lasso))
81
+ print("Coefficients:", lasso.coef_)
82
+
83
+ plt.plot(ridge.coef_, 'bo-', label='Ridge')
84
+ plt.plot(lasso.coef_, 'ro-', label='LASSO')
85
+ plt.axhline(0, color='gray', linestyle='--')
86
+ plt.xlabel("Feature Index")
87
+ plt.ylabel("Coefficient Value")
88
+ plt.title("Ridge vs LASSO (alpha=10)")
89
+ plt.legend()
90
+ plt.show()
@@ -0,0 +1,229 @@
1
+
2
+ import numpy as np
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.preprocessing import StandardScaler
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.metrics import (
10
+ classification_report,
11
+ confusion_matrix,
12
+ roc_auc_score,
13
+ precision_recall_fscore_support
14
+ )
15
+
16
+
17
+ def logisticregression():
18
+
19
+ # Generate imbalanced dataset
20
+ np.random.seed(0)
21
+
22
+ n_total = 1000
23
+ n_class1 = int(n_total * 0.10)
24
+ n_class0 = n_total - n_class1
25
+
26
+ # Generate Class 0
27
+ X0 = np.random.multivariate_normal(
28
+ mean=[0, 0],
29
+ cov=[[1.0, 0.6], [0.6, 1.5]],
30
+ size=n_class0
31
+ )
32
+
33
+ # Generate Class 1
34
+ X1 = np.random.multivariate_normal(
35
+ mean=[2.0, 1.5],
36
+ cov=[[0.8, 0.2], [0.2, 0.6]],
37
+ size=n_class1
38
+ )
39
+
40
+ # Combine data
41
+ X = np.vstack((X0, X1))
42
+ y = np.hstack((np.zeros(n_class0), np.ones(n_class1)))
43
+
44
+ df = pd.DataFrame(X, columns=['x1', 'x2'])
45
+ df['y'] = y.astype(int)
46
+
47
+ # Display class distribution
48
+ print("Class Distribution:")
49
+ print(df['y'].value_counts())
50
+
51
+ # Covariance matrix
52
+ print("\nCovariance Matrix:")
53
+ print(df[['x1', 'x2']].cov())
54
+
55
+ # Fisher LDA
56
+ X_class0 = df[df['y'] == 0][['x1', 'x2']].values
57
+ X_class1 = df[df['y'] == 1][['x1', 'x2']].values
58
+
59
+ mu0 = np.mean(X_class0, axis=0)
60
+ mu1 = np.mean(X_class1, axis=0)
61
+
62
+ # Within-class scatter matrix
63
+ Sw = np.zeros((2, 2))
64
+
65
+ for Xi in [X_class0, X_class1]:
66
+ Si = np.cov(Xi.T, bias=True) * Xi.shape[0]
67
+ Sw += Si
68
+
69
+ # LDA direction
70
+ w = np.linalg.pinv(Sw) @ (mu1 - mu0)
71
+
72
+ # Normalize LDA direction
73
+ w_unit = w / np.linalg.norm(w)
74
+
75
+ # Project data onto LDA direction
76
+ df['lda_proj'] = df[['x1', 'x2']].values @ w_unit
77
+
78
+ # Graph 1: Fisher LDA Projection
79
+ plt.figure(figsize=(8, 6))
80
+
81
+ plt.hist(
82
+ df[df['y'] == 0]['lda_proj'],
83
+ bins=30,
84
+ alpha=0.6,
85
+ label='Class 0'
86
+ )
87
+
88
+ plt.hist(
89
+ df[df['y'] == 1]['lda_proj'],
90
+ bins=30,
91
+ alpha=0.6,
92
+ label='Class 1'
93
+ )
94
+
95
+ plt.title("Fisher LDA Projection (1D)")
96
+ plt.xlabel("Projected value")
97
+ plt.ylabel("Count")
98
+ plt.legend()
99
+ plt.grid()
100
+ plt.show()
101
+
102
+ # Graph 2: Scatter of Features with LDA Direction
103
+ plt.figure(figsize=(8, 6))
104
+
105
+ plt.scatter(
106
+ df[df['y'] == 0]['x1'],
107
+ df[df['y'] == 0]['x2'],
108
+ color='blue',
109
+ label='Class 0'
110
+ )
111
+
112
+ plt.scatter(
113
+ df[df['y'] == 1]['x1'],
114
+ df[df['y'] == 1]['x2'],
115
+ color='red',
116
+ label='Class 1'
117
+ )
118
+
119
+ x_vals = np.linspace(-6, 6, 100)
120
+ y_vals = (w[1] / w[0]) * x_vals
121
+
122
+ plt.plot(
123
+ x_vals,
124
+ y_vals,
125
+ color='black',
126
+ linewidth=2,
127
+ label='LDA direction'
128
+ )
129
+
130
+ plt.title("Scatter of Features with LDA Direction")
131
+ plt.xlabel("x1")
132
+ plt.ylabel("x2")
133
+ plt.legend()
134
+ plt.grid()
135
+ plt.show()
136
+
137
+ # Split dataset
138
+ X_features = df[['x1', 'x2']]
139
+ y_target = df['y']
140
+
141
+ X_train, X_test, y_train, y_test = train_test_split(
142
+ X_features,
143
+ y_target,
144
+ test_size=0.3,
145
+ random_state=1,
146
+ stratify=y_target
147
+ )
148
+
149
+ # Feature scaling
150
+ scaler = StandardScaler()
151
+
152
+ X_train_s = scaler.fit_transform(X_train)
153
+ X_test_s = scaler.transform(X_test)
154
+
155
+ # Balanced Logistic Regression
156
+ clf_bal = LogisticRegression(
157
+ class_weight='balanced',
158
+ solver='liblinear',
159
+ random_state=0
160
+ )
161
+
162
+ clf_bal.fit(X_train_s, y_train)
163
+
164
+ y_pred_bal = clf_bal.predict(X_test_s)
165
+ y_prob_bal = clf_bal.predict_proba(X_test_s)[:, 1]
166
+
167
+ print("\nBalanced Model Performance:")
168
+ print(classification_report(y_test, y_pred_bal))
169
+
170
+ print("Confusion Matrix:")
171
+ print(confusion_matrix(y_test, y_pred_bal))
172
+
173
+ print("ROC AUC:",
174
+ roc_auc_score(y_test, y_prob_bal))
175
+
176
+ # Unbalanced Logistic Regression
177
+ clf_unbal = LogisticRegression(
178
+ class_weight=None,
179
+ solver='liblinear',
180
+ random_state=0
181
+ )
182
+
183
+ clf_unbal.fit(X_train_s, y_train)
184
+
185
+ y_pred_unbal = clf_unbal.predict(X_test_s)
186
+ y_prob_unbal = clf_unbal.predict_proba(X_test_s)[:, 1]
187
+
188
+ print("\nUnbalanced Model Performance:")
189
+ print(classification_report(y_test, y_pred_unbal))
190
+
191
+ print("Confusion Matrix:")
192
+ print(confusion_matrix(y_test, y_pred_unbal))
193
+
194
+ print("ROC AUC:",
195
+ roc_auc_score(y_test, y_prob_unbal))
196
+
197
+ # Coefficients and Odds Ratios
198
+ print("\nBalanced Model Coefficients:")
199
+ print(clf_bal.coef_)
200
+
201
+ print("\nBalanced Model Odds Ratios:")
202
+ print(np.exp(clf_bal.coef_))
203
+
204
+ print("\nUnbalanced Model Coefficients:")
205
+ print(clf_unbal.coef_)
206
+
207
+ print("\nUnbalanced Model Odds Ratios:")
208
+ print(np.exp(clf_unbal.coef_))
209
+
210
+ # Class-wise performance
211
+ precision, recall, f1, support = precision_recall_fscore_support(
212
+ y_test,
213
+ y_pred_bal,
214
+ zero_division=0
215
+ )
216
+
217
+ print("\nBalanced Model Class-wise Performance:")
218
+
219
+ for i in range(len(precision)):
220
+ print(
221
+ f"Class {i}: "
222
+ f"Precision={precision[i]:.3f}, "
223
+ f"Recall={recall[i]:.3f}, "
224
+ f"F1-score={f1[i]:.3f}, "
225
+ f"Support={support[i]}"
226
+ )
227
+
228
+ print("\nLDA Direction:")
229
+ print(w)
@@ -0,0 +1,40 @@
1
+
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.preprocessing import PolynomialFeatures
5
+ from sklearn.linear_model import LinearRegression
6
+ from sklearn.metrics import mean_squared_error
7
+
8
+
9
+ def polyfeatures():
10
+
11
+ # Generate data
12
+ np.random.seed(0)
13
+ X = np.linspace(-4, 4, 25).reshape(-1, 1)
14
+ y_true = 0.5 * X**2 + X + 2
15
+ y = y_true + np.random.normal(0, 1.5, X.shape)
16
+
17
+ # Test polynomial degrees
18
+ degrees = [1, 2, 3, 4, 5]
19
+
20
+ plt.figure(figsize=(15, 10))
21
+
22
+ for i, d in enumerate(degrees, 1):
23
+ poly = PolynomialFeatures(degree=d)
24
+ X_poly = poly.fit_transform(X)
25
+
26
+ model = LinearRegression()
27
+ model.fit(X_poly, y)
28
+ pred = model.predict(X_poly)
29
+
30
+ mse = mean_squared_error(y, pred)
31
+
32
+ plt.subplot(2, 3, i)
33
+ plt.scatter(X, y, color='gray', label='Data')
34
+ plt.plot(X, y_true, color='green', label='True Function')
35
+ plt.plot(X, pred, color='red', label=f'Degree {d}')
36
+ plt.title(f'Degree {d} | MSE: {mse:.2f}')
37
+ plt.legend()
38
+
39
+ plt.tight_layout()
40
+ plt.show()
sllearn/ridge.py ADDED
@@ -0,0 +1,40 @@
1
+
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+
7
+ from sklearn.linear_model import LinearRegression, Ridge
8
+ from sklearn.preprocessing import SplineTransformer
9
+ from sklearn.pipeline import make_pipeline
10
+
11
+
12
+ def ridge():
13
+
14
+ df = pd.read_csv("Housing.csv")
15
+
16
+ x = df[['area']].to_numpy()
17
+ y = df['price'].to_numpy()
18
+
19
+ sqft_range = np.linspace(x.min(), x.max(), 300).reshape(-1, 1)
20
+
21
+ # Linear Regression
22
+ reg = LinearRegression().fit(x, y)
23
+ y_pred_lin = reg.predict(sqft_range)
24
+
25
+ # B-Spline Regression
26
+ model = make_pipeline(
27
+ SplineTransformer(n_knots=3, degree=1),
28
+ Ridge(alpha=1e-3)
29
+ )
30
+
31
+ model.fit(x, y)
32
+ y_pred_spline = model.predict(sqft_range)
33
+
34
+ # Plot
35
+ plt.plot(sqft_range, y_pred_lin, label="Linear")
36
+ plt.plot(sqft_range, y_pred_spline, label="B-Spline")
37
+ sns.scatterplot(x=df['area'], y=df['price'])
38
+
39
+ plt.legend()
40
+ plt.show()
sllearn/svc.py ADDED
@@ -0,0 +1,58 @@
1
+
2
+ import pandas as pd
3
+ import seaborn as sns
4
+ import matplotlib.pyplot as plt
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
7
+ from sklearn.svm import SVC
8
+ from sklearn.metrics import *
9
+
10
+
11
+ def svc():
12
+
13
+ df = sns.load_dataset('titanic')
14
+ cols = ['pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked']
15
+ df = df[cols + ['survived']].copy()
16
+
17
+ df['age'] = df['age'].fillna(df['age'].median())
18
+ df['embarked'] = df['embarked'].fillna(df['embarked'].mode()[0])
19
+
20
+ for c in ['sex', 'embarked']:
21
+ df[c] = LabelEncoder().fit_transform(df[c])
22
+
23
+ X = df[cols]
24
+ y = df['survived']
25
+
26
+ X_train, X_test, y_train, y_test = train_test_split(
27
+ X, y, test_size=0.2, random_state=42)
28
+
29
+ sc = StandardScaler()
30
+ X_train = sc.fit_transform(X_train)
31
+ X_test = sc.transform(X_test)
32
+
33
+ models = {
34
+ 'Linear': SVC(kernel='linear'),
35
+ 'RBF': SVC(kernel='rbf', gamma='scale')
36
+ }
37
+
38
+ predictions = []
39
+
40
+ for name, model in models.items():
41
+ model.fit(X_train, y_train)
42
+ pred = model.predict(X_test)
43
+ predictions.append((name, pred))
44
+
45
+ print(name, "Kernel")
46
+ print("Accuracy:", accuracy_score(y_test, pred))
47
+ print("Precision:", precision_score(y_test, pred))
48
+ print("Recall:", recall_score(y_test, pred))
49
+ print("F1 Score:", f1_score(y_test, pred))
50
+
51
+ fig, ax = plt.subplots(1, 2, figsize=(10, 4))
52
+
53
+ for a, (name, pred) in zip(ax, predictions):
54
+ sns.heatmap(confusion_matrix(y_test, pred),
55
+ annot=True, fmt='d', ax=a)
56
+ a.set_title(name + " Kernel")
57
+
58
+ plt.show()
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: sml-practicals-toolkit
3
+ Version: 1.0.0
4
+ Summary: Statistical Machine Learning Lab Programs
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: numpy
8
+ Requires-Dist: pandas
9
+ Requires-Dist: matplotlib
10
+ Requires-Dist: seaborn
11
+ Requires-Dist: scikit-learn
12
+
13
+
14
+ # sllearn
15
+
16
+ A simple Python library for Statistical Machine Learning Lab programs.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install sllearn
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ```python
27
+ import sllearn
28
+
29
+ sllearn.polyfeatures()
30
+ sllearn.svc()
31
+ sllearn.ridge()
32
+ sllearn.lasso()
33
+ sllearn.gaussianmixture()
34
+ sllearn.logisticregression()
35
+ ```
36
+
37
+ ## Available Programs
38
+
39
+ | Function | Description |
40
+ |---|---|
41
+ | polyfeatures() | Polynomial Features |
42
+ | svc() | Support Vector Classifier |
43
+ | ridge() | Ridge and B-Spline Regression |
44
+ | lasso() | Ridge and Lasso Comparison |
45
+ | gaussianmixture() | Gaussian Mixture Model |
46
+ | logisticregression() | Logistic Regression and Fisher LDA |
47
+
48
+ ## Dependencies
49
+
50
+ - NumPy
51
+ - Pandas
52
+ - Matplotlib
53
+ - Seaborn
54
+ - Scikit-learn
55
+
56
+ ## Author
57
+
58
+ Rayees Akbar
59
+
60
+ ## Purpose
61
+
62
+ Developed for learning and practicing Statistical Machine Learning concepts.
@@ -0,0 +1,11 @@
1
+ sllearn/__init__.py,sha256=jkJxHSc4mNxbZS8fugFStQ7EgMWufV9vM9ZOvrPPFzo,262
2
+ sllearn/gaussianmixture.py,sha256=NrQu1PBLvH8qqLlK7yDm1q5em6wtn3JEJ0cOY0MGOtI,1646
3
+ sllearn/lasso.py,sha256=ONbsL1cOLB-nPKeJvOQlAEv2X3fPAtBZErwtWChxTWM,2769
4
+ sllearn/logisticregression.py,sha256=DB7CcIZCpnrYjiVaLUukcKRqFymHgwIxYmvlLq2du9Q,5532
5
+ sllearn/polyfeatures.py,sha256=Y2uQPEq8iZ5gNikfo3VGOXX_QS32uevPB8Je99tqBsg,1119
6
+ sllearn/ridge.py,sha256=TlI7AkSqtoe1uw8x-uj7l_mVZTC5fv20ctU0hluVSWU,982
7
+ sllearn/svc.py,sha256=pH-6fyULjEgpB0I6tI_JwNP4JKUChr-XHtzwxsf4UGw,1719
8
+ sml_practicals_toolkit-1.0.0.dist-info/METADATA,sha256=hZg-yPi3yYyi7PJ997wVf4KVoAKfTK0hOgnnA3879M0,1183
9
+ sml_practicals_toolkit-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ sml_practicals_toolkit-1.0.0.dist-info/top_level.txt,sha256=-IoSI5hiNUP2pIJRbsLQxPHNVpGSkFZTNaBvkUvrbJQ,8
11
+ sml_practicals_toolkit-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ sllearn