shashank-utils 0.1.0__tar.gz

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 (32) hide show
  1. shashank_utils-0.1.0/LICENSE +21 -0
  2. shashank_utils-0.1.0/PKG-INFO +129 -0
  3. shashank_utils-0.1.0/README.md +101 -0
  4. shashank_utils-0.1.0/pyproject.toml +46 -0
  5. shashank_utils-0.1.0/setup.cfg +4 -0
  6. shashank_utils-0.1.0/src/shashank_utils/__init__.py +30 -0
  7. shashank_utils-0.1.0/src/shashank_utils/calculator.py +27 -0
  8. shashank_utils-0.1.0/src/shashank_utils/conversions.py +21 -0
  9. shashank_utils-0.1.0/src/shashank_utils/ml_program_01.py +32 -0
  10. shashank_utils-0.1.0/src/shashank_utils/ml_program_02.py +31 -0
  11. shashank_utils-0.1.0/src/shashank_utils/ml_program_03.py +40 -0
  12. shashank_utils-0.1.0/src/shashank_utils/ml_program_04.py +162 -0
  13. shashank_utils-0.1.0/src/shashank_utils/ml_program_05.py +36 -0
  14. shashank_utils-0.1.0/src/shashank_utils/ml_program_06.py +65 -0
  15. shashank_utils-0.1.0/src/shashank_utils/ml_program_07.py +64 -0
  16. shashank_utils-0.1.0/src/shashank_utils/ml_program_08.py +35 -0
  17. shashank_utils-0.1.0/src/shashank_utils/ml_program_09.py +45 -0
  18. shashank_utils-0.1.0/src/shashank_utils/ml_program_10.py +43 -0
  19. shashank_utils-0.1.0/src/shashank_utils/ml_program_11.py +69 -0
  20. shashank_utils-0.1.0/src/shashank_utils/ml_program_12.py +67 -0
  21. shashank_utils-0.1.0/src/shashank_utils/number_utils.py +45 -0
  22. shashank_utils-0.1.0/src/shashank_utils/patterns.py +32 -0
  23. shashank_utils-0.1.0/src/shashank_utils.egg-info/PKG-INFO +129 -0
  24. shashank_utils-0.1.0/src/shashank_utils.egg-info/SOURCES.txt +30 -0
  25. shashank_utils-0.1.0/src/shashank_utils.egg-info/dependency_links.txt +1 -0
  26. shashank_utils-0.1.0/src/shashank_utils.egg-info/requires.txt +10 -0
  27. shashank_utils-0.1.0/src/shashank_utils.egg-info/top_level.txt +1 -0
  28. shashank_utils-0.1.0/tests/test_calculator.py +15 -0
  29. shashank_utils-0.1.0/tests/test_conversions.py +18 -0
  30. shashank_utils-0.1.0/tests/test_ml_programs.py +48 -0
  31. shashank_utils-0.1.0/tests/test_number_utils.py +27 -0
  32. shashank_utils-0.1.0/tests/test_patterns.py +19 -0
@@ -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,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,101 @@
1
+ # shashank-utils
2
+
3
+ A small, beginner-friendly collection of reusable Python utilities for
4
+ arithmetic, text patterns, unit conversions, and number checks.
5
+
6
+ ## Requirements
7
+
8
+ Python 3.9 or newer.
9
+
10
+ ## Installation
11
+
12
+ Install the package from a local checkout:
13
+
14
+ ```bash
15
+ python -m pip install .
16
+ ```
17
+
18
+ For development, install the package in editable mode with its test dependency:
19
+
20
+ ```bash
21
+ python -m pip install -e ".[test]"
22
+ ```
23
+
24
+ To run the machine-learning examples, install their optional dependencies too:
25
+
26
+ ```bash
27
+ python -m pip install -e ".[ml]"
28
+ ```
29
+
30
+ This project is not published to PyPI.
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from shashank_utils import (
36
+ add,
37
+ celsius_to_fahrenheit,
38
+ factorial,
39
+ is_prime,
40
+ pyramid,
41
+ )
42
+
43
+ print(add(2, 3)) # 5
44
+ print(celsius_to_fahrenheit(25)) # 77.0
45
+ print(factorial(5)) # 120
46
+ print(is_prime(17)) # True
47
+ print(pyramid(3))
48
+ # *
49
+ # ***
50
+ # *****
51
+ ```
52
+
53
+ Pattern functions return a string with newline-separated rows. Arithmetic and
54
+ conversion functions return their calculated values. `factorial` raises
55
+ `ValueError` for negative input, and `divide` raises `ZeroDivisionError` when
56
+ the divisor is zero.
57
+
58
+ ## Available functions
59
+
60
+ - `calculator`: `add`, `subtract`, `multiply`, `divide`
61
+ - `patterns`: `triangle`, `pyramid`, `square`
62
+ - `conversions`: `celsius_to_fahrenheit`, `fahrenheit_to_celsius`,
63
+ `kilometres_to_miles`, `miles_to_kilometres`
64
+ - `number_utils`: `is_prime`, `factorial`, `is_palindrome`
65
+
66
+ ## Machine learning lab programs
67
+
68
+ The following standalone examples are independently runnable from the project
69
+ root with `python src/shashank_utils/ml_program_01.py` (replace the filename
70
+ number as needed). Install the `ml` extra above first. Programs 1 and 5 use
71
+ scikit-learn's California Housing dataset; program 7 uses Seaborn's Titanic
72
+ dataset. Those datasets may need an internet connection the first time they are
73
+ loaded.
74
+
75
+ 1. `ml_program_01.py` — exploratory data analysis of California Housing.
76
+ 2. `ml_program_02.py` — Iris feature correlation matrix.
77
+ 3. `ml_program_03.py` — two-component PCA visualization of Iris.
78
+ 4. `ml_program_04.py` — Candidate Elimination on a small EnjoySport example.
79
+ 5. `ml_program_05.py` — linear regression on California Housing.
80
+ 6. `ml_program_06.py` — degree-two polynomial regression on generated data.
81
+ 7. `ml_program_07.py` — logistic regression on Titanic passenger features.
82
+ 8. `ml_program_08.py` — scaled K-nearest neighbors classification on Iris.
83
+ 9. `ml_program_09.py` — decision-tree classification on Breast Cancer data.
84
+ 10. `ml_program_10.py` — expectation-maximization clustering with a Gaussian
85
+ mixture model.
86
+ 11. `ml_program_11.py` — voting, bagging, AdaBoost, and random-forest
87
+ classifiers on Breast Cancer data.
88
+ 12. `ml_program_12.py` — random policy search in a small line-world
89
+ reinforcement-learning environment.
90
+
91
+ ## Run the tests
92
+
93
+ After installing the development dependencies, run:
94
+
95
+ ```bash
96
+ python -m pytest
97
+ ```
98
+
99
+ ## License
100
+
101
+ This project is licensed under the MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "shashank-utils"
7
+ version = "0.1.0"
8
+ description = "A small collection of beginner-friendly Python utilities."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ authors = [
12
+ { name = "Shashank Yamme", email = "yammeshashank@gmail.com" },
13
+ ]
14
+ license = "MIT"
15
+ license-files = ["LICENSE"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest>=7.0"]
30
+ ml = [
31
+ "numpy>=1.24",
32
+ "pandas>=2.0",
33
+ "matplotlib>=3.7",
34
+ "scikit-learn>=1.3",
35
+ "seaborn>=0.13",
36
+ ]
37
+
38
+ [tool.setuptools]
39
+ package-dir = { "" = "src" }
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]
46
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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()