Mastering the Data Science Workflow with Python: From EDA to ML

Advertisements

Python has become one of the most important programming languages in data science, not simply because it offers powerful libraries, but because it supports an entire analytical workflow within a single environment. A data scientist can import raw data, investigate its structure, identify inconsistencies, uncover meaningful patterns, build predictive models, and communicate the results without constantly switching between different tools. Yet knowing how to use pandas, NumPy, Matplotlib, or Scikit-learn does not automatically translate into effective data science. The real skill lies in understanding when to use each tool, why a particular analytical decision matters, and how to move from one stage to the next without compromising the reliability of the results.

Imagine that you have been given a dataset containing customer transactions for an online store. The business wants to know which customers are likely to stop purchasing, which products generate the most revenue, and whether historical behavior can help predict future sales. You could immediately train a machine learning model, but doing so before examining the data might lead to misleading predictions, hidden data leakage, or conclusions based on incorrect assumptions. A stronger approach begins with exploratory data analysis, proceeds through careful data preparation and feature engineering, and only then moves toward model development and evaluation.

This article presents a practical checklist for following that workflow in Python. Rather than treating data science as a series of disconnected coding exercises, we will examine how each stage contributes to the final result, which libraries are most useful, and what you should verify before moving forward. Whether you are building your first machine learning project or refining an existing analytical process, the objective is the same: produce results that are technically sound, reproducible, and useful in practice.

A reliable data science project begins with a properly configured environment. Although it is tempting to install every popular library into a single Python installation, separating project dependencies makes experiments easier to reproduce and reduces conflicts between packages. For most traditional data science workflows, a virtual environment, Jupyter Notebook, and a small collection of well-established libraries provide everything needed to get started.

Pandas handles tabular data, NumPy supports numerical computation, Matplotlib and Seaborn provide visualization tools, and Scikit-learn supplies preprocessing methods, machine learning algorithms, and evaluation utilities. Depending on the project, you may also need SciPy for scientific computing, Statsmodels for statistical modeling, or XGBoost for gradient-boosted decision trees.

A basic environment can be created with the following commands:

python -m venv .venv

Activate the environment using the command appropriate for your operating system, then install the core libraries:

python -m pip install numpy pandas matplotlib seaborn scikit-learn jupyter

Once the environment is ready, organize the project so that raw data, processed data, notebooks, reusable source code, and results have distinct locations. This separation may seem unnecessary when working with a small CSV file, but it becomes valuable as the project grows and several analytical stages need to be repeated.

Practical checklist: Confirm that the environment works, record package dependencies, organize project files, and ensure that the dataset can be accessed from the intended working directory. For reproducibility, save the environment’s dependencies in a requirements file or use a suitable environment-management tool.

Exploratory data analysis, commonly abbreviated as EDA, is the process of investigating a dataset to understand its structure, quality, distributions, relationships, and potential analytical limitations. It is not merely the creation of charts. Proper EDA helps determine whether the available data can answer the original question and reveals problems that must be addressed before modeling.

The first step is to load the data and inspect a few rows.

import pandas as pd
import numpy as np
df = pd.read_csv("customer_data.csv")
print(df.head())
print(df.shape)
print(df.columns.tolist())
print(df.info())

These commands provide a useful initial picture. The first few rows reveal the general structure of the records, shape reports the number of rows and columns, and info() summarizes column names, data types, and non-null counts.

However, the initial inspection should go beyond simply confirming that the file loaded successfully. Column names may contain inconsistent capitalization, dates may have been interpreted as strings, and numerical fields may contain unexpected text values. A column representing customer age, for example, might contain numbers alongside entries such as “unknown”, while a transaction date could be stored in a format that prevents chronological analysis.

Descriptive statistics provide another useful perspective.

print(df.describe(include="all").T)

For numerical variables, this reveals statistics such as the mean, standard deviation, minimum, maximum, and quartiles. For categorical variables, it provides information about the number of unique values and the most frequent category.

The critical question at this stage is not whether the dataset looks complicated. It is whether you understand what each column represents, how the observations were collected, and what limitations the data may have. A machine learning model cannot compensate for a poorly defined business problem or a variable whose meaning is misunderstood.

Practical checklist: Inspect the dimensions, column names, data types, descriptive statistics, and sample records. Verify the meaning of important variables, identify the target you intend to predict, and investigate whether the dataset represents the population or process you want to study.

Real-world datasets are rarely as clean as examples in programming tutorials. Missing values, duplicate records, inconsistent category labels, impossible measurements, and incorrectly formatted fields are common. These issues can distort statistical summaries and reduce model reliability if they are not identified early.

Start by measuring the extent of missingness in each column.

missing = (
df.isna()
.sum()
.to_frame("missing_count")
)
missing["missing_percentage"] = (
df.isna().mean() * 100
)
print(missing.sort_values(
"missing_percentage",
ascending=False
))

This analysis helps distinguish isolated missing values from columns that are largely incomplete. Nevertheless, the percentage alone does not determine the correct treatment. Missing customer income, for example, might reflect customers choosing not to disclose financial information, whereas a missing transaction amount might indicate a recording failure. The reason for the missingness can influence both the cleaning strategy and the interpretation of the results.

Duplicate records require similar attention. You can identify exact duplicate rows using df.duplicated(), but removing them indiscriminately is not always appropriate. In a transaction dataset, two identical purchases might represent legitimate separate transactions. The correct decision depends on the meaning of a record and the rules governing the data collection process.

print("Duplicate rows:", df.duplicated().sum())

Data validation should also cover impossible or suspicious values. Negative quantities, dates in the future, customer ages outside the plausible range, and inconsistent currency units deserve investigation. Outliers require particular care: an unusually large transaction may be a genuine high-value purchase rather than an error. Removing such observations simply because they appear extreme can erase precisely the behavior the business needs to understand.

Practical checklist: Quantify missing values, inspect duplicate records, standardize inconsistent labels, validate numerical ranges, verify date formats, and investigate unusual observations. Document every consequential cleaning decision so that another analyst can understand why it was made.

Once the basic quality checks are complete, visualization helps reveal patterns that are difficult to recognize from summary statistics alone. Histograms show the distribution of numerical variables, box plots help investigate spread and potential outliers, and scatter plots can reveal relationships between pairs of variables. Bar charts are particularly useful for comparing categories, while correlation matrices summarize certain forms of association between numerical features. Consider a dataset containing customer ages and purchase amounts. The mean purchase amount might appear reasonable, but a histogram could reveal a highly right-skewed distribution in which most customers spend relatively little while a small number make very large purchases. That discovery could influence the choice of summary statistics, the treatment of extreme values, and the evaluation metric used in a predictive model.

import matplotlib.pyplot as plt
import seaborn as sns
sns.histplot(
data=df,
x="purchase_amount",
kde=True
)
plt.title("Distribution of Purchase Amounts")
plt.xlabel("Purchase Amount")
plt.ylabel("Number of Customers")
plt.tight_layout()
plt.show()

To investigate relationships between numerical variables, a correlation matrix can provide a useful starting point.

numeric_df = df.select_dtypes(
include="number"
)
correlation = numeric_df.corr()
sns.heatmap(
correlation,
annot=True,
cmap="coolwarm",
fmt=".2f"
)
plt.title("Correlation Between Numerical Features")
plt.tight_layout()
plt.show()

Correlation must be interpreted carefully. A strong correlation does not establish causation, and a weak linear correlation does not rule out a nonlinear relationship. Furthermore, correlated features can be useful for prediction even when their relationship does not explain an underlying causal mechanism.

During EDA, it is also worth examining how variables behave across meaningful groups. Comparing average spending by customer segment, for example, may reveal differences that disappear when all customers are analyzed together. Where relevant, inspect relationships with the target variable, while remembering that target-driven exploration can introduce selection bias if it influences decisions repeatedly without a proper validation strategy.

Practical checklist: Examine numerical distributions, categorical frequencies, relationships between important variables, group-level differences, and potential outliers. Use charts to investigate specific questions rather than generating visualizations without a clear analytical purpose.

Data preparation is the stage where exploratory findings become concrete decisions. The objective is not to make every dataset perfectly uniform, but to transform the available information into a form suitable for the intended analysis while preserving meaningful information.

Missing numerical values may be imputed using the median or mean, while categorical variables may require a dedicated missing-value category or the most frequent value. The appropriate method depends on the variable’s meaning, the amount of missingness, and the assumptions that can reasonably be made. In some cases, retaining a missingness indicator is helpful because the absence of a value may itself carry information.

Categorical features often need to be encoded before they can be used by conventional machine learning estimators. One-hot encoding is appropriate for many nominal categories, such as product type or country, because it avoids imposing an artificial numerical order. Ordinal encoding can be more suitable when categories genuinely follow a meaningful ranking, such as low, medium, and high.

Numerical scaling is another important consideration. Algorithms such as logistic regression with regularization, support vector machines, and k-nearest neighbors can be sensitive to differences in feature scales. Decision trees and many tree-based ensembles generally require less attention to scaling because their splits are based on feature thresholds rather than distances between scaled measurements.

The most important principle is to avoid allowing information from the evaluation data to influence the preparation process. Imputation values, scaling parameters, feature selection decisions, and other learned transformations should be fitted using training data only. This is one reason Scikit-learn pipelines are so valuable: they help keep preprocessing and model fitting within a consistent workflow.

Practical checklist: Choose suitable imputation methods, encode categorical variables, scale numerical features when needed, standardize inconsistent representations, and retain meaningful information. Make sure every transformation is justified by the data and the modeling objective.

A model can perform impressively on data it has already encountered while failing to generalize to new observations. To measure generalization, the available data must be separated into training and evaluation sets in a way that reflects how the model will be used.

For many independent observations, a common starting point is an 80/20 training-test split. Classification problems with imbalanced target classes may benefit from stratification, which helps preserve the class proportions across the splits.

from sklearn.model_selection import train_test_split
X = df.drop(columns=["target"])
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)

Here, “target” must be replaced with the actual target column, and stratification is appropriate when the task involves classification with suitable class labels. For regression, remove the stratify=y argument unless you have deliberately constructed an appropriate stratification strategy.

The test set should be reserved for final evaluation rather than repeatedly consulted during model development. When many model choices are compared against the same test set, decisions gradually become tailored to that particular sample, making the final score less independent than it appears. Cross-validation on the training data provides a stronger basis for comparing alternatives.

Some datasets require different splitting strategies altogether. Time-series observations should generally be separated chronologically so that future information does not leak into training. Data involving repeated measurements from the same patient, customer, or device may require group-based splitting to prevent related records from appearing in both training and evaluation sets. The right strategy follows from the data-generating process, not simply from a standard percentage.

Practical checklist: Define the prediction target, separate features from labels, choose an appropriate splitting strategy, preserve a genuinely untouched test set, and check for leakage from duplicated entities, future observations, or target-derived features.

Advertisements

It is tempting to begin with a complex model because advanced algorithms often attract more attention. In practice, a simple baseline is usually the better starting point. It provides a reference against which more sophisticated models can be judged and can reveal whether the dataset contains enough predictive information to justify additional complexity.

For a classification problem, a dummy classifier can establish a basic reference score, while logistic regression provides a meaningful first model when its assumptions and limitations are reasonable. For regression, predicting the training-set mean or median establishes a baseline, while linear regression can reveal whether simple relationships already explain a useful proportion of the variation.

Consider a business trying to predict whether customers will cancel a subscription. A model that always predicts the majority class might achieve 90% accuracy if only 10% of customers cancel. Despite the seemingly strong score, it would fail to identify any customers at risk. This illustrates why the baseline must be interpreted alongside the business objective and appropriate evaluation metrics.

A simple model also provides an opportunity to validate the entire workflow before adding complexity. If data splitting, preprocessing, evaluation, and result interpretation are not yet reliable, a more advanced algorithm will make the project harder to diagnose rather than automatically improving it.

Practical checklist: Establish a simple reference, train an interpretable baseline, evaluate it with a metric suited to the problem, and record the result. Only introduce greater complexity when there is a clear reason to expect meaningful improvement.

Scikit-learn is particularly useful because it provides a consistent interface for preprocessing, model training, cross-validation, and evaluation. Its Pipeline and ColumnTransformer classes make it possible to combine transformations for different feature types with a final estimator, reducing the risk of inconsistent processing between training and prediction.

The following example demonstrates a practical classification workflow for a dataset containing numerical and categorical features. It assumes that the target is binary and that the feature columns have been correctly identified.

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
numeric_features = X_train.select_dtypes(
include="number"
).columns
categorical_features = X_train.select_dtypes(
exclude="number"
).columns
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipeline = Pipeline([
(
"imputer",
SimpleImputer(strategy="most_frequent")
),
(
"encoder",
OneHotEncoder(handle_unknown="ignore")
)
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, numeric_features),
(
"categorical",
categorical_pipeline,
categorical_features
)
])
model = Pipeline([
("preprocessing", preprocessor),
("classifier", LogisticRegression(max_iter=1000))
])
scores = cross_val_score(
model,
X_train,
y_train,
cv=5,
scoring="f1"
)
print("Mean cross-validation F1:", scores.mean())
model.fit(X_train, y_train)

The pipeline imputes missing numerical values, scales numerical features, imputes missing categorical values, and one-hot encodes categorical variables before training logistic regression. Because these transformations are fitted within the pipeline, cross-validation can refit them separately on each training fold rather than allowing validation-fold information to influence preprocessing.

The example uses F1 as its cross-validation metric, which can be useful when balancing precision and recall is important. However, it is not universally appropriate. If false positives and false negatives have very different costs, the evaluation metric should reflect those consequences. Likewise, binary classification assumptions should be checked before applying this exact workflow to multiclass, multilabel, or regression problems.

Once the baseline is established, other algorithms can be compared using the same data splits and evaluation framework. Depending on the problem, reasonable candidates might include random forests, gradient-boosted trees, support vector machines, or alternative linear models. The objective is not to collect the largest possible number of algorithms, but to identify the model that best satisfies the task’s predictive, operational, and interpretability requirements.

Practical checklist: Build preprocessing and modeling into a pipeline, use cross-validation for model comparison, fit the chosen pipeline on the training data, and keep the test set separate until the final evaluation.

A machine learning score is useful only when its meaning is understood. The correct evaluation method depends on whether the model performs classification, regression, ranking, forecasting, or another task. Even within a single task, different metrics can lead to different conclusions about which model is preferable.

For binary classification, accuracy measures the proportion of correct predictions, precision measures how many predicted positives are actually positive, and recall measures how many actual positives the model successfully identifies. The F1 score combines precision and recall through their harmonic mean. ROC-AUC assesses ranking performance across classification thresholds, while precision-recall analysis can be particularly informative when the positive class is rare.

For regression, mean absolute error (MAE) measures the average absolute prediction error, while root mean squared error (RMSE) penalizes large errors more strongly. The coefficient of determination, \(R^2\), provides another perspective on predictive performance, although it should not be interpreted as a universal measure of model quality.

After fitting the classification pipeline, you can calculate several common metrics using the held-out test set.

from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
classification_report,
confusion_matrix
)
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(
y_test, y_pred, zero_division=0
))
print("Recall:", recall_score(
y_test, y_pred, zero_division=0
))
print("F1:", f1_score(
y_test, y_pred, zero_division=0
))
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))

This example assumes binary classification with a conventional positive class. If the task is multiclass, you should choose an appropriate averaging strategy for precision, recall, and F1, and ensure that the confusion matrix and report reflect the actual class structure.

Evaluation should also examine the consequences of mistakes. In fraud detection, missing a fraudulent transaction may be more costly than investigating a legitimate one. In medical screening, overlooking a genuine case can have serious consequences. In customer retention, a model may need to identify a useful number of at-risk customers within a limited intervention budget. These situations demand more than a single headline metric.

Practical checklist: Select metrics before comparing models, inspect class-specific performance, analyze confusion matrices or residuals, investigate important failure cases, and evaluate whether the results satisfy the real operational objective.

Once the baseline has been evaluated, model improvement should be guided by evidence rather than trial and error. Underfitting occurs when a model is too limited to capture meaningful structure in the data, while overfitting occurs when it learns patterns that do not generalize reliably to unseen observations. Both can produce disappointing results, but they require different responses.

Cross-validation provides a more stable basis for comparing candidate models and hyperparameters. Scikit-learn offers GridSearchCV for evaluating specified combinations and RandomizedSearchCV for sampling a subset of possible configurations. The latter can be more practical when the search space is large.

For example, a random forest might be evaluated across different numbers of trees, maximum depths, and minimum leaf sizes. These settings influence model complexity and can affect the balance between predictive performance, computational cost, and generalization.

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
forest_pipeline = Pipeline([
("preprocessing", preprocessor),
("classifier", RandomForestClassifier(
random_state=42
))
])
param_distributions = {
"classifier__n_estimators": [100, 200, 400],
"classifier__max_depth": [None, 5, 10, 20],
"classifier__min_samples_leaf": [1, 2, 5, 10]
}
search = RandomizedSearchCV(
forest_pipeline,
param_distributions=param_distributions,
n_iter=12,
cv=5,
scoring="f1",
random_state=42,
n_jobs=-1
)
search.fit(X_train, y_train)
print("Best parameters:", search.best_params_)
print("Best CV F1:", search.best_score_)

This search uses the same preprocessing strategy as the logistic regression example. The double-underscore parameter syntax allows Scikit-learn to access the classifier’s settings through the pipeline. Once the search finishes, search.best_estimator_ contains the best pipeline found under the specified search configuration.

Feature engineering can also improve performance, particularly when the raw columns do not express the structure of the problem clearly. Transaction frequency, average order value, customer tenure, and time since the previous purchase may be more informative than isolated transaction records. Yet engineered features must be calculated using only information available at prediction time. For instance, a customer retention model must not use future transactions to construct historical purchasing features.

A final caution concerns repeated experimentation. If you repeatedly inspect the test score and modify the model in response, the test set gradually becomes part of the development process. Cross-validation and a disciplined separation between training, validation, and final testing help preserve the credibility of the evaluation.

Practical checklist: Use cross-validation to compare models, tune hyperparameters systematically, investigate feature engineering opportunities, check for overfitting, and avoid using the final test set as a repeated optimization target.

A model that produces accurate predictions is not necessarily a useful analytical product. Stakeholders need to understand what the predictions mean, where the model performs well, and which limitations should influence decisions. Interpretation is especially important when predictions affect customers, employees, financial outcomes, or other consequential processes.

For a linear model, coefficients can help explain how changes in features relate to predictions, subject to the model’s assumptions and preprocessing choices. For tree-based models, feature importance can provide a useful initial summary of which variables contribute to predictive performance. However, importance measures should not automatically be interpreted as evidence of causality, and correlated features can make individual importance scores difficult to interpret.

Tools such as permutation importance and SHAP can offer additional perspectives on model behavior. Permutation importance measures how model performance changes when a feature’s values are disrupted, while SHAP estimates feature contributions to individual predictions under a defined attribution framework. Each method has assumptions and limitations, so the interpretation should remain connected to the model, the dataset, and the question being asked.

Communication also requires distinguishing predictive association from causal explanation. If customers with shorter account histories are more likely to cancel, that does not establish that account age itself causes cancellation. Other variables may explain the relationship, and determining causal effects requires a suitable research design rather than predictive accuracy alone.

Practical checklist: Explain the model’s purpose, report its performance and limitations, examine important features and representative errors, distinguish association from causation, and present results in language appropriate for the intended audience.

The final stage is often overlooked in introductory projects. A notebook that runs successfully once is not necessarily a reproducible analytical workflow, and a model that performs well during evaluation is not automatically ready for production. Reliable work requires the ability to reproduce results, apply the same transformations to new data, and detect changes in performance after deployment.

A useful project should preserve the data preparation logic, the selected model, the evaluation results, and the environment needed to reproduce the analysis. Reusable functions and modular scripts can reduce duplicated code, while version control helps track changes to the project. For larger datasets, data versioning and experiment-tracking tools can provide additional structure.

Once a model has been evaluated, a fitted Scikit-learn pipeline can be saved and later loaded for prediction. One common approach is to use joblib.

import joblib
joblib.dump(model, "customer_model.joblib")
loaded_model = joblib.load("customer_model.joblib")
predictions = loaded_model.predict(new_data)

Here, new_data must contain the same expected feature columns and compatible data types as the original input. The pipeline retains the fitted preprocessing steps alongside the classifier, so new observations pass through the same transformations used during training.

Model persistence introduces security considerations. Files saved with joblib or Python’s pickle-based serialization mechanisms can execute arbitrary code when loaded, so only load artifacts from trusted sources. In addition, the saved model should be associated with appropriate dependency versions and documentation, because incompatible software changes can affect reproducibility.

Deployment also creates new responsibilities. Incoming data may change in distribution, missing-value rates may increase, and relationships between features and outcomes may weaken over time. Monitoring input quality, prediction distributions, and—when ground-truth outcomes become available—actual model performance helps identify when investigation or retraining is needed. For high-impact applications, governance, privacy, fairness, access control, and human oversight may be essential parts of the workflow.

Practical checklist: Save the complete fitted pipeline, document dependencies, preserve evaluation results, validate new input data, protect serialized model files, and define a plan for monitoring performance after deployment.

The difference between writing Python code and practicing data science lies in the quality of the decisions made along the way. A successful workflow begins by understanding the data, continues through disciplined exploration and preparation, and reaches machine learning only after the analytical foundations are sufficiently reliable. Each stage reduces a different category of risk, from misleading summaries and data leakage to inappropriate evaluation metrics and models that fail outside the training environment.

Python makes this process accessible because its ecosystem connects nearly every stage of the work. Pandas and NumPy support data manipulation, visualization libraries help reveal patterns, and Scikit-learn provides a structured way to prepare features, train models, and evaluate their performance. Nevertheless, libraries remain tools rather than substitutes for statistical reasoning. The strongest results emerge when the analyst understands the assumptions behind each method and is willing to question a promising result rather than accept it at face value. If you are developing your data science skills, consider applying this checklist to a dataset you have never examined before. Work through each stage, record the decisions you make, and compare your first baseline with the final model. Which stage do you find most challenging: exploratory data analysis, data cleaning, feature engineering, or model evaluation?

Share your experience in the comments, because the practical difficulties encountered during real projects often teach more than a perfectly prepared tutorial.

Advertisements

(ML) إلى تعلم الآلة (EDA) إتقان سير عمل علم البيانات باستخدام لغة بايثون: من الاستكشاف الأولي للبيانات

Advertisements

أصبحت لغة بايثون واحدة من أهم لغات البرمجة في مجال علم البيانات ليس فقط لأنها توفر مكتبات قوية بل لأنها تدعم سير عمل تحليلياً متكاملاً ضمن بيئة واحدة، إذ يمكن لعالم البيانات استيراد البيانات الخام وفحص بنيتها وتحديد التناقضات والكشف عن أنماط ذات دلالة وبناء نماذج تنبؤية وعرض النتائج كل ذلك دون الحاجة إلى التنقل المستمر بين أدوات مختلفة، ومع ذلك فإن مجرد معرفة كيفية استخدام مكتبات

pandas أو NumPy أو Matplotlib أو Scikit-learn مثل

لا يعني بالضرورة القدرة على ممارسة علم البيانات بفعالية، إذ تكمن المهارة الحقيقية في فهم متى يجب استخدام كل أداة ولماذا يعد اتخاذ قرار تحليلي معين أمراً مهماً وكيفية الانتقال من مرحلة إلى أخرى دون المساس بموثوقية النتائج

تخيل أن لديك مجموعة بيانات تحتوي على معاملات العملاء في متجر إلكتروني وترغب الشركة في معرفة العملاء المحتمل توقفهم عن الشراء والمنتجات التي تحقق أكبر قدر من الإيرادات وما إذا كان السلوك السابق للعملاء يمكن أن يساعد في التنبؤ بالمبيعات المستقبلية، قد تبادر فوراً إلى تدريب نموذج لتعلم الآلة لكن القيام بذلك قبل فحص البيانات قد يؤدي إلى تنبؤات مضللة أو تسريب خفي للبيانات أو استنتاجات مبنية على افتراضات خاطئة، لذا فإن النهج الأفضل يبدأ بالتحليل الاستكشافي للبيانات يليه إعداد دقيق للبيانات وهندسة السمات، ثم ننتقل بعد ذلك إلى تطوير النموذج وتقييمه

يقدم هذا المقال قائمة مرجعية عملية لاتباع سير العمل هذا باستخدام لغة بايثون، وبدلاً من التعامل مع علم البيانات كسلسلة من التمارين البرمجية المنفصلة ​​سنستعرض كيف تساهم كل مرحلة في الوصول إلى النتيجة النهائية وما هي المكتبات الأكثر فائدة وما الذي ينبغي عليك التحقق منه قبل الانتقال إلى الخطوة التالية، وسواء كنت تعمل على بناء مشروعك الأول في تعلم الآلة أو تسعى لتحسين عملية تحليلية قائمة بالفعل فإن الهدف يظل واحداً: تقديم نتائج سليمة تقنياً وقابلة للتكرار وذات قيمة عملية

يبدأ أي مشروع ناجح في مجال علوم البيانات بتهيئة بيئة عمل مناسبة، ورغم أنه قد يكون من المغري تثبيت جميع المكتبات الشائعة في بيئة بايثون واحدة إلا أن فصل تبعيات كل مشروع عن الآخر يجعل إعادة إجراء التجارب أسهل ويقلل من احتمالية حدوث تعارضات بين الحزم البرمجية، فبالنسبة لمعظم مهام علوم البيانات التقليدية

Jupyter Notebook توفر بيئة افتراضية مع برنامج

ومجموعة مختارة من المكتبات الموثوقة كل ما يلزم للبدء

للتعامل مع البيانات الجدولية Pandas تُستخدم مكتبة

العمليات الحسابية الرقمية NumPy وتدعم

أدوات للتصور البياني Matplotlib وSeaborn بينما توفر مكتبتا

أدواتٍ لمعالجة البيانات مسبقاً Scikit-learn وتُقدم

وخوارزميات للتعلم الآلي ووظائف لتقييم النماذج، واعتماداً على طبيعة المشروع

للحوسبة العلمية SciPy قد تحتاج أيضاً إلى مكتبة

للنمذجة الإحصائية Statsmodels أو

لبناء نماذج أشجار القرار XGBoost أو

المعتمدة على تقنية “تعزيز التدرج”

:يمكن إنشاء بيئة عمل أساسية باستخدام الأمر التالي

python -m venv .venv

:قم بتفعيل البيئة باستخدام الأمر المناسب لنظام التشغيل الذي تستخدمه ثم ثبّت المكتبات الأساسية

python -m pip install numpy pandas matplotlib seaborn scikit-learn jupyter

بمجرد تجهيز البيئة نظّم ملفات المشروع بحيث يكون لكل من البيانات الخام والبيانات المعالجة ودفاتر الملاحظات والكود المصدري القابل لإعادة الاستخدام والنتائج أماكن مخصصة ومستقلة، قد يبدو هذا الفصل غير ضروري

صغير CSV عند العمل على ملف

لكنه يصبح بالغ الأهمية مع توسع المشروع والحاجة إلى تكرار مراحل تحليلية متعددة قائمة مراجعة عملية: تأكد من أن بيئة العمل تعمل بشكل صحيح ووثّق تبعيات الحزم البرمجية ونظّم ملفات المشروع وتأكد من إمكانية الوصول إلى مجموعة البيانات من مجلد العمل المخصص، ولضمان إمكانية إعادة إنتاج النتائج احفظ قائمة تبعيات البيئة في ملف خاص

(requirements.txt مثل ملف)

أو استخدم أداة مناسبة لإدارة بيئات العمل

(Exploratory Data Analysis) يُعرف تحليل البيانات الاستكشافي

EDA والذي يُختصر عادةً بـ

بأنه عملية فحص مجموعة بيانات لفهم بنيتها وجودتها وتوزيعاتها والعلاقات بين متغيراتها وأي قيود تحليلية محتملة، ولا يقتصر هذا التحليل على إنشاء الرسوم البيانية فحسب، فإجراء تحليل استكشافي سليم يساعد في تحديد ما إذا كانت البيانات المتاحة قادرة على الإجابة عن السؤال المطروح، كما يكشف عن مشكلات ينبغي معالجتها قبل البدء في بناء النماذج

تتمثل الخطوة الأولى في تحميل البيانات والاطلاع على عدد قليل من صفوفها

import pandas as pd
import numpy as np
df = pd.read_csv("customer_data.csv")
print(df.head())
print(df.shape)
print(df.columns.tolist())
print(df.info())

توفر هذه الأوامر تصوراً أولياً مفيداً، إذ تكشف الأسطر القليلة الأولى عن البنية العامة للسجلات

عدد الصفوف والأعمدة shape بينما يوضح الأمر

ملخصاً لأسماء الأعمدة `info()`ويقدم الأمر

وأنواع البيانات وعدد القيم غير الفارغة ومع ذلك ينبغي ألا يقتصر الفحص الأولي على التأكد من تحميل الملف بنجاح فحسب، فقد تكون أسماء الأعمدة غير متسقة من حيث استخدام الأحرف الكبيرة والصغيرة أو قد تُفسَّر التواريخ كنصوص (سلاسل نصية) أو قد تحتوي الحقول الرقمية على قيم نصية غير متوقعة، فعلى سبيل المثال: قد يضم عمود يمثل “عمر العميل” أرقاماً

(unknown) “إلى جانب مدخلات مثل “غير معروف

بينما قد يكون تاريخ المعاملة مخزناً بتنسيق يحول دون إجراء تحليل زمني

:وتوفر الإحصاءات الوصفية منظوراً مفيداً آخر في هذا السياق

`print(df.describe(include="all").T)`

بالنسبة للمتغيرات الرقمية يكشف هذا الأمر عن إحصاءات مثل المتوسط والانحراف المعياري والقيمتين الصغرى والعظمى، والربيعيات

(categorical variables) أما بالنسبة للمتغيرات الفئوية

فيقدم معلومات حول عدد القيم الفريدة والفئة الأكثر تكراراً

إن السؤال الجوهري في هذه المرحلة ليس ما إذا كانت مجموعة البيانات تبدو معقدة، بل هو: هل تفهم ما يمثله كل عمود وكيف جُمعت الملاحظات وما هي القيود التي قد تتسم بها هذه البيانات؟ فنموذج تعلم الآلة لا يمكنه تعويض سوء صياغة مشكلة العمل أو سوء فهم المعنى الحقيقي لأحد المتغيرات

قائمة مراجعة عملية: افحص أبعاد البيانات وأسماء الأعمدة وأنواع البيانات والإحصاءات الوصفية وعينة من السجلات، تحقق من دلالات المتغيرات المهمة وحدد المتغير المستهدف الذي تنوي التنبؤ به وتأكد مما إذا كانت مجموعة البيانات تمثل فعلياً المجتمع أو العملية التي ترغب في دراستها

نادراً ما تكون مجموعات البيانات الواقعية نظيفة بالقدر الذي تظهر عليه في أمثلة البرامج التعليمية، إذ تكثر فيها القيم المفقودة والسجلات المكررة وتسميات الفئات غير المتسقة والقياسات غير المنطقية والحقول ذات التنسيقات الخاطئة، وإذا لم تُكتشف هذه المشكلات في مرحلة مبكرة فقد تؤدي إلى تشويه الملخصات الإحصائية وتقليل موثوقية النماذج

ابدأ بقياس مدى فقدان البيانات في كل عمود:

missing = (missing = (
df.isna()
.sum()
.to_frame("missing_count")
)
missing["missing_percentage"] = (
df.isna().mean() * 100
)
print(missing.sort_values(
"missing_percentage",
ascending=False
))

يساعد هذا التحليل في التمييز بين القيم المفقودة في حالات فردية وبين الأعمدة التي تعاني من نقص كبير في البيانات، ومع ذلك لا تكفي النسبة المئوية وحدها لتحديد طريقة المعالجة المثلى، ففقدان بيانات “دخل العميل” -على سبيل المثال- قد يعني أن العميل اختار عدم الإفصاح عن معلوماته المالية، بينما قد يشير فقدان “قيمة المعاملة” إلى وجود خلل في عملية التسجيل، لذا فإن فهم سبب فقدان البيانات يؤثر بشكل مباشر على استراتيجية التنظيف وعلى كيفية تفسير النتائج وتتطلب السجلات المكررة اهتماماً مماثلاً، إذ يمكنك تحديد الصفوف المتطابقة تماماً

`df.duplicated()` باستخدام الدالة

لكن حذفها بشكل عشوائي ليس إجراءً صائباً دائماً، ففي مجموعة بيانات المعاملات قد يمثل وجود عمليتين متطابقتين تماماً معاملتين منفصلتين وصحيحتين، يعتمد القرار السليم على طبيعة السجل والقواعد التي تحكم عملية جمع البيانات

print("Duplicate rows:", df.duplicated().sum())

كما ينبغي أن تشمل عملية التحقق من صحة البيانات رصد القيم غير المنطقية أو المشبوهة، مثل الكميات السالبة أو التواريخ المستقبلية أو أعمار العملاء التي تقع خارج النطاق المعقول أو وحدات العملة غير المتسقة

عناية خاصة (Outliers) وتتطلب القيم المتطرفة

فقد تكون المعاملة ذات القيمة الكبيرة جداً عملية شراء حقيقية وذات أهمية وليست مجرد خطأ، لذا فإن حذف مثل هذه البيانات لمجرد أنها تبدو متطرفة قد يؤدي إلى فقدان معلومات جوهرية حول سلوكٍ يحتاج العمل التجاري إلى فهمه

قائمة مراجعة عملية: احسب عدد القيم المفقودة وافحص السجلات المكررة ووحد التسميات غير المتسقة وتحقق من النطاقات الرقمية وتنسيقات التواريخ وراجع أي ملاحظات غير معتادة، احرص على توثيق كل قرار تتخذه بشأن تنظيف البيانات ليتسنى للمحللين الآخرين فهم الأسباب التي دعت لاتخاذ ذلك القرار

بمجرد الانتهاء من فحوصات الجودة الأساسية يساعد التصور البياني في الكشف عن أنماط يصعب ملاحظتها من خلال الإحصاءات التلخيصية وحدها

(Histograms) وتوضح الرسوم البيانية التكرارية

توزيع المتغيرات الرقمية

(Box plots) بينما تساعد المخططات الصندوقية

في دراسة مدى التشتت والقيم المتطرفة المحتملة

(Scatter plots) وتكشف مخططات التشتت

عن العلاقات بين أزواج المتغيرات

(Bar charts) وتُعد المخططات الشريطية

مفيدة بشكل خاص للمقارنة بين الفئات

(Correlation matrices) في حين تلخص مصفوفات الارتباط

أشكالاً معينة من الارتباط بين السمات الرقمية

لنفترض وجود مجموعة بيانات تتضمن أعمار العملاء ومبالغ مشترياتهم، قد يبدو متوسط ​​مبلغ الشراء منطقياً لكن الرسم البياني التكراري قد يكشف عن توزيع ملتوي بشدة نحو اليمين، حيث ينفق معظم العملاء مبالغ صغيرة نسبياً، بينما يقوم عدد قليل منهم بعمليات شراء كبيرة جداً، هذا الاكتشاف قد يؤثر على اختيار الإحصاءات التلخيصية وطريقة التعامل مع القيم المتطرفة ومقياس التقييم المستخدم في النموذج التنبؤي

import matplotlib.pyplot as plt
import seaborn as sns
sns.histplot(
data=df,
x="purchase_amount",
kde=True
)
plt.title("Distribution of Purchase Amounts")
plt.xlabel("Purchase Amount")
plt.ylabel("Number of Customers")
plt.tight_layout()
plt.show()

ولاستكشاف العلاقات بين المتغيرات الرقمية يمكن أن تكون مصفوفة الارتباط نقطة انطلاق مفيدة

numeric_df = df.select_dtypes(
include="number"
)
correlation = numeric_df.corr()
sns.heatmap(
correlation,
annot=True,
cmap="coolwarm",
fmt=".2f"
)
plt.title("Correlation Between Numerical Features")
plt.tight_layout()
plt.show()

يجب تفسير الارتباط بحذر، فالارتباط القوي لا يعني وجود علاقة سببية، كما أن ضعف الارتباط الخطي لا ينفي وجود علاقة غير خطية، علاوة على ذلك يمكن أن تكون السمات المترابطة مفيدة في التنبؤ حتى وإن كانت العلاقة بينها لا تفسر آلية سببية كامنة

(EDA) خلال مرحلة الاستكشاف الأولي للبيانات

يجدر أيضاً فحص سلوك المتغيرات عبر مجموعات ذات دلالة، فمقارنة متوسط ​​الإنفاق حسب فئة العملاء -على سبيل المثال- قد تكشف عن فروق تختفي عند تحليل جميع العملاء كمجموعة واحدة، وعند الاقتضاء افحص العلاقات مع المتغير المستهدف مع الأخذ في الاعتبار أن الاستكشاف الموجه نحو المتغير المستهدف قد يؤدي إلى “تحيز الاختيار” إذا كان يؤثر على القرارات بشكل متكرر دون وجود استراتيجية ملائمة للتحقق من النتائج

قائمة مراجعة عملية: افحص التوزيعات الرقمية وتكرارات المتغيرات الفئوية والعلاقات بين المتغيرات المهمة والفروق على مستوى المجموعات والقيم المتطرفة المحتملة، استخدم الرسوم البيانية لاستقصاء أسئلة محددة بدلاً من إنشاء تصورات مرئية تفتقر إلى هدف تحليلي واضح

تُعد مرحلة إعداد البيانات هي النقطة التي تتحول فيها النتائج المستخلصة من الاستكشاف الأولي إلى قرارات عملية، ولا يكمن الهدف في جعل كل مجموعة بيانات متطابقة تماماً، بل في تحويل المعلومات المتاحة إلى صيغة ملائمة للتحليل المطلوب مع الحفاظ في الوقت ذاته على المعلومات ذات الدلالة بالنسبة للقيم الرقمية المفقودة يمكن تعويضها باستخدام الوسيط أو المتوسط ​​الحسابي

(Categorical variables) بينما قد تتطلب المتغيرات الفئوية

تخصيص فئة مستقلة للقيم المفقودة أو استبدالها بالقيمة الأكثر تكراراً، ويعتمد اختيار الطريقة المناسبة على طبيعة المتغير وحجم البيانات المفقودة والافتراضات التي يمكن تبنيها منطقياً، وفي بعض الحالات يكون من المفيد الاحتفاظ بمؤشر خاص للقيم المفقودة، إذ قد يحمل غياب القيمة بحد ذاته دلالةً معلوماتية

غالباً ما تحتاج السمات الفئوية إلى ترميز قبل إمكانية استخدامها في خوارزميات تعلم الآلة التقليدية، ويُعد “الترميز الأحادي” خياراً مناسباً للعديد من الفئات الاسمية -مثل نوع المنتج أو اسم الدولة- لأنه يتجنب فرض ترتيب رقمي مصطنع، أما “الترميز الترتيبي” فقد يكون أكثر ملاءمة عندما تتبع الفئات ترتيباً منطقياً فعلياً مثل: منخفض ومتوسط ومرتفع كما يُعد ضبط مقياس القيم الرقمية أمراً بالغ الأهمية، فبعض الخوارزميات

(Regularization) مثل الانحدار اللوجستي مع التنظيم

(SVM) وآلات المتجهات الداعمة

(k-nearest neighbors) وخوارزمية أقرب الجيران

قد تكون حساسة للفروق في مقاييس السمات

(Decision trees) في المقابل لا تتطلب أشجار القرار

والنماذج المعتمدة على الأشجار اهتماماً كبيراً بضبط المقاييس، لأن عمليات التقسيم فيها تعتمد على عتبات محددة للسمات وليس على المسافات بين القيم المقاسة ويتمثل المبدأ الأهم في تجنب تسريب أي معلومات من بيانات التقييم إلى عملية إعداد البيانات، لذا يجب استخلاص قيم التعويض ومعايير ضبط المقاييس وقرارات اختيار السمات وغيرها من التحويلات بناءً على بيانات التدريب فقط، ولهذا السبب تكتسب أدوات

Scikit-learn في مكتبة (Pipelines) “خطوط المعالجة”

أهمية كبيرة، فهي تساعد في الحفاظ على اتساق سير العمل بين مرحلتي المعالجة الأولية وتدريب النموذج

قائمة مراجعة عملية: اختر طرقاً مناسبة لتعويض القيم المفقودة وقم بترميز المتغيرات الفئوية واضبط مقاييس السمات الرقمية عند الحاجة ووحد الصيغ غير المتسقة للبيانات مع الحرص على الاحتفاظ بالمعلومات ذات القيمة، تأكد من أن كل تحويل تجريه له ما يبرره استناداً إلى طبيعة البيانات وأهداف بناء النموذج

قد يُظهر النموذج أداءً مبهراً على البيانات التي سبق له التعامل معها، لكنه قد يفشل في التعميم عند مواجهة ملاحظات جديدة، ولتقييم قدرة النموذج على التعميم، يجب تقسيم البيانات المتاحة إلى مجموعتين: مجموعة للتدريب وأخرى للتقييم وذلك بطريقة تحاكي الكيفية التي سيُستخدم بها النموذج فعلياً، بالنسبة للعديد من الملاحظات المستقلة تتمثل نقطة البداية الشائعة في تقسيم البيانات إلى 80% للتدريب و20% للاختبار، أما في مسائل التصنيف التي تتسم بعدم توازن فئات الهدف فقد يكون من المفيد استخدام

(stratification) “التقسيم الطبقي”

الذي يساعد في الحفاظ على نسب الفئات كما هي عبر أجزاء البيانات المقسمة

from sklearn.model_selection import train_test_split
X = df.drop(columns=["target"])
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)

(الهدف) “target” هنا يجب استبدال كلمة

باسم العمود الفعلي المستهدف، وتُعد عملية التقسيم الطبقي ملائمة

(classification) عندما تتضمن المهمة تصنيفاً

بوجود فئات محددة

(regression) أما في حالات الانحدار

`stratify=y`فينبغي إزالة المعامل

ما لم تكن قد وضعت استراتيجية مدروسة ومناسبة للتقسيم الطبقي

(test set) يجب تخصيص مجموعة الاختبار

للتقييم النهائي فقط وتجنب الرجوع إليها بشكل متكرر أثناء تطوير النموذج، فمقارنة نماذج متعددة باستخدام مجموعة الاختبار ذاتها تؤدي تدريجياً إلى تكييف القرارات لتناسب تلك العينة تحديداً، مما يجعل النتيجة النهائية أقل استقلالية مما تبدو عليه

(cross-validation) لذا يُعد التحقق المتقاطع

على بيانات التدريب أساساً أكثر موثوقية للمقارنة بين الخيارات المختلفة

تتطلب بعض مجموعات البيانات استراتيجيات تقسيم مختلفة تماماً

(time-series) ففي بيانات السلاسل الزمنية

ينبغي الفصل بين البيانات زمنياً لضمان عدم تسرب معلومات مستقبلية إلى مرحلة التدريب، كما قد تتطلب البيانات التي تتضمن قياسات متكررة لنفس المريض أو العميل أو الجهاز استخدام استراتيجية

(group-based splitting) تقسيم قائمة على المجموعات

وذلك لمنع ظهور سجلات مترابطة في كل من مجموعتي التدريب والتقييم، إن اختيار الاستراتيجية الصحيحة ينبع من طبيعة العملية التي تولد البيانات وليس مجرد الاعتماد على نسبة مئوية ثابتة

قائمة مراجعة عملية: حدد الهدف المراد التنبؤ به وافصل السمات عن التسميات واختر استراتيجية تقسيم مناسبة واحتفظ بمجموعة اختبار تظل بمنأى تام عن عملية التطوير وتأكد من عدم وجود تسرب للبيانات ناتج عن تكرار الكيانات أو تضمين ملاحظات مستقبلية أو استخدام سمات مشتقة من المتغير المستهدف

Advertisements

قد يكون من المغري البدء بنموذج معقد نظراً لأن الخوارزميات المتقدمة غالباً ما تحظى باهتمام أكبر، لكن من الناحية العملية يُعد البدء بنموذج مرجعي بسيط خياراً أفضل، فهو يوفر معياراً يمكن من خلاله تقييم النماذج الأكثر تعقيداً، كما يكشف عما إذا كانت مجموعة البيانات تحتوي على معلومات تنبؤية كافية تبرر إضافة المزيد من التعقيد

في مسائل التصنيف

(Dummy Classifier) “يمكن استخدام “مصنف افتراضي

لتحديد درجة مرجعية أساسية

(Logistic Regression) “بينما يمثل “الانحدار اللوجستي

نموذجاً أولياً جيداً بشرط أن تكون افتراضاته وقيوده مقبولة في سياق المشكلة، أما في مسائل الانحدار فيمكن اعتبار التنبؤ بمتوسط أو وسيط قيم مجموعة التدريب نموذجاً مرجعياً

(Linear Regression) “في حين يساعد “الانحدار الخطي

في معرفة ما إذا كانت العلاقات البسيطة قادرة بالفعل على تفسير جزء مفيد من التباين في البيانات

لنتخيل شركة تحاول التنبؤ بما إذا كان العملاء سيلغون اشتراكاتهم، فإذا كان 10% فقط من العملاء يلغون اشتراكاتهم فإن نموذجاً يتوقع دائماً الفئة الأكثر شيوعاً (عدم الإلغاء) قد يحقق دقة تصل إلى 90%، ورغم أن هذه النتيجة تبدو قوية إلا أن النموذج سيفشل تماماً في تحديد أي من العملاء المعرضين لخطر إلغاء الاشتراك، يوضح هذا المثال لماذا يجب تفسير النموذج المرجعي في ضوء أهداف العمل ومقاييس التقييم المناسبة

كما يتيح النموذج البسيط فرصة للتحقق من سلامة سير العمل بالكامل قبل إضافة أي تعقيدات، فإذا كانت عمليات تقسيم البيانات والمعالجة الأولية والتقييم وتفسير النتائج غير موثوقة بعد فإن استخدام خوارزمية أكثر تقدماً لن يؤدي إلى تحسين النتائج تلقائياً بل سيجعل تشخيص المشكلات في المشروع أكثر صعوبة

قائمة مراجعة عملية: أنشئ نموذجاً مرجعياً بسيطاً ودرّب نموذجاً يمكن تفسير نتائجه ثم قيّمه باستخدام مقياس ملائم لطبيعة المشكلة وسجّل النتيجة، لا تلجأ إلى تعقيد النموذج إلا إذا كان هناك سبب واضح يدعو لتوقع تحسن ملموس في الأداء

مفيدة للغاية Scikit-learn تعد مكتبة

فهي توفر واجهة موحدة للمعالجة الأولية وتدريب النماذج والتحقق المتقاطع والتقييم

`Pipeline` و`ColumnTransformer` وتتيح فئتا

دمج عمليات تحويل متنوعة لأنواع مختلفة من السمات مع النموذج النهائي مما يقلل من مخاطر حدوث تباين في المعالجة بين مرحلتي التدريب والتنبؤ يوضح المثال التالي سير عمل عملياً لمسألة تصنيف باستخدام مجموعة بيانات تحتوي على سمات رقمية وأخرى فئوية

(Binary) يفترض المثال أن المتغير المستهدف ثنائي القيمة

وأنه قد تم تحديد أعمدة السمات بشكل صحيح

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
numeric_features = X_train.select_dtypes(
include="number"
).columns
categorical_features = X_train.select_dtypes(
exclude="number"
).columns
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipeline = Pipeline([
(
"imputer",
SimpleImputer(strategy="most_frequent")
),
(
"encoder",
OneHotEncoder(handle_unknown="ignore")
)
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, numeric_features),
(
"categorical",
categorical_pipeline,
categorical_features
)
])
model = Pipeline([
("preprocessing", preprocessor),
("classifier", LogisticRegression(max_iter=1000))
])
scores = cross_val_score(
model,
X_train,
y_train,
cv=5,
scoring="f1"
)
print("Mean cross-validation F1:", scores.mean())
model.fit(X_train, y_train)

تقوم هذه الآلية بتعويض القيم العددية المفقودة وتعديل مقياس السمات العددية وتعويض القيم الفئوية المفقودة وتشفير المتغيرات الفئوية

one-hot باستخدام ترميز

قبل تدريب نموذج الانحدار اللوجستي، ولأن هذه التحويلات تتم ضمن الآلية نفسها، يمكن للتحقق المتبادل إعادة ضبطها بشكل منفصل على كل مجموعة تدريب بدلاً من السماح لمعلومات مجموعة التحقق بالتأثير على المعالجة المسبقة

للتحقق المتبادل F1 يستخدم المثال مقياس

وهو مفيد عند أهمية تحقيق التوازن بين الدقة والاستدعاء، مع ذلك فهو ليس مناسباً في جميع الحالات، فإذا كانت تكلفة النتائج الإيجابية الخاطئة والنتائج السلبية الخاطئة متفاوتة بشكل كبير فينبغي أن يعكس مقياس التقييم هذه النتائج، وبالمثل يجب التحقق من افتراضات التصنيف الثنائي قبل تطبيق هذه الآلية نفسها على مسائل التصنيف المتعدد أو التصنيفات المتعددة أو الانحدار

بمجرد تحديد الأساس يمكن مقارنة الخوارزميات الأخرى باستخدام نفس تقسيمات البيانات وإطار التقييم، وبحسب طبيعة المشكلة قد تشمل الخوارزميات المناسبة الغابات العشوائية والأشجار المعززة بالتدرج وآلات المتجهات الداعمة أو نماذج خطية بديلة، فلا يهدف البحث إلى جمع أكبر عدد ممكن من الخوارزميات، بل إلى تحديد النموذج الأمثل الذي يلبي متطلبات المهمة من حيث التنبؤ والتشغيل وقابلية التفسير

قائمة التحقق العملية: دمج المعالجة المسبقة والنمذجة في مسار معالجة متكامل، استخدام التحقق المتبادل لمقارنة النماذج، تطبيق مسار المعالجة المختار على بيانات التدريب والاحتفاظ بمجموعة الاختبار منفصلة حتى التقييم النهائي

لا تكون نتيجة التعلم الآلي مفيدة إلا عند فهم معناها، تعتمد طريقة التقييم الصحيحة على ما إذا كان النموذج يؤدي مهمة تصنيف أو انحدار أو ترتيب أو تنبؤ أو أي مهمة أخرى، حتى ضمن المهمة الواحدة قد تؤدي المقاييس المختلفة إلى استنتاجات متباينة حول النموذج الأفضل في التصنيف الثنائي تقيس الدقة نسبة التنبؤات الصحيحة، بينما تقيس الدقة عدد النتائج الإيجابية المتوقعة التي تحققت بالفعل ويقيس الاستدعاء عدد النتائج الإيجابية الفعلية التي حددها النموذج بنجاح

F1 يجمع مقياس

بين الدقة والاستدعاء من خلال متوسطهما التوافقي

أداء التصنيف عبر عتبات التصنيف ROC-AUC ويقيس مؤشر

بينما يُعد تحليل الدقة والاستدعاء مفيداً للغاية عندما تكون الفئة الإيجابية نادرة

(MAE) في الانحدار يقيس متوسط الخطأ المطلق

متوسط الخطأ المطلق في التنبؤ

(RMSE) بينما يُعاقب جذر متوسط مربع الخطأ

الأخطاء الكبيرة بشكل أكبر

منظوراً آخر (\(R^2\)) يُقدِّم معامل التحديد

حول الأداء التنبؤي رغم أنه لا ينبغي اعتباره مقياساً شاملاً لجودة النموذج وبعد ضبط نموذج التصنيف يمكنك حساب العديد من المقاييس الشائعة

(held-out test set) باستخدام مجموعة بيانات الاختبار المستبعدة

from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
classification_report,
confusion_matrix
)
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(
y_test, y_pred, zero_division=0
))
print("Recall:", recall_score(
y_test, y_pred, zero_division=0
))
print("F1:", f1_score(
y_test, y_pred, zero_division=0
))
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))

يفترض هذا المثال تصنيفاً ثنائياً مع فئة موجبة تقليدية، ففي حال كانت المهمة متعددة الفئات ينبغي اختيار استراتيجية مناسبة

F1 لحساب المتوسطات للدقة والاستدعاء ومقياس

والتأكد من أن مصفوفة الارتباك والتقرير يعكسان بنية الفئات الفعلية

ينبغي أن يشمل التقييم أيضاً دراسة عواقب الأخطاء، ففي كشف الاحتيال قد يكون إغفال معاملة احتيالية أكثر تكلفة من التحقيق في معاملة مشروعة وفي الفحص الطبي قد يكون لتجاهل حالة حقيقية عواقب وخيمة، وفي مجال الاحتفاظ بالعملاء قد يحتاج النموذج إلى تحديد عدد كافٍ من العملاء المعرضين للخطر ضمن ميزانية تدخل محدودة، فتتطلب هذه الحالات أكثر من مجرد مقياس رئيسي واحد قائمة مراجعة عملية: اختيار المقاييس قبل مقارنة النماذج وفحص الأداء الخاص بكل فئة وتحليل مصفوفات الارتباك أو البواقي والتحقيق في حالات الفشل المهمة وتقييم ما إذا كانت النتائج تحقق الهدف التشغيلي الحقيقي

بعد تقييم النموذج الأساسي ينبغي أن يستند تحسين النموذج إلى الأدلة بدلاً من التجربة والخطأ، يحدث نقص التوافق عندما يكون النموذج محدوداً جداً بحيث لا يستطيع استيعاب البنية المهمة في البيانات، بينما يحدث فرط التوافق عندما يتعلم أنماطاً لا يمكن تعميمها بشكل موثوق على الملاحظات غير المرئية، قد ينتج عن كليهما نتائج مخيبة للآمال لكنهما يتطلبان استجابات مختلفة يوفر التحقق المتقاطع أساساً أكثر استقراراً لمقارنة النماذج المرشحة والمعلمات الفائقة

GridSearchCV خاصية Scikit-learn توفر مكتبة

لتقييم تركيبات محددة

لأخذ عينة من مجموعة فرعية من التكوينات الممكنة RandomizedSearchCV وخاصية

قد تكون الأخيرة أكثر عملية عندما تكون مساحة البحث كبيرة

على سبيل المثال: يمكن تقييم نموذج الغابة العشوائية عبر أعداد مختلفة من الأشجار وأعماق قصوى وأحجام أوراق دنيا، تؤثر هذه الإعدادات على تعقيد النموذج ويمكن أن تؤثر على التوازن بين الأداء التنبؤي والتكلفة الحسابية والتعميم

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
forest_pipeline = Pipeline([
("preprocessing", preprocessor),
("classifier", RandomForestClassifier(
random_state=42
))
])
param_distributions = {
"classifier__n_estimators": [100, 200, 400],
"classifier__max_depth": [None, 5, 10, 20],
"classifier__min_samples_leaf": [1, 2, 5, 10]
}
search = RandomizedSearchCV(
forest_pipeline,
param_distributions=param_distributions,
n_iter=12,
cv=5,
scoring="f1",
random_state=42,
n_jobs=-1
)
search.fit(X_train, y_train)
print("Best parameters:", search.best_params_)
print("Best CV F1:", search.best_score_)

يستخدم هذا البحث نفس استراتيجية المعالجة المسبقة المستخدمة في مثال الانحدار اللوجستي، يسمح بناء جملة المعامل

Scikit-learn ذي الشرطتين السفليتين لمكتبة

بالوصول إلى إعدادات المصنف عبر مسار المعالجة

`search.best_estimator_`فبمجرد انتهاء البحث يحتوي

على أفضل مسار معالجة تم العثور عليه ضمن إعدادات البحث المحددة

يمكن لهندسة الميزات أيضاً تحسين الأداء خاصةً عندما لا تُعبّر الأعمدة الأولية عن بنية المشكلة بوضوح، قد يكون تكرار المعاملات ومتوسط قيمة الطلب ومدة ولاء العميل والوقت المنقضي منذ عملية الشراء السابقة أكثر إفادة من سجلات المعاملات المنفردة، مع ذلك يجب حساب الميزات المُهندسة باستخدام المعلومات المتاحة فقط وقت التنبؤ، فعلى سبيل المثال: يجب ألا يستخدم نموذج الاحتفاظ بالعملاء المعاملات المستقبلية لبناء ميزات الشراء التاريخية

أخيراً يجب توخي الحذر عند إجراء التجارب المتكررة، فإذا قمت بفحص نتيجة الاختبار بشكل متكرر وتعديل النموذج بناءً على ذلك فإن مجموعة الاختبار تُصبح تدريجياً جزءاً من عملية التطوير، يساعد التحقق المتبادل والفصل المنهجي بين التدريب والتحقق والاختبار النهائي في الحفاظ على مصداقية التقييم

يتعلق هذا التحذير الأخير بالتجريب المتكرر، قائمة مراجعة عملية: استخدم التحقق المتبادل لمقارنة النماذج واضبط المعلمات الفائقة بشكل منهجي واستكشف فرص هندسة الميزات وتحقق من فرط التخصيص وتجنب استخدام مجموعة الاختبار النهائية كهدف متكرر للتحسين

لا يُعدّ النموذج الذي يُنتج تنبؤات دقيقة بالضرورة منتجاً تحليلياً مفيداً، إذ يحتاج أصحاب المصلحة إلى فهم معنى التنبؤات ومواطن قوة النموذج والقيود التي ينبغي أن تؤثر على القرارات، يكتسب التفسير أهمية خاصة عندما تؤثر التنبؤات على العملاء أو الموظفين أو النتائج المالية أو غيرها من العمليات الهامة

بالنسبة للنموذج الخطي يمكن أن تساعد المعاملات في شرح كيفية ارتباط التغيرات في الميزات بالتنبؤات، وذلك وفقاً لافتراضات النموذج وخيارات المعالجة المسبقة، بالنسبة للنماذج الشجرية يمكن أن توفر أهمية الميزات ملخصاً أولياً مفيداً للمتغيرات التي تُسهم في الأداء التنبؤي، مع ذلك لا ينبغي تفسير مقاييس الأهمية تلقائياً على أنها دليل على السببية وقد تجعل الميزات المترابطة من الصعب تفسير درجات الأهمية الفردية

SHAPيمكن لأدوات مثل أهمية التبديل و

أن توفر رؤى إضافية حول سلوك النموذج، تقيس أهمية التبديل كيفية تغير أداء النموذج عند تغيير قيم إحدى الميزات

مساهمات الميزات SHAP بينما يقدر

في التنبؤات الفردية ضمن إطار إسناد محدد، تنطوي كل طريقة على افتراضات وقيود لذا ينبغي أن يظل التفسير مرتبطاً بالنموذج ومجموعة البيانات والسؤال المطروح

كما يتطلب التواصل بشأن هذه النتائج التمييز بين الارتباط التنبؤي والتفسير السببي، فإذا كان العملاء ذوو فترات التعامل الأقصر أكثر عرضة لإلغاء حساباتهم، فهذا لا يعني بالضرورة أن طول فترة التعامل بحد ذاته هو سبب الإلغاء إذ قد توجد متغيرات أخرى تفسر هذه العلاقة، ولتحديد التأثيرات السببية لا يكفي الاعتماد على الدقة التنبؤية وحدها بل يتطلب الأمر تصميماً بحثياً ملائماً

قائمة مراجعة عملية: وضّح الغرض من النموذج واعرض مستوى أدائه وقيوده وافحص السمات المهمة والأخطاء النموذجية وميّز بين الارتباط والسببية وقدم النتائج بلغة تناسب الجمهور المستهدف

غالباً ما يتم تجاهل هذه المرحلة الأخيرة في المشاريع التمهيدية، فمجرد نجاح تشغيل دفتر ملاحظات لمرة واحدة لا يعني بالضرورة أن سير العمل التحليلي قابل للتكرار، كما أن النموذج الذي يحقق أداءً جيداً أثناء التقييم لا يعني تلقائياً أنه جاهز للنشر الفعلي (الإنتاج)، يتطلب العمل الموثوق القدرة على تكرار النتائج وتطبيق التحويلات ذاتها على بيانات جديدة ورصد أي تغيرات في الأداء بعد النشر

ينبغي للمشروع النافع أن يحتفظ بمنطق إعداد البيانات والنموذج المختار ونتائج التقييم والبيئة اللازمة لإعادة إجراء التحليل، يمكن أن تساهم الدوال القابلة لإعادة الاستخدام والنصوص البرمجية ذات البنية النمطية في تقليل تكرار الأكواد، بينما يساعد نظام التحكم في الإصدارات على تتبع التغييرات التي تطرأ على المشروع، أما في حالة مجموعات البيانات الأكبر حجماً فيمكن الاستعانة بأدوات مخصصة لإصدارات البيانات وتتبع التجارب لتوفير هيكلية أكثر تنظيماً

وبمجرد تقييم النموذج يمكن حفظ مسار العمل المُدرَّب

ثم تحميله لاحقاً Scikit-learn في مكتبة

لاستخدامه في التنبؤ، ومن الأساليب الشائعة

`joblib` في هذا الصدد استخدام مكتبة

import joblib
joblib.dump(model, "customer_model.joblib")
loaded_model = joblib.load("customer_model.joblib")
predictions = loaded_model.predict(new_data)

هنا يجب أن تحتوي البيانات الجديدة على نفس أعمدة الميزات المتوقعة وأنواع البيانات المتوافقة مع المدخلات الأصلية، فيحتفظ مسار المعالجة بخطوات المعالجة المسبقة المُجهزة جنباً إلى جنب مع المصنف بحيث تمر الملاحظات الجديدة بنفس التحويلات المستخدمة أثناء التدريب

يُثير حفظ النموذج اعتبارات أمنية

joblib فيمكن للملفات المحفوظة باستخدام

pickle أو آليات التسلسل القائمة على

في بايثون تنفيذ تعليمات برمجية عشوائية عند تحميلها، لذا يجب تحميل الملفات فقط من مصادر موثوقة، بالإضافة إلى ذلك يجب ربط النموذج المحفوظ بإصدارات التبعيات والوثائق المناسبة لأن تغييرات البرامج غير المتوافقة قد تؤثر على إمكانية إعادة إنتاج النتائج

كما يُنشئ النشر مسؤوليات جديدة، قد تتغير البيانات الواردة في توزيعها وقد تزداد معدلات القيم المفقودة وقد تضعف العلاقات بين الميزات والنتائج بمرور الوقت، تساعد مراقبة جودة المدخلات وتوزيعات التنبؤ وأداء النموذج الفعلي – عند توفر نتائج الحقيقة الأساسية – في تحديد متى يلزم إجراء تحقيق أو إعادة تدريب، بالنسبة للتطبيقات ذات التأثير الكبير قد تكون الحوكمة والخصوصية والإنصاف والتحكم في الوصول والإشراف البشري أجزاءً أساسية من سير العمل

قائمة مراجعة عملية: احفظ مسار المعالجة المُجهز بالكامل ووثّق التبعيات واحفظ نتائج التقييم وتحقق من صحة بيانات الإدخال الجديدة واحمِ ملفات النموذج المُسلسلة وحدد خطة لمراقبة الأداء بعد النشر

يكمن الفرق بين كتابة كود بايثون وممارسة علوم البيانات في جودة القرارات المتخذة على طول الطريق، يبدأ سير العمل الناجح بفهم البيانات ويستمر من خلال الاستكشاف والإعداد المُنضبط ولا يصل إلى التعلم الآلي إلا بعد أن تصبح الأسس التحليلية موثوقة بدرجة كافية، تُقلل كل مرحلة فئة مختلفة من المخاطر من الملخصات المُضللة وتسريب البيانات إلى مقاييس التقييم غير المناسبة والنماذج التي تفشل خارج بيئة التدريب تُسهل بايثون هذه العملية لأن نظامها البيئي يربط جميع مراحل العمل تقريباً

Pandas و NumPy فتدعم مكتبتا

معالجة البيانات وتساعد مكتبات التصور البياني في الكشف عن الأنماط

طريقة منظمة Scikit-learn بينما توفر مكتبة

لإعداد الميزات وتدريب النماذج وتقييم أدائها، ومع ذلك تبقى المكتبات أدوات وليست بدائل للاستدلال الإحصائي، تتحقق أفضل النتائج عندما يدرك المحلل الافتراضات الكامنة وراء كل طريقة ويكون مستعداً لمساءلة النتائج الواعدة بدلاً من قبولها كما تبدو للوهلة الأولى

إذا كنت تعمل على تطوير مهاراتك في علم البيانات فجرب تطبيق هذه القائمة المرجعية على مجموعة بيانات لم يسبق لك فحصها من قبل، مُر بكل مرحلة من المراحل ودوِّن القرارات التي تتخذها ثم قارن بين نموذجك الأولي (الأساسي) والنموذج النهائي، أي مرحلة تجدها الأكثر صعوبة: تحليل البيانات الاستكشافي أم تنظيف البيانات أم هندسة السمات أم تقييم النموذج؟ شاركنا تجربتك في التعليقات، فغالباً ما تكون الصعوبات العملية التي تواجهها في المشاريع الواقعية أكثر تعليماً من الدروس التعليمية المُعدّة بشكل مثالي

Advertisements

Leave a Reply