Zero Labs
Industry News / AI

Essential Python Libraries for Data Science

Source · Towards AI By Raj kumar

From the publisher’s feed, collected in the ZeroLabs newsroom.

Part 3: Classical Machine LearningIn Part 1, we focused on how data is represented, transformed, and computed using NumPy and Pandas. By the end of that part, the dataset was clean, structured, and numerically stable.In Part 2, we resisted the urge to jump straight into modeling. Instead, we validated assumptions through visualization and diagnostics. We inspected distributions, examined feature relationships, identified correlation and redundancy, and documented constraints that would influence downstream decisions.At this point, the data is not just prepared. It is understood.Only now does it make sense to introduce machine learning.This is an important distinction. Classical machine learning does not add intelligence to raw data. It formalizes patterns that already exist. When modeling is introduced too early, it amplifies noise, hidden bias, and data quality issues. When introduced at the right time, it becomes a powerful and reliable decision-making layer.This third part continues in the same notebook, using the same normalized and diagnosed dataset from Parts 1 and part 2. No data is reloaded. No features are redefined. The diagnostic observations already recorded will now influence how models are built, evaluated, and interpreted.The focus here is classical machine learning for structured, tabular data, using scikit-learn. Not from a competition perspective, and not as a catalog of algorithms, but as a systematic modeling process that prioritizes stability, interpretability, and reproducibility.We will start with simple, well-understood baselines, build pipelines that reflect real workflows, and evaluate models in a way that aligns with production constraints rather than leaderboard metrics.By the end of this part, you will not just have trained models. You will have a modeling approach that fits naturally into the data pipeline we have built so far.In this part, we will:Split data correctly while preserving assumptionsBuild preprocessing and modeling pipelinesTrain baseline models for structured dataEvaluate performance using appropriate metricsEstablish a foundation for more advanced models in later partsEach step will extend the same end-to-end example, without resetting or reshaping the workflow.Transition to ModelingWith data prepared in Part 1 and validated in Part 2, the next step is to introduce machine learning in the most conservative and reliable way possible.We begin by defining how data flows into a model.Step 11: Train–Test Split — Defining the Boundary Between Learning and EvaluationOnce data has been prepared and validated, the first modeling decision is not which algorithm to use. It is how to separate what the model is allowed to learn from what it will be evaluated on.This boundary is critical. A poorly designed train–test split introduces leakage, inflates performance metrics, and creates false confidence that only collapses later in production. A well-designed split enforces discipline and makes model evaluation meaningful.In real systems, models are always evaluated on future or unseen data. The train–test split is the simplest approximation of that reality.Because the dataset we are working with is already normalized and diagnostically validated, this step is not about fixing data issues. It is about preserving assumptions and ensuring that evaluation reflects how the model will actually be used.Why Train–Test Splitting Comes Before ModelingMany beginners treat the train–test split as a mechanical step. In production environments, it is a design decision.Key considerations include:Preventing information leakageEnsuring reproducibilityMaintaining alignment with downstream evaluationEstablishing a stable baseline for comparisonOnce this split is defined, everything that follows must respect it.Step 11.1: Defining Features and TargetWe continue using the same feature set and target defined earlier. Nothing is reloaded and nothing is redefined.X = X_normalized_dfy = df["target"]At this stage:X represents normalized numerical featuresy represents the classification targetBoth are already validated and alignedStep 11.2: Performing the Train–Test SplitWe now split the dataset into training and testing subsets. The test set represents unseen data and must remain untouched until evaluation.from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)Key points about this split:test_size=0.2 reserves 20% of data for evaluationrandom_state=42 ensures reproducibilitystratify=y preserves class distribution, which is essential for classification problemsStratification is particularly important in real-world datasets where class imbalance is common. Without it, evaluation metrics can become misleading.What This Split GuaranteesAt this point, we have enforced several important constraints:The model will only learn from X_train and y_trainEvaluation will be performed only on X_test and y_testNo diagnostic or preprocessing logic will peek into the test setPerformance metrics will reflect generalization, not memorizationThese guarantees are more important than the choice of algorithm that follows.Why This Matters in Production SystemsIn production, models rarely fail because they are mathematically incorrect. They fail because evaluation was optimistic, assumptions were violated, or leakage went unnoticed.A clean train–test split is the first safeguard against these failures. It establishes trust in every metric computed afterward and provides a stable foundation for comparing models as the system evolves.Transition to the Next StepWith the learning and evaluation boundary clearly defined, we can now introduce models in a controlled and interpretable way.Step 12: Baseline Models — Establishing Reference PerformanceOnce the train–test boundary has been defined, the next step is not to search for the most powerful algorithm. It is to establish baselines.Baseline models serve a specific purpose in production-grade data science. They answer a simple but critical question:What level of performance can we achieve with the simplest, most interpretable assumptions?Without baselines, improvements cannot be measured meaningfully. More complex models may appear to perform well, but without a reference point, it is impossible to know whether that performance is real or accidental.In structured, tabular data problems, linear models are often the most informative place to start.Why Baseline Models MatterBaseline models provide several important guarantees:They are fast to train and evaluateTheir behavior is easy to interpretTheir limitations are well understoodThey expose data issues earlyThey create a stable benchmark for comparisonIf a sophisticated model cannot significantly outperform a well-chosen baseline, the additional complexity is rarely justified.Step 12.1: Logistic Regression as a Baseline ClassifierBecause this is a binary classification problem, Logistic Regression is a natural starting point. Despite its simplicity, it performs surprisingly well on many real-world datasets and provides clear signals about feature relevance.We will use scikit-learn’s implementation with default settings, keeping the model intentionally simple.from sklearn.linear_model import LogisticRegressionlog_reg = LogisticRegression( max_iter=1000, random_state=42)log_reg.fit(X_train, y_train)At this stage:The model is trained only on training dataNo hyperparameter tuning is performedThe goal is reference performance, not optimizationStep 12.2: Evaluating the Baseline ModelEvaluation must be performed strictly on the test set. Any evaluation on training data would overstate performance and undermine the purpose of the baseline.from sklearn.metrics import accuracy_scorey_pred = log_reg.predict(X_test)accuracy = accuracy_score(y_test, y_pred)accuracyAccuracy provides a quick sanity check, but it should never be the only metric considered. It answers how often predictions are correct, not how or why they fail.Step 12.3: Confusion Matrix for Error StructureTo understand model behavior more deeply, we examine the confusion matrix. This reveals the types of errors the model makes and whether those errors are symmetric.from sklearn.metrics import confusion_matrixconf_matrix = confusion_matrix(y_test, y_pred)conf_matrixThis matrix highlights:False positives vs false negativesWhether one class is systematically harder to predictPotential business implications of misclassificationThese patterns often matter more than raw accuracy.Step 12.4: Classification Report for Detailed MetricsFinally, we examine precision, recall, and F1-score to understand performance per class.from sklearn.metrics import classification_reportprint(classification_report(y_test, y_pred))This report provides a more complete picture of model behavior and often exposes trade-offs hidden by aggregate metrics.What This Baseline Tells UsAt this point, we have established a clear reference point:Performance achieved with minimal assumptionsError patterns that reflect data structureA model that is easy to interpret and debugThis baseline becomes the yardstick against which all future models will be measured.Why This Step Is Critical in ProductionIn production systems, baseline models are often retained even after more advanced models are deployed. They serve as:Fallback optionsSanity checks during retrainingReference points during model drift analysisSkipping baselines removes this safety net.Transition to the Next StepWith a baseline model in place, we can now focus on structure rather than algorithms.In the next step, we will introduce scikit-learn pipelines to formalize preprocessing and modeling as a single, reproducible unit.Step 13: Modeling Pipelines — Structuring Training and EvaluationOnce a baseline model is established, the next priority is not improving performance. It is improving structure.In exploratory work, it is common to see preprocessing steps applied manually before model training. In production systems, this approach quickly becomes fragile. Transformations drift, evaluation becomes inconsistent, and retraining pipelines break in subtle ways.Modeling pipelines exist to prevent this.A pipeline enforces a single, repeatable path from raw input to prediction. Every transformation applied during training is guaranteed to be applied in the same way during evaluation and inference. This consistency is what turns a model into a system component rather than a one-off experiment.Why Pipelines Matter More Than AlgorithmsIn real deployments, models fail far more often due to process issues than algorithmic limitations.Pipelines address several recurring problems:Inconsistent preprocessing between training and inferenceAccidental leakage from test dataDifficulty reproducing resultsFragile retraining workflowsOnce pipelines are in place, models become easier to reason about, easier to validate, and easier to operate over time.Step 13.1: Introducing the scikit-learn Pipelinescikit-learn provides a native Pipeline abstraction that allows preprocessing and modeling steps to be chained together into a single object.Even when preprocessing is minimal, using a pipeline early establishes good discipline.from sklearn.pipeline import Pipelinefrom sklearn.linear_model import LogisticRegressionStep 13.2: Defining a Simple Modeling PipelineIn our case, the data is already numerically normalized. That does not eliminate the need for a pipeline. It simply means the pipeline is currently lightweight.pipeline = Pipeline( steps=[ ("model", LogisticRegression( max_iter=1000, random_state=42 )) ])This pipeline explicitly defines:A single modeling stepAll model configuration in one placeA reusable object that encapsulates training logicAs the system evolves, additional steps can be added without changing downstream code.Step 13.3: Training the PipelineTraining the pipeline looks identical to training a model, but the semantics are different. The pipeline now owns the full transformation and modeling process.pipeline.fit(X_train, y_train)This single call ensures that:All steps are fit only on training dataNo accidental leakage occursThe training process is reproducibleStep 13.4: Evaluating the PipelineEvaluation also remains unchanged at the surface level, which is a key advantage of pipelines.y_pred_pipeline = pipeline.predict(X_test)from sklearn.metrics import accuracy_scoreaccuracy_score(y_test, y_pred_pipeline)Because the pipeline encapsulates all logic, the same object can later be used for inference without modification.Step 13.5: Why Pipelines Scale WellAs systems grow, pipelines become even more valuable. They support:Adding preprocessing steps safelySwapping models without refactoring codeCross-validation without leakageConsistent retraining and deploymentIn regulated or long-lived systems, pipelines are often a requirement rather than a convenience.Pipelines as System BoundariesA useful way to think about pipelines is as contract boundaries. Everything inside the pipeline is part of the learning system. Everything outside is orchestration.This separation simplifies:AuditingDebuggingMonitoringChange managementIt also makes the system more resilient to future changes.Transition to the Next StepWith pipelines in place, we can now evaluate models more rigorously and compare alternatives without changing process.In the next step, we will focus on model evaluation beyond accuracy, examining metrics that reveal error structure and business impact.Step 14: Model Evaluation — Metrics That Actually MatterOnce a model has been trained through a clean pipeline, the next question is not whether it achieves a high score, but what that score actually means.In many projects, evaluation stops at a single metric, often accuracy. In production systems, this is rarely sufficient. A model can achieve high accuracy while still making costly or unacceptable errors. Evaluation must therefore expose error structure, not just aggregate performance.This step focuses on understanding how the model fails, not just how often it succeeds.Why Accuracy Alone Is Not EnoughAccuracy answers one question: What fraction of predictions were correct?It does not answer:Which class is harder to predictWhether false positives or false negatives dominateHow performance varies across decision thresholdsWhether errors align with business riskIn regulated or high-impact systems, these distinctions matter more than raw accuracy.Step 14.1: Reusing Pipeline PredictionsWe continue evaluating the pipeline model introduced in Step 13. No new models are trained and no parameters are changed.y_pred = pipeline.predict(X_test)This ensures that evaluation reflects the exact system that would be deployed.Step 14.2: Confusion Matrix — Understanding Error TypesThe confusion matrix is one of the most important diagnostic tools in classification. It shows how predictions are distributed across true classes.from sklearn.metrics import confusion_matrixconf_matrix = confusion_matrix(y_test, y_pred)conf_matrixThis matrix reveals:How often the model confuses one class for anotherWhether errors are balanced or skewedWhich mistakes are most commonIn real systems, these patterns often map directly to business outcomes.Step 14.3: Precision, Recall, and F1-ScoreTo go beyond raw counts, we examine class-level performance using precision, recall, and F1-score.from sklearn.metrics import classification_reportprint(classification_report(y_test, y_pred))These metrics provide deeper insight:Precision measures how reliable positive predictions areRecall measures how well the model captures actual positivesF1-score balances the twoDifferent applications prioritize these metrics differently. Understanding the trade-offs is more important than optimizing any single value.Step 14.4: Probability Scores and Decision ThresholdsMany models, including logistic regression, produce probability estimates rather than hard class labels. These probabilities allow decision thresholds to be adjusted based on risk tolerance.y_proba = pipeline.predict_proba(X_test)[:, 1]Working with probabilities enables:Threshold tuningRisk-based decisioningBetter alignment with business constraintsThis is especially important when the cost of different error types is asymmetric.Step 14.5: ROC Curve and AUCThe ROC curve visualizes the trade-off between true positive rate and false positive rate across thresholds.from sklearn.metrics import roc_curve, roc_auc_scorefpr, tpr, thresholds = roc_curve(y_test, y_proba)roc_auc = roc_auc_score(y_test, y_proba)roc_aucAUC provides a threshold-independent measure of separability. While it should not be used in isolation, it is useful for comparing models under consistent conditions.Interpreting Evaluation Results in ContextEvaluation metrics do not exist in a vacuum. Their meaning depends on:Data distributionClass imbalanceBusiness riskRegulatory constraintsA model that is statistically strong but operationally risky is not production-ready. Evaluation is where these tensions surface.Why This Step Matters in ProductionIn production systems:Metrics guide deployment decisionsMetrics define alert thresholdsMetrics drive retraining schedulesMetrics support audits and reviewsPoor evaluation leads to fragile systems, regardless of model sophistication.Transition to the Next StepAt this point, we have:A validated datasetA reproducible pipelineA baseline modelA meaningful evaluation frameworkIn the next step, we will bring these elements together and discuss model selection, comparison, and readiness for more advanced approaches, setting the stage for Part 4.Step 15: Model Comparison and Readiness — Knowing When to Move ForwardBy this point, we have done everything that classical machine learning requires to be credible.We did not rush into complex algorithms. We built a clean data foundation, validated assumptions, enforced strict training boundaries, established baselines, structured the workflow with pipelines, and evaluated models using metrics that expose real behavior.Now comes a decision that many projects get wrong: whether to move forward, and how.Model comparison is not about picking the highest score. It is about deciding whether additional complexity is justified, safe, and aligned with system constraints.What We Are Comparing AgainstOur baseline model provides a reference point with several important properties:It is interpretableIt is stableIt is fast to train and retrainIts failure modes are easy to understandIts performance is measurable and reproducibleAny model that follows must justify itself relative to this baseline, not in isolation.When a Baseline Is “Good Enough”In many real-world systems, baseline models remain in production for years. This is not a failure of ambition. It is a reflection of trade-offs.A baseline may be sufficient when:Performance meets business requirementsErrors are well understood and acceptableLatency and throughput constraints are tightExplainability is mandatoryRetraining and monitoring need to be simpleIn these cases, complexity adds risk without meaningful upside.When It Makes Sense to Go FurtherMore advanced models become relevant when:Baseline performance is clearly insufficientError patterns indicate nonlinear structureFeature interactions matterBusiness impact justifies additional complexityMonitoring and governance capabilities are in placeThis decision should be driven by evidence, not by algorithm popularity.Readiness Checklist Before Moving OnBefore introducing more sophisticated models, the system should satisfy the following:A stable baseline existsEvaluation metrics are trustedError behavior is understoodPipelines are in placeRetraining is reproducibleMonitoring requirements are clearIf any of these are missing, adding complexity will amplify existing weaknesses.Why This Step Matters More Than Any AlgorithmMany production failures happen not because models are weak, but because teams move forward prematurely. They add complexity before establishing control.This step enforces restraint.It ensures that progress is deliberate and reversible, not reactive.Closing Thoughts for Part 3Classical machine learning is not outdated. It remains the backbone of most production systems built on structured, tabular data. What determines success is not the algorithm itself, but the process around it: disciplined data handling, careful evaluation, and awareness of real operational constraints.By the end of this part, we have not simply trained models. We have established a modeling approach that is stable, interpretable, and designed to evolve safely as systems grow in complexity. This foundation is what allows teams to move forward with confidence rather than chasing incremental gains without control.If this way of thinking reflects how you approach data science in real systems, consider clapping to signal that this perspective was useful, leaving a comment to share how you handle baselines and evaluation in your own work, or following the series to continue from classical modeling into more advanced production techniques. Sharing the article with others working on tabular ML systems also helps extend the discussion beyond a single post. Thanks !!!Transition to Part 4With a solid classical modeling foundation in place, we are now ready to explore gradient boosting in production.In Part 4, we will examine why models such as XGBoost, LightGBM, and CatBoost dominate tabular machine learning, and how they are tuned, evaluated, and governed in real-world systems where performance, explainability, and stability all matter.Essential Python Libraries for Data Science was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.