scikit-learn
БесплатноБез исполняемых скриптовНе проверенAssists with building, evaluating, and deploying machine learning models using scikit-learn. Use when performing data preprocessing, feature engineering…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
scikit-learn
Overview
Scikit-learn is a Python machine learning library that provides a consistent API for the full ML workflow: data preprocessing (scaling, encoding, imputation), model selection (classification, regression, clustering), hyperparameter tuning (grid search, randomized search), cross-validation, and pipeline construction. It supports serialization via joblib for production deployment.
Instructions
- When preprocessing data, use
ColumnTransformerto apply different transformers to numeric and categorical columns (StandardScaler, OneHotEncoder, SimpleImputer), always within a Pipeline to prevent data leakage. - When choosing models, start with fast baselines (LogisticRegression, RandomForest) and use
HistGradientBoostingClassifierfor best tabular performance, since it handles missing values natively and is faster than GradientBoosting. - When evaluating, use
cross_val_scorewith 5-fold CV instead of single train/test splits, and useclassification_report()instead of accuracy alone since accuracy is misleading on imbalanced datasets. - When tuning hyperparameters, use
RandomizedSearchCVwhen the search space exceeds 100 combinations (faster than exhaustive GridSearchCV), and useStratifiedKFoldorTimeSeriesSplitas appropriate. - When building pipelines, chain preprocessing and model steps with
Pipelineto ensure transformers fit only on training data, then serialize the full pipeline withjoblib.dump()for deployment. - When selecting features, use
permutation_importance()for model-agnostic measurement,SelectKBestfor statistical filtering, orfeature_importances_from tree-based models.
Examples
Example 1: Build a customer churn prediction pipeline
User request: "Create a model to predict which customers will churn"
The script below is self-contained (it generates stand-in customer data; replace the DataFrame with the real export) and was run on scikit-learn 1.9.1.
import joblib
import numpy as np
import pandas as pd
from scipy.stats import randint
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import classification_report
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(42)
n = 2000
df = pd.DataFrame({
"tenure_months": rng.integers(1, 72, n),
"monthly_charge": rng.normal(70, 20, n).round(2),
"plan": rng.choice(["basic", "plus", "pro"], n),
"payment": rng.choice(["card", "invoice", "paypal"], n),
})
df.loc[rng.random(n) < 0.05, "monthly_charge"] = np.nan
risk = 0.04 * (df["monthly_charge"].fillna(70) - 70) - 0.05 * df["tenure_months"] + (df["plan"] == "basic") - 0.5
df["churned"] = rng.random(n) < 1 / (1 + np.exp(-risk))
X, y = df.drop(columns="churned"), df["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
numeric = ["tenure_months", "monthly_charge"]
categorical = ["plan", "payment"]
prep = ColumnTransformer([
("num", Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
pipe = Pipeline([("prep", prep), ("model", HistGradientBoostingClassifier(random_state=42))])
search = RandomizedSearchCV(
pipe,
{"model__learning_rate": [0.03, 0.05, 0.1], "model__max_leaf_nodes": randint(8, 64)},
n_iter=10, cv=StratifiedKFold(5, shuffle=True, random_state=42), scoring="recall", random_state=42, n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_)
print(classification_report(y_test, search.predict(X_test)))
joblib.dump(search.best_estimator_, "churn.joblib")
print(joblib.load("churn.joblib").predict_proba(X_test.head(2))[:, 1].round(2))
Result: it prints the best parameters, a classification_report for the held-out 25%, and the churn probability for two customers loaded back from churn.joblib. On the synthetic data churn recall is about 0.34, which is why the report, not accuracy, is the number to read. Raise n_iter and add real features before trusting a model.
Example 2: Cluster customers into segments
User request: "Segment customers based on purchasing behavior"
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, _ = make_blobs(n_samples=600, centers=4, n_features=3, random_state=7) # stand-in for spend, frequency, recency
for k in range(2, 8):
p = make_pipeline(StandardScaler(), KMeans(n_clusters=k, n_init="auto", random_state=7)).fit(X)
print(k, round(silhouette_score(p[:-1].transform(X), p[-1].labels_), 3))
Result: one silhou
Установить scikit-learn в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл scikit-learn?
Assists with building, evaluating, and deploying machine learning models using scikit-learn. Use when performing data preprocessing, feature engineering, model selection, hyperparameter tuning, cross-validation, or building pipelines for classification, regression, and clustering tasks. Trigger words: sklearn, scikit-learn, machine learning, classification, regression, pipeline, cross-validation.
Как установить скилл scikit-learn?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл scikit-learn запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic