shashank-utils 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.
- shashank_utils/__init__.py +30 -0
- shashank_utils/calculator.py +27 -0
- shashank_utils/conversions.py +21 -0
- shashank_utils/ml_program_01.py +32 -0
- shashank_utils/ml_program_02.py +31 -0
- shashank_utils/ml_program_03.py +40 -0
- shashank_utils/ml_program_04.py +162 -0
- shashank_utils/ml_program_05.py +36 -0
- shashank_utils/ml_program_06.py +65 -0
- shashank_utils/ml_program_07.py +64 -0
- shashank_utils/ml_program_08.py +35 -0
- shashank_utils/ml_program_09.py +45 -0
- shashank_utils/ml_program_10.py +43 -0
- shashank_utils/ml_program_11.py +69 -0
- shashank_utils/ml_program_12.py +67 -0
- shashank_utils/number_utils.py +45 -0
- shashank_utils/patterns.py +32 -0
- shashank_utils-0.1.0.dist-info/METADATA +129 -0
- shashank_utils-0.1.0.dist-info/RECORD +22 -0
- shashank_utils-0.1.0.dist-info/WHEEL +5 -0
- shashank_utils-0.1.0.dist-info/licenses/LICENSE +21 -0
- shashank_utils-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Reusable beginner-friendly utilities."""
|
|
2
|
+
|
|
3
|
+
from .calculator import add, divide, multiply, subtract
|
|
4
|
+
from .conversions import (
|
|
5
|
+
celsius_to_fahrenheit,
|
|
6
|
+
fahrenheit_to_celsius,
|
|
7
|
+
kilometres_to_miles,
|
|
8
|
+
miles_to_kilometres,
|
|
9
|
+
)
|
|
10
|
+
from .number_utils import factorial, is_palindrome, is_prime
|
|
11
|
+
from .patterns import pyramid, square, triangle
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"add",
|
|
17
|
+
"subtract",
|
|
18
|
+
"multiply",
|
|
19
|
+
"divide",
|
|
20
|
+
"triangle",
|
|
21
|
+
"pyramid",
|
|
22
|
+
"square",
|
|
23
|
+
"celsius_to_fahrenheit",
|
|
24
|
+
"fahrenheit_to_celsius",
|
|
25
|
+
"kilometres_to_miles",
|
|
26
|
+
"miles_to_kilometres",
|
|
27
|
+
"is_prime",
|
|
28
|
+
"factorial",
|
|
29
|
+
"is_palindrome",
|
|
30
|
+
]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Basic arithmetic operations."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def add(a: float, b: float) -> float:
|
|
5
|
+
"""Return the sum of *a* and *b*."""
|
|
6
|
+
return a + b
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def subtract(a: float, b: float) -> float:
|
|
10
|
+
"""Return *b* subtracted from *a*."""
|
|
11
|
+
return a - b
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def multiply(a: float, b: float) -> float:
|
|
15
|
+
"""Return the product of *a* and *b*."""
|
|
16
|
+
return a * b
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def divide(a: float, b: float) -> float:
|
|
20
|
+
"""Return *a* divided by *b*.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
ZeroDivisionError: If *b* is zero.
|
|
24
|
+
"""
|
|
25
|
+
if b == 0:
|
|
26
|
+
raise ZeroDivisionError("Cannot divide by zero.")
|
|
27
|
+
return a / b
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Common temperature and distance conversions."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def celsius_to_fahrenheit(celsius: float) -> float:
|
|
5
|
+
"""Convert a temperature in degrees Celsius to Fahrenheit."""
|
|
6
|
+
return (celsius * 9 / 5) + 32
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def fahrenheit_to_celsius(fahrenheit: float) -> float:
|
|
10
|
+
"""Convert a temperature in degrees Fahrenheit to Celsius."""
|
|
11
|
+
return (fahrenheit - 32) * 5 / 9
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def kilometres_to_miles(kilometres: float) -> float:
|
|
15
|
+
"""Convert kilometres to miles."""
|
|
16
|
+
return kilometres * 0.621371
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def miles_to_kilometres(miles: float) -> float:
|
|
20
|
+
"""Convert miles to kilometres."""
|
|
21
|
+
return miles / 0.621371
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Program 01: Exploratory Data Analysis - California Housing
|
|
2
|
+
"""Explore summary statistics and distributions in California Housing."""
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from sklearn.datasets import fetch_california_housing
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def load_housing_frame() -> pd.DataFrame:
|
|
10
|
+
"""Fetch California Housing as a pandas DataFrame."""
|
|
11
|
+
return fetch_california_housing(as_frame=True).frame.copy()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main() -> None:
|
|
15
|
+
housing = load_housing_frame()
|
|
16
|
+
print("First five rows:")
|
|
17
|
+
print(housing.head())
|
|
18
|
+
print("\nSummary statistics:")
|
|
19
|
+
print(housing.describe().round(2))
|
|
20
|
+
print("\nMissing values:")
|
|
21
|
+
print(housing.isna().sum())
|
|
22
|
+
|
|
23
|
+
housing["MedHouseVal"].hist(bins=30, edgecolor="black")
|
|
24
|
+
plt.title("California Housing: median house value")
|
|
25
|
+
plt.xlabel("Median value (hundreds of thousands of dollars)")
|
|
26
|
+
plt.ylabel("Number of districts")
|
|
27
|
+
plt.tight_layout()
|
|
28
|
+
plt.show()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
main()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Program 02: Correlation Matrix - Iris Dataset
|
|
2
|
+
"""Calculate and display correlations between Iris measurements."""
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from sklearn.datasets import load_iris
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def iris_correlation_matrix() -> pd.DataFrame:
|
|
10
|
+
"""Return the feature correlation matrix for the Iris dataset."""
|
|
11
|
+
iris = load_iris()
|
|
12
|
+
frame = pd.DataFrame(iris.data, columns=iris.feature_names)
|
|
13
|
+
return frame.corr()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main() -> None:
|
|
17
|
+
correlation = iris_correlation_matrix()
|
|
18
|
+
print(correlation.round(3))
|
|
19
|
+
|
|
20
|
+
figure, axis = plt.subplots()
|
|
21
|
+
image = axis.imshow(correlation, cmap="coolwarm", vmin=-1, vmax=1)
|
|
22
|
+
axis.set_xticks(range(len(correlation.columns)), correlation.columns, rotation=45, ha="right")
|
|
23
|
+
axis.set_yticks(range(len(correlation.index)), correlation.index)
|
|
24
|
+
axis.set_title("Iris feature correlation matrix")
|
|
25
|
+
figure.colorbar(image, ax=axis, label="Correlation")
|
|
26
|
+
figure.tight_layout()
|
|
27
|
+
plt.show()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
main()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Program 03: Principal Component Analysis - Iris Dataset
|
|
2
|
+
"""Scale Iris measurements and project them onto two principal components."""
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
from sklearn.datasets import load_iris
|
|
6
|
+
from sklearn.decomposition import PCA
|
|
7
|
+
from sklearn.preprocessing import StandardScaler
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def project_iris():
|
|
11
|
+
"""Return the two-dimensional PCA projection and source dataset."""
|
|
12
|
+
iris = load_iris()
|
|
13
|
+
scaled_features = StandardScaler().fit_transform(iris.data)
|
|
14
|
+
pca = PCA(n_components=2)
|
|
15
|
+
projection = pca.fit_transform(scaled_features)
|
|
16
|
+
return projection, iris, pca.explained_variance_ratio_
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main() -> None:
|
|
20
|
+
projection, iris, variance_ratio = project_iris()
|
|
21
|
+
print("Explained variance ratio:", variance_ratio.round(3))
|
|
22
|
+
|
|
23
|
+
for label, name in enumerate(iris.target_names):
|
|
24
|
+
selected = iris.target == label
|
|
25
|
+
plt.scatter(
|
|
26
|
+
projection[selected, 0],
|
|
27
|
+
projection[selected, 1],
|
|
28
|
+
label=name,
|
|
29
|
+
alpha=0.75,
|
|
30
|
+
)
|
|
31
|
+
plt.xlabel("Principal component 1")
|
|
32
|
+
plt.ylabel("Principal component 2")
|
|
33
|
+
plt.title("PCA projection of the Iris dataset")
|
|
34
|
+
plt.legend()
|
|
35
|
+
plt.tight_layout()
|
|
36
|
+
plt.show()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
main()
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Program 04: Candidate Elimination Algorithm
|
|
2
|
+
"""Find specific and general hypothesis boundaries from labeled examples."""
|
|
3
|
+
|
|
4
|
+
from typing import Sequence
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
WILDCARD = "?"
|
|
8
|
+
BOTTOM = "<bottom>"
|
|
9
|
+
Hypothesis = tuple[str, ...]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def covers(hypothesis: Hypothesis, example: Sequence[str]) -> bool:
|
|
13
|
+
"""Return whether a hypothesis accepts an example."""
|
|
14
|
+
return all(
|
|
15
|
+
value == WILDCARD or (value != BOTTOM and value == example[index])
|
|
16
|
+
for index, value in enumerate(hypothesis)
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def more_general_or_equal(general: Hypothesis, specific: Hypothesis) -> bool:
|
|
21
|
+
"""Return whether *general* is at least as general as *specific*."""
|
|
22
|
+
return all(
|
|
23
|
+
general_value == WILDCARD
|
|
24
|
+
or specific_value == BOTTOM
|
|
25
|
+
or general_value == specific_value
|
|
26
|
+
for general_value, specific_value in zip(general, specific)
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _most_specific(hypotheses: set[Hypothesis]) -> set[Hypothesis]:
|
|
31
|
+
return {
|
|
32
|
+
hypothesis
|
|
33
|
+
for hypothesis in hypotheses
|
|
34
|
+
if not any(
|
|
35
|
+
hypothesis != other and more_general_or_equal(hypothesis, other)
|
|
36
|
+
for other in hypotheses
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _most_general(hypotheses: set[Hypothesis]) -> set[Hypothesis]:
|
|
42
|
+
return {
|
|
43
|
+
hypothesis
|
|
44
|
+
for hypothesis in hypotheses
|
|
45
|
+
if not any(
|
|
46
|
+
hypothesis != other and more_general_or_equal(other, hypothesis)
|
|
47
|
+
for other in hypotheses
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def candidate_elimination(
|
|
53
|
+
examples: Sequence[Sequence[str]], labels: Sequence[bool]
|
|
54
|
+
) -> tuple[list[Hypothesis], list[Hypothesis]]:
|
|
55
|
+
"""Return the specific and general boundaries for boolean labeled examples.
|
|
56
|
+
|
|
57
|
+
Each feature domain is inferred from all supplied examples. Labels must be
|
|
58
|
+
``True`` for positive examples and ``False`` for negative examples.
|
|
59
|
+
"""
|
|
60
|
+
if not examples:
|
|
61
|
+
raise ValueError("At least one training example is required.")
|
|
62
|
+
if len(examples) != len(labels):
|
|
63
|
+
raise ValueError("Each example must have exactly one label.")
|
|
64
|
+
if any(not isinstance(label, bool) for label in labels):
|
|
65
|
+
raise TypeError("Labels must be booleans.")
|
|
66
|
+
|
|
67
|
+
feature_count = len(examples[0])
|
|
68
|
+
if feature_count == 0 or any(len(example) != feature_count for example in examples):
|
|
69
|
+
raise ValueError("Examples must have the same non-zero number of features.")
|
|
70
|
+
|
|
71
|
+
domains = [
|
|
72
|
+
{example[index] for example in examples}
|
|
73
|
+
for index in range(feature_count)
|
|
74
|
+
]
|
|
75
|
+
specific = {(BOTTOM,) * feature_count}
|
|
76
|
+
general = {(WILDCARD,) * feature_count}
|
|
77
|
+
|
|
78
|
+
for example_values, is_positive in zip(examples, labels):
|
|
79
|
+
example = tuple(example_values)
|
|
80
|
+
if is_positive:
|
|
81
|
+
general = {hypothesis for hypothesis in general if covers(hypothesis, example)}
|
|
82
|
+
updated_specific = set()
|
|
83
|
+
for hypothesis in specific:
|
|
84
|
+
if covers(hypothesis, example):
|
|
85
|
+
updated_specific.add(hypothesis)
|
|
86
|
+
continue
|
|
87
|
+
generalized = tuple(
|
|
88
|
+
example[index]
|
|
89
|
+
if value == BOTTOM
|
|
90
|
+
else WILDCARD
|
|
91
|
+
if value != example[index]
|
|
92
|
+
else value
|
|
93
|
+
for index, value in enumerate(hypothesis)
|
|
94
|
+
)
|
|
95
|
+
if any(
|
|
96
|
+
more_general_or_equal(boundary, generalized)
|
|
97
|
+
for boundary in general
|
|
98
|
+
):
|
|
99
|
+
updated_specific.add(generalized)
|
|
100
|
+
specific = _most_specific(updated_specific)
|
|
101
|
+
else:
|
|
102
|
+
specific = {
|
|
103
|
+
hypothesis
|
|
104
|
+
for hypothesis in specific
|
|
105
|
+
if not covers(hypothesis, example)
|
|
106
|
+
}
|
|
107
|
+
updated_general = set()
|
|
108
|
+
for hypothesis in general:
|
|
109
|
+
if not covers(hypothesis, example):
|
|
110
|
+
updated_general.add(hypothesis)
|
|
111
|
+
continue
|
|
112
|
+
for index, value in enumerate(hypothesis):
|
|
113
|
+
if value != WILDCARD:
|
|
114
|
+
continue
|
|
115
|
+
for domain_value in domains[index]:
|
|
116
|
+
if domain_value == example[index]:
|
|
117
|
+
continue
|
|
118
|
+
specialized = list(hypothesis)
|
|
119
|
+
specialized[index] = domain_value
|
|
120
|
+
candidate = tuple(specialized)
|
|
121
|
+
if any(
|
|
122
|
+
more_general_or_equal(candidate, boundary)
|
|
123
|
+
for boundary in specific
|
|
124
|
+
):
|
|
125
|
+
updated_general.add(candidate)
|
|
126
|
+
general = _most_general(updated_general)
|
|
127
|
+
|
|
128
|
+
specific = {
|
|
129
|
+
hypothesis
|
|
130
|
+
for hypothesis in specific
|
|
131
|
+
if any(
|
|
132
|
+
more_general_or_equal(boundary, hypothesis)
|
|
133
|
+
for boundary in general
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
general = {
|
|
137
|
+
hypothesis
|
|
138
|
+
for hypothesis in general
|
|
139
|
+
if any(
|
|
140
|
+
more_general_or_equal(hypothesis, boundary)
|
|
141
|
+
for boundary in specific
|
|
142
|
+
)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return sorted(specific), sorted(general)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def main() -> None:
|
|
149
|
+
examples = [
|
|
150
|
+
("Sunny", "Warm", "Normal", "Strong", "Warm", "Same"),
|
|
151
|
+
("Sunny", "Warm", "High", "Strong", "Warm", "Same"),
|
|
152
|
+
("Rainy", "Cold", "High", "Strong", "Warm", "Change"),
|
|
153
|
+
("Sunny", "Warm", "High", "Strong", "Cool", "Change"),
|
|
154
|
+
]
|
|
155
|
+
labels = [True, True, False, True]
|
|
156
|
+
specific, general = candidate_elimination(examples, labels)
|
|
157
|
+
print("Specific boundary (S):", specific)
|
|
158
|
+
print("General boundary (G):", general)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
if __name__ == "__main__":
|
|
162
|
+
main()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Program 05: Linear Regression - California Housing Dataset
|
|
2
|
+
"""Fit and evaluate a linear regression model for California house values."""
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from sklearn.datasets import fetch_california_housing
|
|
6
|
+
from sklearn.linear_model import LinearRegression
|
|
7
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
8
|
+
from sklearn.model_selection import train_test_split
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def fit_housing_regression() -> dict[str, float]:
|
|
12
|
+
"""Train a linear model and return test-set RMSE and R-squared."""
|
|
13
|
+
housing = fetch_california_housing()
|
|
14
|
+
features_train, features_test, target_train, target_test = train_test_split(
|
|
15
|
+
housing.data,
|
|
16
|
+
housing.target,
|
|
17
|
+
test_size=0.2,
|
|
18
|
+
random_state=42,
|
|
19
|
+
)
|
|
20
|
+
model = LinearRegression()
|
|
21
|
+
model.fit(features_train, target_train)
|
|
22
|
+
predictions = model.predict(features_test)
|
|
23
|
+
return {
|
|
24
|
+
"rmse": float(np.sqrt(mean_squared_error(target_test, predictions))),
|
|
25
|
+
"r2": float(r2_score(target_test, predictions)),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main() -> None:
|
|
30
|
+
metrics = fit_housing_regression()
|
|
31
|
+
print(f"Test RMSE: {metrics['rmse']:.3f}")
|
|
32
|
+
print(f"Test R-squared: {metrics['r2']:.3f}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
main()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Program 06: Polynomial Regression
|
|
2
|
+
"""Fit a polynomial regression curve to reproducible synthetic data."""
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import numpy as np
|
|
6
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
7
|
+
from sklearn.model_selection import train_test_split
|
|
8
|
+
from sklearn.pipeline import make_pipeline
|
|
9
|
+
from sklearn.preprocessing import PolynomialFeatures
|
|
10
|
+
from sklearn.linear_model import LinearRegression
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def make_polynomial_data(samples: int = 120, seed: int = 42):
|
|
14
|
+
"""Create noisy observations from a quadratic relationship."""
|
|
15
|
+
if samples < 4:
|
|
16
|
+
raise ValueError("At least four samples are required.")
|
|
17
|
+
rng = np.random.default_rng(seed)
|
|
18
|
+
features = np.linspace(-3, 3, samples).reshape(-1, 1)
|
|
19
|
+
target = 0.5 * features[:, 0] ** 2 + 2 * features[:, 0] + 1
|
|
20
|
+
target += rng.normal(0, 1.5, size=samples)
|
|
21
|
+
return features, target
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fit_polynomial_regression(degree: int = 2):
|
|
25
|
+
"""Fit a polynomial model and return it with test metrics and data."""
|
|
26
|
+
features, target = make_polynomial_data()
|
|
27
|
+
x_train, x_test, y_train, y_test = train_test_split(
|
|
28
|
+
features, target, test_size=0.25, random_state=42
|
|
29
|
+
)
|
|
30
|
+
model = make_pipeline(
|
|
31
|
+
PolynomialFeatures(degree=degree, include_bias=False),
|
|
32
|
+
LinearRegression(),
|
|
33
|
+
)
|
|
34
|
+
model.fit(x_train, y_train)
|
|
35
|
+
predictions = model.predict(x_test)
|
|
36
|
+
metrics = {
|
|
37
|
+
"rmse": float(np.sqrt(mean_squared_error(y_test, predictions))),
|
|
38
|
+
"r2": float(r2_score(y_test, predictions)),
|
|
39
|
+
}
|
|
40
|
+
return model, metrics, features, target
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def main() -> None:
|
|
44
|
+
model, metrics, features, target = fit_polynomial_regression()
|
|
45
|
+
print(f"Test RMSE: {metrics['rmse']:.3f}")
|
|
46
|
+
print(f"Test R-squared: {metrics['r2']:.3f}")
|
|
47
|
+
|
|
48
|
+
order = np.argsort(features[:, 0])
|
|
49
|
+
plt.scatter(features[:, 0], target, label="observations", alpha=0.6)
|
|
50
|
+
plt.plot(
|
|
51
|
+
features[order, 0],
|
|
52
|
+
model.predict(features[order]),
|
|
53
|
+
color="red",
|
|
54
|
+
label="degree-two fit",
|
|
55
|
+
)
|
|
56
|
+
plt.xlabel("Input")
|
|
57
|
+
plt.ylabel("Target")
|
|
58
|
+
plt.title("Polynomial regression")
|
|
59
|
+
plt.legend()
|
|
60
|
+
plt.tight_layout()
|
|
61
|
+
plt.show()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
main()
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Program 07: Logistic Regression - Titanic Dataset
|
|
2
|
+
"""Predict Titanic survival using a logistic-regression pipeline."""
|
|
3
|
+
|
|
4
|
+
import seaborn as sns
|
|
5
|
+
from sklearn.compose import ColumnTransformer
|
|
6
|
+
from sklearn.impute import SimpleImputer
|
|
7
|
+
from sklearn.linear_model import LogisticRegression
|
|
8
|
+
from sklearn.metrics import accuracy_score
|
|
9
|
+
from sklearn.model_selection import train_test_split
|
|
10
|
+
from sklearn.pipeline import Pipeline
|
|
11
|
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
NUMERIC_FEATURES = ["pclass", "age", "sibsp", "parch", "fare"]
|
|
15
|
+
CATEGORICAL_FEATURES = ["sex", "embarked"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def fit_titanic_classifier() -> float:
|
|
19
|
+
"""Train on Seaborn's Titanic dataset and return test accuracy."""
|
|
20
|
+
titanic = sns.load_dataset("titanic")
|
|
21
|
+
features = titanic[NUMERIC_FEATURES + CATEGORICAL_FEATURES]
|
|
22
|
+
target = titanic["survived"]
|
|
23
|
+
x_train, x_test, y_train, y_test = train_test_split(
|
|
24
|
+
features,
|
|
25
|
+
target,
|
|
26
|
+
test_size=0.2,
|
|
27
|
+
random_state=42,
|
|
28
|
+
stratify=target,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
numeric_pipeline = Pipeline(
|
|
32
|
+
[
|
|
33
|
+
("imputer", SimpleImputer(strategy="median")),
|
|
34
|
+
("scaler", StandardScaler()),
|
|
35
|
+
]
|
|
36
|
+
)
|
|
37
|
+
categorical_pipeline = Pipeline(
|
|
38
|
+
[
|
|
39
|
+
("imputer", SimpleImputer(strategy="most_frequent")),
|
|
40
|
+
("encoder", OneHotEncoder(handle_unknown="ignore")),
|
|
41
|
+
]
|
|
42
|
+
)
|
|
43
|
+
preprocessing = ColumnTransformer(
|
|
44
|
+
[
|
|
45
|
+
("numeric", numeric_pipeline, NUMERIC_FEATURES),
|
|
46
|
+
("categorical", categorical_pipeline, CATEGORICAL_FEATURES),
|
|
47
|
+
]
|
|
48
|
+
)
|
|
49
|
+
model = Pipeline(
|
|
50
|
+
[
|
|
51
|
+
("preprocessing", preprocessing),
|
|
52
|
+
("classifier", LogisticRegression(max_iter=1000)),
|
|
53
|
+
]
|
|
54
|
+
)
|
|
55
|
+
model.fit(x_train, y_train)
|
|
56
|
+
return float(accuracy_score(y_test, model.predict(x_test)))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def main() -> None:
|
|
60
|
+
print(f"Test accuracy: {fit_titanic_classifier():.3f}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
if __name__ == "__main__":
|
|
64
|
+
main()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Program 08: K-Nearest Neighbors - Iris Dataset
|
|
2
|
+
"""Classify Iris flowers with scaled K-nearest neighbors."""
|
|
3
|
+
|
|
4
|
+
from sklearn.datasets import load_iris
|
|
5
|
+
from sklearn.metrics import accuracy_score
|
|
6
|
+
from sklearn.model_selection import train_test_split
|
|
7
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
8
|
+
from sklearn.pipeline import make_pipeline
|
|
9
|
+
from sklearn.preprocessing import StandardScaler
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def fit_iris_knn(neighbors: int = 5) -> float:
|
|
13
|
+
"""Train a scaled KNN classifier and return its test accuracy."""
|
|
14
|
+
iris = load_iris()
|
|
15
|
+
x_train, x_test, y_train, y_test = train_test_split(
|
|
16
|
+
iris.data,
|
|
17
|
+
iris.target,
|
|
18
|
+
test_size=0.25,
|
|
19
|
+
random_state=42,
|
|
20
|
+
stratify=iris.target,
|
|
21
|
+
)
|
|
22
|
+
model = make_pipeline(
|
|
23
|
+
StandardScaler(),
|
|
24
|
+
KNeighborsClassifier(n_neighbors=neighbors),
|
|
25
|
+
)
|
|
26
|
+
model.fit(x_train, y_train)
|
|
27
|
+
return float(accuracy_score(y_test, model.predict(x_test)))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main() -> None:
|
|
31
|
+
print(f"Test accuracy: {fit_iris_knn():.3f}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
if __name__ == "__main__":
|
|
35
|
+
main()
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Program 09: Decision Tree - Breast Cancer Dataset
|
|
2
|
+
"""Train and visualize a decision tree for breast-cancer classification."""
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
from sklearn.datasets import load_breast_cancer
|
|
6
|
+
from sklearn.metrics import accuracy_score
|
|
7
|
+
from sklearn.model_selection import train_test_split
|
|
8
|
+
from sklearn.tree import DecisionTreeClassifier, plot_tree
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def fit_breast_cancer_tree():
|
|
12
|
+
"""Fit a shallow decision tree and return it, data, and test accuracy."""
|
|
13
|
+
dataset = load_breast_cancer()
|
|
14
|
+
x_train, x_test, y_train, y_test = train_test_split(
|
|
15
|
+
dataset.data,
|
|
16
|
+
dataset.target,
|
|
17
|
+
test_size=0.25,
|
|
18
|
+
random_state=42,
|
|
19
|
+
stratify=dataset.target,
|
|
20
|
+
)
|
|
21
|
+
model = DecisionTreeClassifier(max_depth=4, random_state=42)
|
|
22
|
+
model.fit(x_train, y_train)
|
|
23
|
+
accuracy = float(accuracy_score(y_test, model.predict(x_test)))
|
|
24
|
+
return model, dataset, accuracy
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main() -> None:
|
|
28
|
+
model, dataset, accuracy = fit_breast_cancer_tree()
|
|
29
|
+
print(f"Test accuracy: {accuracy:.3f}")
|
|
30
|
+
plt.figure(figsize=(18, 9))
|
|
31
|
+
plot_tree(
|
|
32
|
+
model,
|
|
33
|
+
feature_names=dataset.feature_names,
|
|
34
|
+
class_names=list(dataset.target_names),
|
|
35
|
+
filled=True,
|
|
36
|
+
rounded=True,
|
|
37
|
+
max_depth=3,
|
|
38
|
+
)
|
|
39
|
+
plt.title("Decision tree (first three levels)")
|
|
40
|
+
plt.tight_layout()
|
|
41
|
+
plt.show()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
if __name__ == "__main__":
|
|
45
|
+
main()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Program 10: Expectation-Maximization Clustering
|
|
2
|
+
"""Cluster generated points with a Gaussian mixture model (EM algorithm)."""
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
from sklearn.datasets import make_blobs
|
|
6
|
+
from sklearn.mixture import GaussianMixture
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def run_em_clustering(samples: int = 500, seed: int = 42):
|
|
10
|
+
"""Return generated points, EM cluster labels, and the fitted mixture."""
|
|
11
|
+
features, _ = make_blobs(
|
|
12
|
+
n_samples=samples,
|
|
13
|
+
centers=3,
|
|
14
|
+
cluster_std=1.4,
|
|
15
|
+
random_state=seed,
|
|
16
|
+
)
|
|
17
|
+
model = GaussianMixture(n_components=3, random_state=seed)
|
|
18
|
+
labels = model.fit_predict(features)
|
|
19
|
+
return features, labels, model
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> None:
|
|
23
|
+
features, labels, model = run_em_clustering()
|
|
24
|
+
print("Estimated component means:")
|
|
25
|
+
print(model.means_.round(2))
|
|
26
|
+
print(f"Bayesian information criterion: {model.bic(features):.2f}")
|
|
27
|
+
plt.scatter(features[:, 0], features[:, 1], c=labels, cmap="viridis", s=18)
|
|
28
|
+
plt.scatter(
|
|
29
|
+
model.means_[:, 0],
|
|
30
|
+
model.means_[:, 1],
|
|
31
|
+
marker="x",
|
|
32
|
+
color="red",
|
|
33
|
+
s=100,
|
|
34
|
+
label="component means",
|
|
35
|
+
)
|
|
36
|
+
plt.title("Gaussian mixture clustering")
|
|
37
|
+
plt.legend()
|
|
38
|
+
plt.tight_layout()
|
|
39
|
+
plt.show()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
main()
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Program 11: Ensemble Learning - Voting, Bagging, Boosting and Random Forest
|
|
2
|
+
"""Compare common ensemble classifiers on the Breast Cancer dataset."""
|
|
3
|
+
|
|
4
|
+
from sklearn.datasets import load_breast_cancer
|
|
5
|
+
from sklearn.ensemble import (
|
|
6
|
+
AdaBoostClassifier,
|
|
7
|
+
BaggingClassifier,
|
|
8
|
+
RandomForestClassifier,
|
|
9
|
+
VotingClassifier,
|
|
10
|
+
)
|
|
11
|
+
from sklearn.linear_model import LogisticRegression
|
|
12
|
+
from sklearn.metrics import accuracy_score
|
|
13
|
+
from sklearn.model_selection import train_test_split
|
|
14
|
+
from sklearn.pipeline import make_pipeline
|
|
15
|
+
from sklearn.preprocessing import StandardScaler
|
|
16
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def compare_ensemble_classifiers() -> dict[str, float]:
|
|
20
|
+
"""Fit voting, bagging, boosting, and forest models and score each."""
|
|
21
|
+
dataset = load_breast_cancer()
|
|
22
|
+
x_train, x_test, y_train, y_test = train_test_split(
|
|
23
|
+
dataset.data,
|
|
24
|
+
dataset.target,
|
|
25
|
+
test_size=0.25,
|
|
26
|
+
random_state=42,
|
|
27
|
+
stratify=dataset.target,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
models = {
|
|
31
|
+
"voting": VotingClassifier(
|
|
32
|
+
estimators=[
|
|
33
|
+
(
|
|
34
|
+
"logistic",
|
|
35
|
+
make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)),
|
|
36
|
+
),
|
|
37
|
+
("tree", DecisionTreeClassifier(max_depth=4, random_state=42)),
|
|
38
|
+
(
|
|
39
|
+
"forest",
|
|
40
|
+
RandomForestClassifier(n_estimators=100, random_state=42),
|
|
41
|
+
),
|
|
42
|
+
],
|
|
43
|
+
voting="soft",
|
|
44
|
+
),
|
|
45
|
+
"bagging": BaggingClassifier(
|
|
46
|
+
estimator=DecisionTreeClassifier(max_depth=4),
|
|
47
|
+
n_estimators=50,
|
|
48
|
+
random_state=42,
|
|
49
|
+
),
|
|
50
|
+
"boosting": AdaBoostClassifier(n_estimators=100, random_state=42),
|
|
51
|
+
"random_forest": RandomForestClassifier(
|
|
52
|
+
n_estimators=100,
|
|
53
|
+
random_state=42,
|
|
54
|
+
),
|
|
55
|
+
}
|
|
56
|
+
scores = {}
|
|
57
|
+
for name, model in models.items():
|
|
58
|
+
model.fit(x_train, y_train)
|
|
59
|
+
scores[name] = float(accuracy_score(y_test, model.predict(x_test)))
|
|
60
|
+
return scores
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def main() -> None:
|
|
64
|
+
for name, score in compare_ensemble_classifiers().items():
|
|
65
|
+
print(f"{name.replace('_', ' ').title()} accuracy: {score:.3f}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
main()
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Program 12: Reinforcement Learning - Policy Search
|
|
2
|
+
"""Search for a successful stochastic policy in a small line-world."""
|
|
3
|
+
|
|
4
|
+
from typing import Sequence
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def evaluate_policy(
|
|
10
|
+
policy: Sequence[float],
|
|
11
|
+
episodes: int = 200,
|
|
12
|
+
max_steps: int = 20,
|
|
13
|
+
seed: int = 42,
|
|
14
|
+
) -> float:
|
|
15
|
+
"""Return the average goal reward for a right-move probability per state."""
|
|
16
|
+
probabilities = np.asarray(policy, dtype=float)
|
|
17
|
+
if probabilities.ndim != 1 or probabilities.size == 0:
|
|
18
|
+
raise ValueError("Policy must contain one probability per non-terminal state.")
|
|
19
|
+
if np.any((probabilities < 0) | (probabilities > 1)):
|
|
20
|
+
raise ValueError("Policy probabilities must be between zero and one.")
|
|
21
|
+
if episodes < 1 or max_steps < 1:
|
|
22
|
+
raise ValueError("Episodes and maximum steps must be positive.")
|
|
23
|
+
|
|
24
|
+
rng = np.random.default_rng(seed)
|
|
25
|
+
goal = probabilities.size
|
|
26
|
+
total_reward = 0
|
|
27
|
+
for _ in range(episodes):
|
|
28
|
+
position = 0
|
|
29
|
+
for _ in range(max_steps):
|
|
30
|
+
direction = 1 if rng.random() < probabilities[position] else -1
|
|
31
|
+
position = min(goal, max(0, position + direction))
|
|
32
|
+
if position == goal:
|
|
33
|
+
total_reward += 1
|
|
34
|
+
break
|
|
35
|
+
return total_reward / episodes
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def search_policy(
|
|
39
|
+
states: int = 5,
|
|
40
|
+
trials: int = 100,
|
|
41
|
+
episodes: int = 200,
|
|
42
|
+
seed: int = 42,
|
|
43
|
+
) -> tuple[np.ndarray, float]:
|
|
44
|
+
"""Use random search to find a policy with high average goal reward."""
|
|
45
|
+
if states < 1 or trials < 1:
|
|
46
|
+
raise ValueError("States and trials must be positive.")
|
|
47
|
+
rng = np.random.default_rng(seed)
|
|
48
|
+
best_policy = rng.uniform(0, 1, size=states)
|
|
49
|
+
best_reward = evaluate_policy(best_policy, episodes=episodes, seed=seed + 1)
|
|
50
|
+
|
|
51
|
+
for _ in range(trials - 1):
|
|
52
|
+
candidate = rng.uniform(0, 1, size=states)
|
|
53
|
+
reward = evaluate_policy(candidate, episodes=episodes, seed=seed + 1)
|
|
54
|
+
if reward > best_reward:
|
|
55
|
+
best_policy = candidate
|
|
56
|
+
best_reward = reward
|
|
57
|
+
return best_policy, best_reward
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def main() -> None:
|
|
61
|
+
policy, reward = search_policy()
|
|
62
|
+
print("Right-move probabilities by state:", policy.round(2))
|
|
63
|
+
print(f"Average reward: {reward:.3f}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
if __name__ == "__main__":
|
|
67
|
+
main()
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Utilities for common integer checks and calculations."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def is_prime(number: int) -> bool:
|
|
5
|
+
"""Return whether *number* is a prime integer."""
|
|
6
|
+
if isinstance(number, bool) or not isinstance(number, int):
|
|
7
|
+
raise TypeError("Number must be an integer.")
|
|
8
|
+
if number < 2:
|
|
9
|
+
return False
|
|
10
|
+
divisor = 2
|
|
11
|
+
while divisor * divisor <= number:
|
|
12
|
+
if number % divisor == 0:
|
|
13
|
+
return False
|
|
14
|
+
divisor += 1
|
|
15
|
+
return True
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def factorial(number: int) -> int:
|
|
19
|
+
"""Return the factorial of a non-negative integer.
|
|
20
|
+
|
|
21
|
+
Raises:
|
|
22
|
+
TypeError: If *number* is not an integer.
|
|
23
|
+
ValueError: If *number* is negative.
|
|
24
|
+
"""
|
|
25
|
+
if isinstance(number, bool) or not isinstance(number, int):
|
|
26
|
+
raise TypeError("Number must be an integer.")
|
|
27
|
+
if number < 0:
|
|
28
|
+
raise ValueError("Factorial is not defined for negative integers.")
|
|
29
|
+
result = 1
|
|
30
|
+
for factor in range(2, number + 1):
|
|
31
|
+
result *= factor
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_palindrome(number: int) -> bool:
|
|
36
|
+
"""Return whether a non-negative integer reads the same forwards and backwards.
|
|
37
|
+
|
|
38
|
+
Negative integers are not considered palindromes.
|
|
39
|
+
"""
|
|
40
|
+
if isinstance(number, bool) or not isinstance(number, int):
|
|
41
|
+
raise TypeError("Number must be an integer.")
|
|
42
|
+
if number < 0:
|
|
43
|
+
return False
|
|
44
|
+
digits = str(number)
|
|
45
|
+
return digits == digits[::-1]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Functions for building simple text patterns."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _validate_pattern_args(size: int, char: str) -> None:
|
|
5
|
+
if isinstance(size, bool) or not isinstance(size, int):
|
|
6
|
+
raise TypeError("Pattern size must be an integer.")
|
|
7
|
+
if size < 1:
|
|
8
|
+
raise ValueError("Pattern size must be at least 1.")
|
|
9
|
+
if not isinstance(char, str) or len(char) != 1:
|
|
10
|
+
raise ValueError("Pattern character must be a single character.")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def triangle(height: int, char: str = "*") -> str:
|
|
14
|
+
"""Return a left-aligned triangle with *height* rows."""
|
|
15
|
+
_validate_pattern_args(height, char)
|
|
16
|
+
return "\n".join(char * width for width in range(1, height + 1))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def pyramid(height: int, char: str = "*") -> str:
|
|
20
|
+
"""Return a centered pyramid with *height* rows."""
|
|
21
|
+
_validate_pattern_args(height, char)
|
|
22
|
+
return "\n".join(
|
|
23
|
+
" " * (height - row) + char * (2 * row - 1)
|
|
24
|
+
for row in range(1, height + 1)
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def square(size: int, char: str = "*") -> str:
|
|
29
|
+
"""Return a square pattern with *size* rows and columns."""
|
|
30
|
+
_validate_pattern_args(size, char)
|
|
31
|
+
row = char * size
|
|
32
|
+
return "\n".join(row for _ in range(size))
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: shashank-utils
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small collection of beginner-friendly Python utilities.
|
|
5
|
+
Author-email: Shashank Yamme <yammeshashank@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest>=7.0; extra == "test"
|
|
21
|
+
Provides-Extra: ml
|
|
22
|
+
Requires-Dist: numpy>=1.24; extra == "ml"
|
|
23
|
+
Requires-Dist: pandas>=2.0; extra == "ml"
|
|
24
|
+
Requires-Dist: matplotlib>=3.7; extra == "ml"
|
|
25
|
+
Requires-Dist: scikit-learn>=1.3; extra == "ml"
|
|
26
|
+
Requires-Dist: seaborn>=0.13; extra == "ml"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# shashank-utils
|
|
30
|
+
|
|
31
|
+
A small, beginner-friendly collection of reusable Python utilities for
|
|
32
|
+
arithmetic, text patterns, unit conversions, and number checks.
|
|
33
|
+
|
|
34
|
+
## Requirements
|
|
35
|
+
|
|
36
|
+
Python 3.9 or newer.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
Install the package from a local checkout:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
python -m pip install .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For development, install the package in editable mode with its test dependency:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
python -m pip install -e ".[test]"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
To run the machine-learning examples, install their optional dependencies too:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
python -m pip install -e ".[ml]"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
This project is not published to PyPI.
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from shashank_utils import (
|
|
64
|
+
add,
|
|
65
|
+
celsius_to_fahrenheit,
|
|
66
|
+
factorial,
|
|
67
|
+
is_prime,
|
|
68
|
+
pyramid,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
print(add(2, 3)) # 5
|
|
72
|
+
print(celsius_to_fahrenheit(25)) # 77.0
|
|
73
|
+
print(factorial(5)) # 120
|
|
74
|
+
print(is_prime(17)) # True
|
|
75
|
+
print(pyramid(3))
|
|
76
|
+
# *
|
|
77
|
+
# ***
|
|
78
|
+
# *****
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Pattern functions return a string with newline-separated rows. Arithmetic and
|
|
82
|
+
conversion functions return their calculated values. `factorial` raises
|
|
83
|
+
`ValueError` for negative input, and `divide` raises `ZeroDivisionError` when
|
|
84
|
+
the divisor is zero.
|
|
85
|
+
|
|
86
|
+
## Available functions
|
|
87
|
+
|
|
88
|
+
- `calculator`: `add`, `subtract`, `multiply`, `divide`
|
|
89
|
+
- `patterns`: `triangle`, `pyramid`, `square`
|
|
90
|
+
- `conversions`: `celsius_to_fahrenheit`, `fahrenheit_to_celsius`,
|
|
91
|
+
`kilometres_to_miles`, `miles_to_kilometres`
|
|
92
|
+
- `number_utils`: `is_prime`, `factorial`, `is_palindrome`
|
|
93
|
+
|
|
94
|
+
## Machine learning lab programs
|
|
95
|
+
|
|
96
|
+
The following standalone examples are independently runnable from the project
|
|
97
|
+
root with `python src/shashank_utils/ml_program_01.py` (replace the filename
|
|
98
|
+
number as needed). Install the `ml` extra above first. Programs 1 and 5 use
|
|
99
|
+
scikit-learn's California Housing dataset; program 7 uses Seaborn's Titanic
|
|
100
|
+
dataset. Those datasets may need an internet connection the first time they are
|
|
101
|
+
loaded.
|
|
102
|
+
|
|
103
|
+
1. `ml_program_01.py` — exploratory data analysis of California Housing.
|
|
104
|
+
2. `ml_program_02.py` — Iris feature correlation matrix.
|
|
105
|
+
3. `ml_program_03.py` — two-component PCA visualization of Iris.
|
|
106
|
+
4. `ml_program_04.py` — Candidate Elimination on a small EnjoySport example.
|
|
107
|
+
5. `ml_program_05.py` — linear regression on California Housing.
|
|
108
|
+
6. `ml_program_06.py` — degree-two polynomial regression on generated data.
|
|
109
|
+
7. `ml_program_07.py` — logistic regression on Titanic passenger features.
|
|
110
|
+
8. `ml_program_08.py` — scaled K-nearest neighbors classification on Iris.
|
|
111
|
+
9. `ml_program_09.py` — decision-tree classification on Breast Cancer data.
|
|
112
|
+
10. `ml_program_10.py` — expectation-maximization clustering with a Gaussian
|
|
113
|
+
mixture model.
|
|
114
|
+
11. `ml_program_11.py` — voting, bagging, AdaBoost, and random-forest
|
|
115
|
+
classifiers on Breast Cancer data.
|
|
116
|
+
12. `ml_program_12.py` — random policy search in a small line-world
|
|
117
|
+
reinforcement-learning environment.
|
|
118
|
+
|
|
119
|
+
## Run the tests
|
|
120
|
+
|
|
121
|
+
After installing the development dependencies, run:
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
python -m pytest
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
This project is licensed under the MIT License. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
shashank_utils/__init__.py,sha256=cIvyXfLWF0J0Tc0PObEKA5uEqylhglICe08b9Wt8BH0,679
|
|
2
|
+
shashank_utils/calculator.py,sha256=RT-7J1C7sIDHS5fibWXqi7GhCBwKovaUkQ4AU4SQBQo,602
|
|
3
|
+
shashank_utils/conversions.py,sha256=H2XCIbaW_antDv4EUM2vf1NTQVtij-4Aq-ZggcjNjkk,630
|
|
4
|
+
shashank_utils/ml_program_01.py,sha256=hcT-uRj0xSnEcTFv-JxRnznXxFRQhJe1b91LeGOCyPU,989
|
|
5
|
+
shashank_utils/ml_program_02.py,sha256=QAep4xuobarx4sWcPsT0FFC7YA_bclNQN37IwkI58EI,1034
|
|
6
|
+
shashank_utils/ml_program_03.py,sha256=Y2A90nyp1X1gQymB-W9gZ7Y-3b1gXeFI7AEi6NwNLcY,1271
|
|
7
|
+
shashank_utils/ml_program_04.py,sha256=Dq4DIsRLLQ_1lY-Z7SF8edRM_yEAEVtu0Gr-hO4jBfw,5840
|
|
8
|
+
shashank_utils/ml_program_05.py,sha256=R0fkREqKluWs70rwFmM04Cr11EE1q0YdjvOT4vvarLA,1228
|
|
9
|
+
shashank_utils/ml_program_06.py,sha256=NMZgN4iXOfk40kj9IVgls_2aBCbXxg5JDfM6ulvJrCg,2233
|
|
10
|
+
shashank_utils/ml_program_07.py,sha256=9cV9od_np71F000i6rsOWw32mhSWULZzmYynh2ZxRac,2003
|
|
11
|
+
shashank_utils/ml_program_08.py,sha256=e2FY6IPIFsOla0gwYK4rR15nI18Uc7_9DMfMlIJzIp8,1068
|
|
12
|
+
shashank_utils/ml_program_09.py,sha256=LrKJ3UfOGJBQClw_a5x65xX0J3kq3h7R5-vyFNz7ffQ,1423
|
|
13
|
+
shashank_utils/ml_program_10.py,sha256=Q07HvyE0EDzyuMWnQe5kzw8d95z_EDfEAoWPtJ_8cLo,1304
|
|
14
|
+
shashank_utils/ml_program_11.py,sha256=oVL2ZEYb8A6WkBaKRmpOZjlP7vYD2uy4CEJzl78F_Qw,2307
|
|
15
|
+
shashank_utils/ml_program_12.py,sha256=nRDi0oflAZfDV6rKTXap5a3akwQEoa7JQhh4Xx0X0-0,2330
|
|
16
|
+
shashank_utils/number_utils.py,sha256=2OhM2_Q40tGO9rZ_xLqimq16AJcFdF8bkuUPQO_HvUk,1430
|
|
17
|
+
shashank_utils/patterns.py,sha256=242-xDNrGA31AdjQ8ZDWNG9OnZ4wcylSb32Gq_7fSic,1181
|
|
18
|
+
shashank_utils-0.1.0.dist-info/licenses/LICENSE,sha256=1LagO9YbcgmdaQBJzxat2LE3ku7am3b6GSB0FBisbyY,1092
|
|
19
|
+
shashank_utils-0.1.0.dist-info/METADATA,sha256=4d5L618IoGGGlCG5vurbvH9T9DEgKm1S3CiSUPxuYjQ,4303
|
|
20
|
+
shashank_utils-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
21
|
+
shashank_utils-0.1.0.dist-info/top_level.txt,sha256=eXVJe6cqLdG3LP9XSN0WkEmgF40F97NTLpt8jHULPJ8,15
|
|
22
|
+
shashank_utils-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Shashank Yamme
|
|
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
|
+
shashank_utils
|