scikit-doc 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.
@@ -0,0 +1,34 @@
1
+ """Train-only imputation, one-hot encoding and standard scaling."""
2
+ from __future__ import annotations
3
+
4
+ import pandas as pd
5
+ from sklearn.compose import ColumnTransformer
6
+ from sklearn.impute import SimpleImputer
7
+ from sklearn.pipeline import Pipeline
8
+ from sklearn.preprocessing import OneHotEncoder, StandardScaler
9
+
10
+
11
+ def build_customer_preprocessor(X_train: pd.DataFrame):
12
+ numeric_features = X_train.select_dtypes(include="number").columns.tolist()
13
+ categorical_features = X_train.select_dtypes(exclude="number").columns.tolist()
14
+ numeric_pipe = Pipeline([
15
+ ("imputer", SimpleImputer(strategy="median")),
16
+ ("scaler", StandardScaler()),
17
+ ])
18
+ categorical_pipe = Pipeline([
19
+ ("imputer", SimpleImputer(strategy="most_frequent")),
20
+ ("encoder", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
21
+ ])
22
+ return ColumnTransformer([
23
+ ("categorical", categorical_pipe, categorical_features),
24
+ ("numeric", numeric_pipe, numeric_features),
25
+ ], remainder="drop")
26
+
27
+
28
+ def fit_transform_splits(X_train, X_test):
29
+ preprocessor = build_customer_preprocessor(X_train)
30
+ return (
31
+ preprocessor.fit_transform(X_train),
32
+ preprocessor.transform(X_test),
33
+ preprocessor,
34
+ )
@@ -0,0 +1,45 @@
1
+ """Inspect a CSV and answer common tabular-data questions.
2
+
3
+ Usage:
4
+ python data_inspection.py path/to/data.csv --target Price
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+
13
+ def inspect_csv(path: str, target: str | None = None) -> pd.DataFrame:
14
+ df = pd.read_csv(path)
15
+ print("shape:", df.shape)
16
+ print("samples:", df.shape[0])
17
+ print("columns:", df.columns.tolist())
18
+ print("dtypes:\n", df.dtypes)
19
+ print("numeric columns:", df.select_dtypes(include="number").columns.tolist())
20
+ print("categorical columns:", df.select_dtypes(include=["object", "category"]).columns.tolist())
21
+ print("missing values:\n", df.isna().sum().sort_values(ascending=False))
22
+ print("unique values:")
23
+ for column in df.columns:
24
+ if df[column].nunique(dropna=False) <= 30:
25
+ print(f" {column}: {df[column].unique()}")
26
+ if target and target in df:
27
+ print("target median:", df[target].median())
28
+ print("target mean:", df[target].mean())
29
+ print("10 lowest target values mean:", df[target].nsmallest(10).mean())
30
+ print("10 highest target values mean:", df[target].nlargest(10).mean())
31
+ numeric = df.select_dtypes(include="number")
32
+ if numeric.shape[1] >= 2:
33
+ corr = numeric.corr()
34
+ pairs = corr.where(~np.eye(corr.shape[0], dtype=bool)).stack()
35
+ print("least-correlated pair:\n", pairs.sort_values().head(1))
36
+ print("most positively correlated pair:\n", pairs.sort_values(ascending=False).head(1))
37
+ return df
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser()
42
+ parser.add_argument("csv_path")
43
+ parser.add_argument("--target")
44
+ args = parser.parse_args()
45
+ inspect_csv(args.csv_path, args.target)
@@ -0,0 +1,37 @@
1
+ """SelectKBest, SequentialFeatureSelector and RFE examples."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ from sklearn.feature_selection import RFE, SelectKBest, SequentialFeatureSelector, f_regression
6
+ from sklearn.linear_model import LinearRegression
7
+ from sklearn.model_selection import KFold
8
+
9
+
10
+ def select_k_best(X_train, y_train, feature_names=None, k=4):
11
+ selector = SelectKBest(f_regression, k=k).fit(X_train, y_train)
12
+ names = np.asarray(feature_names) if feature_names is not None else np.arange(X_train.shape[1])
13
+ selected = names[selector.get_support()]
14
+ ranked = np.argsort(np.nan_to_num(selector.scores_, nan=-np.inf))[::-1][:k]
15
+ return {
16
+ "selector": selector,
17
+ "selected": selected.tolist(),
18
+ "ranked": names[ranked].tolist(),
19
+ "scores": selector.scores_,
20
+ "pvalues": selector.pvalues_,
21
+ }
22
+
23
+
24
+ def sequential_forward(X_train, y_train, n_features=6, random_state=42):
25
+ cv = KFold(n_splits=5, shuffle=True, random_state=random_state)
26
+ selector = SequentialFeatureSelector(
27
+ LinearRegression(), n_features_to_select=n_features,
28
+ direction="forward", cv=cv, n_jobs=-1,
29
+ ).fit(X_train, y_train)
30
+ return np.flatnonzero(selector.get_support()), selector
31
+
32
+
33
+ def recursive_elimination(X_train, y_train, remove_count=1):
34
+ selector = RFE(
35
+ LinearRegression(), n_features_to_select=X_train.shape[1] - remove_count
36
+ ).fit(X_train, y_train)
37
+ return np.flatnonzero(~selector.support_), selector
@@ -0,0 +1,49 @@
1
+ """Flight-duration parsing, day-part features and ordered encoding."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import numpy as np
6
+ import pandas as pd
7
+ from sklearn.preprocessing import OrdinalEncoder
8
+
9
+
10
+ def duration_to_minutes(value):
11
+ if pd.isna(value):
12
+ return np.nan
13
+ text = str(value).strip()
14
+ h = re.search(r"(\d+)\s*h", text, flags=re.I)
15
+ m = re.search(r"(\d+)\s*m", text, flags=re.I)
16
+ return 60 * (int(h.group(1)) if h else 0) + (int(m.group(1)) if m else 0)
17
+
18
+
19
+ def part_of_day(value):
20
+ if pd.isna(value):
21
+ return np.nan
22
+ hour = int(str(value).split(":", 1)[0])
23
+ if 5 <= hour < 12:
24
+ return "Morning"
25
+ if 12 <= hour < 17:
26
+ return "Afternoon"
27
+ if 17 <= hour < 20:
28
+ return "Evening"
29
+ return "Night"
30
+
31
+
32
+ def engineer_flight_features(df: pd.DataFrame) -> pd.DataFrame:
33
+ data = df.copy()
34
+ data["Additional_Info"] = data["Additional_Info"].replace("No Info", "No info")
35
+ data["Duration"] = data["Duration"].map(duration_to_minutes)
36
+ data["Dep_Time"] = data["Dep_Time"].map(part_of_day)
37
+ data["Arrival_Time"] = data["Arrival_Time"].map(part_of_day)
38
+ data["WeekDay"] = data["WeekDay"].isin(["Saturday", "Sunday"]).astype("int8")
39
+ return data
40
+
41
+
42
+ def make_ordinal_encoder():
43
+ stop_order = ["non-stop", "1 stop", "2 stops", "3 stops", "4 stops"]
44
+ time_order = ["Morning", "Afternoon", "Evening", "Night"]
45
+ return OrdinalEncoder(
46
+ categories=[stop_order, time_order],
47
+ handle_unknown="use_encoded_value",
48
+ unknown_value=-1,
49
+ )
@@ -0,0 +1,64 @@
1
+ """Sentinel detection, conditional counts and heterogeneous preprocessing."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ from sklearn.compose import ColumnTransformer
7
+ from sklearn.impute import SimpleImputer
8
+ from sklearn.pipeline import Pipeline
9
+ from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, StandardScaler
10
+
11
+
12
+ def clean_and_transform(df: pd.DataFrame):
13
+ data = df.copy()
14
+ bad_rooms = data["RM"].lt(1)
15
+ bad_age = data["AGE"].lt(0)
16
+ bad_riverside = data["RIVERSIDE"].eq("UNKNOWN")
17
+ sentinel_counts = {
18
+ "rooms": int(bad_rooms.sum()),
19
+ "age": int(bad_age.sum()),
20
+ "riverside": int(bad_riverside.sum()),
21
+ }
22
+ data.loc[bad_rooms, "RM"] = np.nan
23
+ data.loc[bad_age, "AGE"] = np.nan
24
+ data.loc[bad_riverside, "RIVERSIDE"] = np.nan
25
+
26
+ X = data.drop(columns=["PRICE", "CATEGORY"], errors="ignore")
27
+ y = data["PRICE"]
28
+ from sklearn.model_selection import train_test_split
29
+ X_train, X_test, y_train, y_test = train_test_split(
30
+ X, y, test_size=0.25, random_state=42
31
+ )
32
+
33
+ transformer = ColumnTransformer([
34
+ ("crime", StandardScaler(), ["CRIM"]),
35
+ ("zoning", MinMaxScaler(), ["ZN"]),
36
+ ("industry", MinMaxScaler(), ["INDUS"]),
37
+ ("pollution", StandardScaler(), ["POLINDEX"]),
38
+ ("other_numeric", MinMaxScaler(),
39
+ ["DIS", "HIGHWAYCOUNT", "TAX", "PTRATIO", "IMM", "BPL"]),
40
+ ("rooms", Pipeline([
41
+ ("imputer", SimpleImputer(strategy="mean")),
42
+ ("scale", MinMaxScaler()),
43
+ ]), ["RM"]),
44
+ ("age", Pipeline([
45
+ ("imputer", SimpleImputer(strategy="median")),
46
+ ("scale", StandardScaler()),
47
+ ]), ["AGE"]),
48
+ ("riverside", Pipeline([
49
+ ("imputer", SimpleImputer(strategy="most_frequent")),
50
+ ("encode", OneHotEncoder(drop="first", handle_unknown="ignore",
51
+ sparse_output=False)),
52
+ ]), ["RIVERSIDE"]),
53
+ ], remainder="drop")
54
+
55
+ X_train_t = transformer.fit_transform(X_train)
56
+ X_test_t = transformer.transform(X_test)
57
+ return {
58
+ "sentinel_counts": sentinel_counts,
59
+ "X_train": X_train_t,
60
+ "X_test": X_test_t,
61
+ "y_train": y_train,
62
+ "y_test": y_test,
63
+ "transformer": transformer,
64
+ }
@@ -0,0 +1,60 @@
1
+ """Grid-search recipes for SGDRegressor, PCA/Lasso and polynomial/Lasso."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ from sklearn.decomposition import PCA
6
+ from sklearn.feature_selection import SelectKBest, f_regression
7
+ from sklearn.linear_model import Lasso, SGDRegressor
8
+ from sklearn.model_selection import GridSearchCV
9
+ from sklearn.pipeline import Pipeline
10
+ from sklearn.preprocessing import PolynomialFeatures
11
+
12
+
13
+ def search_sgd(X_train, y_train):
14
+ grid = {
15
+ "penalty": ["l1", "l2", "elasticnet"],
16
+ "alpha": [1e-5, 1e-4, 1e-3, 1e-2, 1e-1],
17
+ "tol": [1e-3, 1e-2],
18
+ }
19
+ search = GridSearchCV(
20
+ SGDRegressor(random_state=42), grid, cv=5,
21
+ scoring="neg_mean_squared_error", refit=True, n_jobs=-1,
22
+ )
23
+ return search.fit(X_train, y_train)
24
+
25
+
26
+ def search_pca_lasso(X_train, y_train):
27
+ pipe = Pipeline([("pca", PCA()), ("lasso", Lasso())])
28
+ grid = {
29
+ "pca__n_components": [0.85, 0.95],
30
+ "lasso__alpha": [10, 1, 0.1, 0.01],
31
+ }
32
+ search = GridSearchCV(
33
+ pipe, grid, cv=5, scoring="neg_mean_absolute_error", n_jobs=-1, refit=True,
34
+ )
35
+ return search.fit(X_train, y_train)
36
+
37
+
38
+ def search_polynomial_lasso(X_train, y_train):
39
+ pipe = Pipeline([
40
+ ("poly", PolynomialFeatures(interaction_only=False)),
41
+ ("lasso", Lasso(warm_start=True, random_state=0)),
42
+ ])
43
+ grid = {
44
+ "poly__degree": [1, 2, 3],
45
+ "lasso__alpha": [0.01, 0.1, 1, 10, 50],
46
+ }
47
+ search = GridSearchCV(
48
+ pipe, grid, cv=5, scoring="neg_mean_squared_error", n_jobs=-1, refit=True,
49
+ )
50
+ return search.fit(X_train, y_train)
51
+
52
+
53
+ def make_f_regression_pipeline(X_train, y_train, k=4):
54
+ pipe = Pipeline([
55
+ ("select", SelectKBest(f_regression, k=k)),
56
+ ("sgd", SGDRegressor(random_state=42)),
57
+ ])
58
+ pipe.fit(X_train, y_train)
59
+ selector = pipe.named_steps["select"]
60
+ return pipe, selector
@@ -0,0 +1,22 @@
1
+ """PCA variance summaries followed by RidgeCV."""
2
+ from __future__ import annotations
3
+
4
+ from sklearn.decomposition import PCA
5
+ from sklearn.linear_model import RidgeCV
6
+
7
+
8
+ def fit_pca_ridgecv(X_train, y_train, X_test, y_test,
9
+ components=7, alphas=(0.01, 0.1, 1, 10, 100)):
10
+ pca = PCA(n_components=components, svd_solver="full", whiten=True, random_state=42)
11
+ X_train_pca = pca.fit_transform(X_train)
12
+ X_test_pca = pca.transform(X_test)
13
+ model = RidgeCV(alphas=list(alphas), cv=5).fit(X_train_pca, y_train)
14
+ return {
15
+ "pca": pca,
16
+ "model": model,
17
+ "variance_fraction_sum": float(pca.explained_variance_ratio_.sum()),
18
+ "first_component_fraction": float(pca.explained_variance_ratio_[0]),
19
+ "first_component_eigenvalue": float(pca.explained_variance_[0]),
20
+ "retained_components": int(pca.n_components_),
21
+ "test_r2": float(model.score(X_test_pca, y_test)),
22
+ }
@@ -0,0 +1,32 @@
1
+ """Fit common regressors and inspect metrics and coefficients."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ from sklearn.linear_model import LinearRegression, Ridge, Lasso, SGDRegressor
6
+ from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
7
+
8
+
9
+ def evaluate_regressor(estimator, X_train, y_train, X_test, y_test):
10
+ estimator.fit(X_train, y_train)
11
+ prediction = estimator.predict(X_test)
12
+ result = {
13
+ "mae": float(mean_absolute_error(y_test, prediction)),
14
+ "mse": float(mean_squared_error(y_test, prediction)),
15
+ "rmse": float(np.sqrt(mean_squared_error(y_test, prediction))),
16
+ "r2": float(r2_score(y_test, prediction)),
17
+ }
18
+ if hasattr(estimator, "coef_"):
19
+ absolute = np.abs(np.asarray(estimator.coef_)).ravel()
20
+ result.update({
21
+ "max_abs_coefficient": float(absolute.max()),
22
+ "most_important_index": int(absolute.argmax()),
23
+ "least_important_index": int(absolute.argmin()),
24
+ "intercept": np.asarray(estimator.intercept_).tolist(),
25
+ })
26
+ if hasattr(estimator, "n_iter_"):
27
+ result["iterations"] = int(np.max(estimator.n_iter_))
28
+ return estimator, result
29
+
30
+
31
+ if __name__ == "__main__":
32
+ print("Import evaluate_regressor and pass your train/test arrays.")
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: scikit-doc
3
+ Version: 0.1.0
4
+ Summary: Step-by-step scikit-learn documentation with source-grounded worked examples.
5
+ Project-URL: Documentation, https://scikit-learn.org/stable/user_guide.html
6
+ Project-URL: Scikit-learn API, https://scikit-learn.org/stable/api/
7
+ Project-URL: Scikit-learn examples, https://scikit-learn.org/stable/auto_examples/index.html
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: numpy>=1.24
12
+ Requires-Dist: pandas>=1.5
13
+ Requires-Dist: scikit-learn>=1.3
14
+ Provides-Extra: plots
15
+ Requires-Dist: matplotlib>=3.7; extra == "plots"
16
+ Requires-Dist: seaborn>=0.12; extra == "plots"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=7; extra == "dev"
19
+ Requires-Dist: build>=1; extra == "dev"
20
+ Requires-Dist: twine>=4; extra == "dev"
21
+ Dynamic: license-file
@@ -0,0 +1,19 @@
1
+ scikit_doc/__init__.py,sha256=gjAHnbTvUCMM3f5dinno94WJxU3IAj-cmHLoGEd1e8o,15530
2
+ scikit_doc/data/NOTEBOOK_EXAMPLES.md,sha256=n0NPJn-Fi-xHC9wQhD6_Gm_qVdaq7jninnlp8dwedYs,101175
3
+ scikit_doc/data/SKLEARN_ROOT_HELP_1_6_1.txt,sha256=eAEY2wA-oyh9U-Qo5WdNdijVqgg_Hr3plCQljuCPxX0,14806
4
+ scikit_doc/data/USER_GUIDE.md,sha256=5YCbCXXMFYS9Ln8r_da0pXExfq6lDoyfGdy_Ram0egQ,39186
5
+ scikit_doc/data/WORKED_EXAMPLES.md,sha256=u3ojZDbLYDl7V2nC04wFmcZXNah2huX8VVunQYtPrk0,116031
6
+ scikit_doc/data/examples.json,sha256=Ixqvh5im2OZ9bFFZettOnaYiOhR_Ux8bNCdwr52S5Eg,135356
7
+ scikit_doc/examples/customer_preprocessing.py,sha256=Oe6duNM0fmYbpTBfBUuXtadtS7lcqIoML6QQ-ZKDZ4E,1251
8
+ scikit_doc/examples/data_inspection.py,sha256=nzeqXpO1g37Wo27cjPTfNxC8ts_Uk-is7lvXagDweKE,1762
9
+ scikit_doc/examples/feature_selection.py,sha256=lWLCqvlg0PswcxblDkRPlsEr1tZdSdVTWGTG1DUk_ro,1496
10
+ scikit_doc/examples/flight_features.py,sha256=H0vUBe7zZJgPc1rR9y2pW8rpAbPhLfgeRZD_qOICBr4,1543
11
+ scikit_doc/examples/house_cleaning.py,sha256=C4QSHXPBePWXZUI1pfSJQZiq4X0_nIRl7E5N3GVbMTs,2306
12
+ scikit_doc/examples/model_search.py,sha256=4sac-mjk3lbY7V4f-A3n8W0G2eiBB402WgsC1v8QO0w,1900
13
+ scikit_doc/examples/pca_ridgecv.py,sha256=QbQey2kKrWA7opzH4rOWdkj_LEj5PH0JFnUbjp7T3_0,937
14
+ scikit_doc/examples/regression_models.py,sha256=8kWCOWUirRO9lssaEyxxmDI2xVbnSQ2i1BfeQd82HL8,1307
15
+ scikit_doc-0.1.0.dist-info/licenses/LICENSE,sha256=kPDAZ9PLvYS3pRCpwjmjBa9pLbA8POVUuYQJ1GpCzHQ,1101
16
+ scikit_doc-0.1.0.dist-info/METADATA,sha256=KUgDVSAcGUp4oxjAZITAWrGO_-G-IIrDw5EUgif0jvI,853
17
+ scikit_doc-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
18
+ scikit_doc-0.1.0.dist-info/top_level.txt,sha256=wT2QnS4rpO7brW_V8VMmL16TPa8jnuURpt0smk5hCGU,11
19
+ scikit_doc-0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Scikit-learn Contributers
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
+ scikit_doc