计划执行与检查节点
executing-plans
按既定实施计划完成工作,保持过程检查和反馈。
ds-logistic-regression【效率与协作】"Implements logistic regression for binary and multinomial classification with probability estimation and odds ratio interpretation"
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: ds-logistic-regression compatibility: opencode completeness: 95 content-types:
Comprehensive guide to logistic regression in machine learning and data science workflows.
Logistic Regression is a critical component of the machine learning workflow. This skill covers:
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.datasets import make_classification
from typing import Tuple
def basic_logistic_regression() -> Tuple[pd.DataFrame, LogisticRegression]:
"""Generate synthetic data, train model, and return results."""
X, y = make_classification(n_samples=500, n_features=10, n_informative=5, random_state=42)
df = pd.DataFrame(X, columns=[f'feature_{i}' for i in range(X.shape[1])])
df['target'] = y
X_train, X_test, y_train, y_test = train_test_split(
df.drop('target', axis=1), df['target'], test_size=0.2, random_state=42
)
model = LogisticRegression(max_iter=1000, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(classification_report(y_test, y_pred))
return df, model
if __name__ == "__main__":
basic_logistic_regression()
import logging
import pandas as pd
import numpy as np
from typing import Any, Dict, List
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
logger = logging.getLogger(__name__)
class LogisticRegressionPipeline:
"""Production-ready logistic regression pipeline with validation and metrics."""
def __init__(self, C: float = 1.0, penalty: str = 'l2', random_state: int = 42) -> None:
self.C = C
self.penalty = penalty
self.random_state = random_state
self.pipeline: Pipeline | None = None
self.scaler: StandardScaler | None = None
self.model: LogisticRegression | None = None
def execute(self, data: pd.DataFrame, target_col: str = 'target') -> Dict[str, Any]:
"""Execute logistic regression pipeline on provided data."""
if data is None or data.empty:
raise ValueError("Input data cannot be None or empty")
if target_col not in data.columns:
raise ValueError(f"Target column '{target_col}' not found in data")
X = data.drop(columns=[target_col])
y = data[target_col]
self.scaler = StandardScaler()
self.model = LogisticRegression(C=self.C, penalty=self.penalty, random_state=self.random_state, max_iter=1000)
self.pipeline = Pipeline([('scaler', self.scaler), ('classifier', self.model)])
self.pipeline.fit(X, y)
predictions = self.pipeline.predict(X)
probabilities = self.pipeline.predict_proba(X)
logger.info("Pipeline executed successfully")
return {
'status': 'success'
'predictions': predictions.tolist()
'probabilities': probabilities.tolist()
'model_params': {'C': self.C, 'penalty': self.penalty}
'feature_names': X.columns.tolist()
}
| Pitfall | Problem | Solution | |
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.