End-to-End Data Science Project — Complete Guide
From the publisher’s feed, collected in the ZeroLabs newsroom.
This document is the one-stop guideline for this repository. It combines:practical operations from README.mdtheoretical background on the dataset and algorithmexplanation of how every part of the codebase connectsguidance on metrics, tracking, and improving wine quality predictionsWe can Use this file when we want to understand what the project does, why it is designed this way, and how to run and improve it.Part I — Conceptual Foundation1. What This Project IsThis project is an end-to-end machine learning workflow for the red wine quality dataset. It covers:data ingestiondata validationtrain/test splitmodel training with ElasticNetmodel evaluationexperiment tracking with DagsHub-hosted MLflowmodel registration in MLflow Model Registrya Flask web app for training and predictioncontainerized execution with Docker and Docker ComposeThe repository is structured so that configuration, pipeline orchestration, component logic, tracking, artifacts, and serving are separated cleanly.1.1 Project GoalThe goal of the project is to take a tabular dataset from source to a trained and tracked model in a reproducible way.At a high level, the project does this:Download the datasetValidate the schemaSplit the data into train and test setsTrain an ElasticNet modelEvaluate the modelLog metrics and parameters to MLflow on DagsHubRegister the model in MLflow as ElasticnetModelServe a simple UI for training and prediction2. Wine Quality Dataset — Theory and Context2.1 Origin and PurposeThe Wine Quality dataset is a well-known tabular dataset used in machine learning education and benchmarking. It was originally published in connection with wine chemistry research and is commonly used to predict sensory quality scores from measurable chemical properties.In this project we use the red wine subset. The data describes physicochemical measurements of individual wine samples. Each row is one wine sample. The target variable is a quality score assigned by human tasters (not a continuous chemical measurement).2.2 Problem TypeThis is a regression problem:Input (features): 11 numeric wine chemistry attributesOutput (target): quality — an integer score, typically between 3 and 8 in practiceThe model learns a mapping:(fixed acidity, volatile acidity, ..., alcohol) --> predicted quality2.3 Feature Descriptions2.4 Target Column: qualityDefined in schema.yaml as quality (integer)Represents an aggregated expert rating, not a precise chemical measurementBecause ratings are subjective and discrete, perfect prediction is difficultSmall prediction errors (e.g., predicting 5.8 vs actual 6) may still be acceptable in practice2.5 Dataset Characteristics Relevant to ModelingUnderstanding the data helps explain model behavior:Moderate size — roughly 1,600 red wine samples; enough for baseline models but not deep learning scaleAll numeric features — no categorical encoding required in the current pipelineNo scaling in current pipeline — features have different ranges (e.g., density ~0.99 vs free SO₂ ~0–70); scaling can improve linear modelsImbalanced target distribution — most wines cluster around scores 5–6; rare scores (3, 8) are harder to predictCorrelated features — density, alcohol, and sugar-related features often correlate; regularized models like ElasticNet handle this better than plain linear regression2.6 Where the Dataset Lives in This Project3. ElasticNet Algorithm — Theory3.1 What ElasticNet IsElasticNet is a linear regression model that combines:L1 regularization (Lasso) — encourages sparsity (some coefficients become exactly zero)L2 regularization (Ridge) — shrinks coefficients smoothly and handles multicollinearityIt is implemented in scikit-learn as sklearn.linear_model.ElasticNet.3.2 Why ElasticNet Fits This ProjectFor wine quality prediction, ElasticNet is a strong baseline because:The relationship between chemistry and perceived quality is often approximately linear at first approximationFeatures are correlated (e.g., density and alcohol)The model is interpretable — you can inspect which chemical factors push quality up or downIt is fast, stable, and easy to deploy with joblibHyperparameters are simple to tune and log in MLflow3.3 Mathematical IntuitionElasticNet minimizes:Loss = MSE + α × [ l1_ratio × |w| + (1 - l1_ratio) × w² ]Where:MSE — mean squared error between predicted and actual qualityw — model coefficients (weights for each feature)α (alpha) — overall regularization strengthl1_ratio — balance between Lasso (1.0) and Ridge (0.0)3.4 Hyperparameters in This ProjectDefined in params.yaml:ElasticNet: alpha: 0.2 l1_ratio: 0.1These values are read by ConfigurationManager, passed into ModelTrainerConfig, used during training in model_trainer.py, and logged to MLflow during evaluation.3.5 Training Behavior in This CodebaseIn model_trainer.py:Load train.csv and test.csvSplit features (X) and target (y = quality)Create ElasticNet(alpha=..., l1_ratio=..., random_state=42)Fit on training data onlySave fitted model to artifacts/model_trainer/model.joblibAt prediction time (prediction_pipeline.py), the saved model loads and runs model.predict() on user input from the Flask form.4. Evaluation Metrics — TheoryDuring model evaluation, the project computes and logs three regression metrics.4.1 RMSE (Root Mean Squared Error)Formula:RMSE = sqrt( mean( (y_true - y_pred)² ) )Interpretation:Measures average prediction error in the same units as quality scorePenalizes large errors more heavily than MAE (because errors are squared)Lower is betterExample: RMSE ≈ 0.70 means predictions are off by roughly 0.7 quality points on average (with extra penalty for big misses)In this project: computed in model_evaluation.py via mean_squared_error, then square-rooted.4.2 MAE (Mean Absolute Error)Formula:MAE = mean( |y_true - y_pred| )Interpretation:Average absolute difference between predicted and actual qualityEasier to explain to non-technical stakeholders than RMSELess sensitive to occasional large outliers than RMSELower is betterIn this project: if MAE ≈ 0.54, predictions are typically within about half a quality point.4.3 R² (Coefficient of Determination)Formula (intuition):R² = 1 - (variance unexplained by model / total variance in target)Interpretation:Ranges from negative infinity to 1.0 (1.0 is perfect)Measures how much variance in quality the model explainsR² ≈ 0.21 means the model explains about 21% of quality variation — common for this dataset with a simple linear modelHigher is betterImportant: for subjective ratings like wine quality, even strong models often show modest R². Improvement should be judged relative to baselines, not against an unrealistic R² = 1.0.4.4 Where Metrics Are Stored and Tracked5. How to Improve Model Quality and PredictionsBetter wine quality predictions and better metrics usually move together, but always validate on the held-out test set to avoid overfitting.5.1 Hyperparameter TuningAdjust params.yaml and re-run python main.py:Try a grid of alpha values: 0.01, 0.05, 0.1, 0.2, 0.5, 1.0Try l1_ratio values: 0.1, 0.3, 0.5, 0.7, 0.9Use GridSearchCV or RandomizedSearchCV in a research notebookLog each experiment in MLflow to compare runsExpected effect: lower RMSE/MAE, higher R² if tuning finds a better bias-variance tradeoff.5.2 Feature ScalingThe current pipeline does not scale features. ElasticNet is sensitive to feature scale because regularization penalizes all coefficients equally.Improvement: add StandardScaler or MinMaxScaler in data_transformation.py or wrap the model in a Pipeline:from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalerpipeline = Pipeline([ ("scaler", StandardScaler()), ("model", ElasticNet(alpha=..., l1_ratio=..., random_state=42)),])Expected effect: often improves linear model performance noticeably.5.3 Better Train/Test MethodologyCurrent split in data_transformation.py uses default train_test_split(data) (75/25, shuffled, no random_state).Improvements:Set random_state=42 for reproducibilityTry stratified splitting based on binned quality scoresUse cross-validation for more reliable metric estimates5.4 Feature EngineeringIdeas grounded in wine chemistry:Interaction terms (e.g., alcohol × volatile acidity)Ratios (e.g., free SO₂ / total SO₂)Polynomial features for non-linear effectsOutlier handling for extreme volatile acidity values5.5 Try Alternative ModelsKeep ElasticNet as baseline, then compare in MLflow:Register the best model under a new name or version in MLflow Model Registry.5.6 Data Quality ImprovementsStrengthen validation in data_validation.py (check dtypes, nulls, ranges — not just column names)Detect and handle duplicate rowsAnalyze target distribution and report class imbalance5.7 Connecting Metrics to User-Facing PredictionsWhen metrics improve:/predict returns quality estimates closer to actual scoresUsers see more trustworthy results in results.htmlMLflow runs show a history of improvement across experimentsPractical loop:change params/features → run main.py → check metrics.json → compare in DagsHub → deploy better model.joblibPart II — Architecture and Codebase Interaction6. End-to-End Flow Overviewconfig.yaml + params.yaml + schema.yaml | v ConfigurationManager | vPipeline classes (src/datascience/pipeline/) | vComponent classes (src/datascience/components/) | vdata/ + artifacts/ + logs/ + MLflow/DagsHub | vFlask app (app.py) + PredictionPipelineThis separation is important:configuration files describe what to runentity classes define the structure of that configurationcomponent classes do the real workpipeline classes orchestrate component executionDVC versions raw and processed datasets under data/main.py runs the whole training workflowapp.py exposes browser routes for training and prediction7. How Each Part Connects to the Others7.1 Configuration Layersrc/datascience/entity/config_entity.py defines dataclasses:DataIngestionConfigDataValidationConfigDataTransformationConfigModelTrainerConfigModelEvaluationConfigsrc/datascience/config/configuration.py reads YAML and builds typed config objects for each stage.7.2 Component Layer (Business Logic)7.3 Pipeline Layer (Orchestration)Each pipeline follows the same pattern:ConfigurationManager() → get_*_config() → Component(config) → run methodPipelines stay thin so you can test and swap components without rewriting orchestration.7.4 Entry Points7.5 Artifacts and Logs8. Complete Flow: Ingestion to PredictionStage 1 — Data IngestionGitHub ZIP URL → download to data/raw/data.zip → extract to data/raw/winequality-red.csvCode path: main.py → DataIngestionTrainingPipeline → DataIngestionStage 2 — Data Validationwinequality-red.csv → read columns → compare against schema.yaml COLUMNS → write artifacts/data_validation/status.txtCode path: main.py → DataValidationTrainingPipeline → DataValiadtionStage 3 — Data Transformationwinequality-red.csv → train_test_split (75% / 25%) → data/processed/train.csv → data/processed/test.csvCode path: main.py → DataTransformationTrainingPipeline → DataTransformationStage 4 — Model Trainingtrain.csv + test.csv + params.yaml → separate X and y (target = quality) → fit ElasticNet → save artifacts/model_trainer/model.joblibCode path: main.py → ModelTrainerTrainingPipeline → ModelTrainerStage 5 — Model Evaluation and Trackingtest.csv + model.joblib → predict on test features → compute rmse, mae, r2 → save metrics.json → log to DagsHub MLflow → register ElasticnetModel → tag model version with metricsCode path: main.py → ModelEvaluationTrainingPipeline → ModelEvaluationStage 6 — Prediction (Serving)User fills form on index.html (11 features) → POST /predict → app.py builds numpy array (1, 11) → PredictionPipeline loads model.joblib → model.predict() → results.html shows predicted qualityCode path: app.py → PredictionPipeline → saved modelOptional — Background Training via WebGET /train → subprocess.Popen(["python", "main.py"]) → stdout/stderr → logs/training.log → returns 202 immediatelyGET /train/status → "running" or "idle"This design prevents Gunicorn worker timeout during long training runs.9. Model and Tracking BehaviorThis project trains an ElasticNet regressor on wine quality data.During evaluation, the project logs:parameters from params.yamlmetrics: rmse, mae, r2the trained model artifacta registered model in DagsHub-hosted MLflowThe registered model name is: ElasticnetModelThe evaluation flow also tags the registered model version with metric values so the model registry is more informative.Credential flow:.env holds MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORDmodel_evaluation.py loads .env if env vars are not already setmlflow.set_tracking_uri() points to DagsHubRun is created, metrics logged, model registered10. Repository Structuredatascienceproject/|-- app.py|-- main.py|-- medium.md ← this guide|-- README.md ← operational reference|-- data/| |-- raw.dvc| |-- processed.dvc| |-- raw/| `-- processed/|-- .dvc/|-- Dockerfile|-- docker-compose.yml|-- .dockerignore|-- .env.example|-- requirements.txt|-- pyproject.toml|-- params.yaml|-- schema.yaml|-- config/| `-- config.yaml|-- templates/| |-- index.html| `-- results.html|-- research/| `-- notebooks for stage-by-stage experimentation`-- src/ `-- datascience/ |-- __init__.py |-- components/ |-- config/ |-- constants/ |-- entity/ |-- pipeline/ `-- utils/Part III — Operations GuideThe sections below preserve the operational content from README.md so this file remains a single source of truth for day-to-day use.11. How the Sections Relate to Each Other11.1 config/config.yamlMain runtime configuration. Defines:where downloaded data goeswhere transformed data goeswhere the trained model is savedwhere evaluation output is savedwhich MLflow tracking URI to usewhich registered model name to useCurrent model registration name:registered_model_name: ElasticnetModel11.2 params.yamlStores model hyperparameters:ElasticNet: alpha: 0.2 l1_ratio: 0.111.3 schema.yamlDefines expected dataset columns and target column:TARGET_COLUMN: name: quality11.4 src/datascience/entity/config_entity.pyDataclasses that turn raw YAML values into typed Python objects.11.5 src/datascience/config/configuration.pyConfiguration manager. Reads all YAML files and creates stage-specific config objects.11.6 src/datascience/components/Business logic:data_ingestion.py — download and extract ZIPdata_validation.py — schema column checkdata_transformation.py — train/test splitmodel_trainer.py — train ElasticNet, save joblibmodel_evaluation.py — metrics, MLflow, registry11.7 src/datascience/pipeline/Thin orchestration wrappers for each component.11.8 main.pyEnd-to-end training entrypoint. Runs stages 1–5 in order.11.9 app.pyFlask application:11.10 artifacts/ and logs/Generated at runtime. See Part II for artifact flow.12. PrerequisitesPython 3.11 or compatibleGitDocker Desktop and Docker Compose (for containerized runs)DVC CLI (installed by pip install -r requirements.txt)DagsHub accountAccess to the DagsHub repository used for MLflow logging13. Local Setup13.1 Create a virtual environmentGit Bash:python -m venv .venvsource .venv/Scripts/activate13.2 Install dependenciespip install -r requirements.txt13.3 Create the local .envMLFLOW_TRACKING_USERNAME=your-dagshub-usernameMLFLOW_TRACKING_PASSWORD=your-dagshub-tokenwe should not commit .env.13.4 DVC noteThis repository now tracks dataset directories with DVC:data/raw.dvcdata/processed.dvcCommit these DVC metadata files:data/raw.dvcdata/processed.dvcdata/.gitignore.dvc/config.dvc/.gitignore.dvcignoreDo not commit:.dvc/config.local.envactual files inside data/raw/actual files inside data/processed/If your DVC remote is already configured, run:dvc pullIf a DVC remote is not configured yet, python main.py can still recreate the local data from the configured source URL. That command recreates:data/raw/data/processed/This does not replace a shared remote-backed DVC workflow.14. DagsHub and MLflow Setup14.1 Connect Git project to DagsHubOption 1: Connect existing GitHub repo from DagsHub UI.Option 2: Add DagsHub as Git remote:git remote add dagshub https://dagshub.com//.gitgit push dagshub mainMLflow URI for this project:https://dagshub.com/faizulkhan56/datascienceproject.mlflowMatching DagsHub Git repository:https://dagshub.com/faizulkhan56/datascienceproject.gitPractical sequence for an existing GitHub project:Create or open the matching repository in DagsHubUse DagsHub’s “connect existing repository” flow or add DagsHub as an additional Git remote from your local cloneConfirm your code is visible in DagsHub after a normal Git pushConfigure .env locally for MLflow credentialsRun python main.py and verify experiment runs appear in DagsHub MLflow6. Configure the DVC remote and push tracked data if we also want dataset versioning visible in DagsHub14.2 MLflow configurationTracking URI is set in config/config.yaml. Credentials load from .env.14.3 Finding MLFLOW_TRACKING_PASSWORDUse a DagsHub access token (recommended over account password):Sign in to DagsHubUser settings → tokensCreate or copy tokenSet as MLFLOW_TRACKING_PASSWORD in .envToken page: https://dagshub.com/user/settings/tokensclick experiment for ML flow linkthen click data for token information14.4 Verify DagsHub connectionAfter successful training, confirm:new MLflow experiment runregistered model ElasticnetModelnew model versionmetrics rmse, mae, r214.5 DVC and DagsHub data versioningMLflow experiment tracking and DVC data versioning are separate features.This project now keeps DVC-tracked datasets in:data/raw/data/processed/To make dataset versions visible in DagsHub’s data area, we still need to complete the account-specific remote setup on our side:Configure a DVC remote for your storage backend or DagsHub-supported workflowAuthenticate that remote locallyRun dvc pushCommit and push the resulting DVC metadata files14.6 Configure DVC remote with DagsHub StorageAfter your Git repository is already connected to DagsHub and MLflow tracking is working, configure the DVC remote in this order.Browser steps:Open our DagsHub repository homepageFind the repository storage / remote / data-connection areaOpen the data-storage instructions for DVCCopy the repository-specific setup values shown thereTerminal steps:./.venv/Scripts/dvc.exe remote add -d dagshub s3://dvc./.venv/Scripts/dvc.exe remote modify dagshub endpointurl https://dagshub.com//.s3./.venv/Scripts/dvc.exe remote modify --local dagshub access_key_id ./.venv/Scripts/dvc.exe remote modify --local dagshub secret_access_key Notes:dagshub is the DVC remote name and is intentionally separate from Git origin-d makes it the default DVC remote--local stores credentials in .dvc/config.local, which must not be committedVerify the remote:./.venv/Scripts/dvc.exe remote listPush the tracked dataset:./.venv/Scripts/dvc.exe push -r dagshubOr, because it is the default:./.venv/Scripts/dvc.exe pushVerify after push:./.venv/Scripts/dvc.exe statusgit statusExpected outcome:DVC status is up to dateGit status remains clean or only shows intentional tracked config changes.dvc/config.local stays untrackedactual files under data/raw/ and data/processed/ stay out of GitThen refresh the DagsHub repository page and check the data-related view again.15. Run Locally Without Docker15.1 Full training pipelinepython main.py15.2 Flask apppython app.pyOpen: http://localhost:8080/after we gave value intended place15.3 Browser routeshttp://localhost:8080/ — homehttp://localhost:8080/train — background traininghttp://localhost:8080/train/status — status checkcheck log within application and log file16. Run with Docker16.1 Why DockerConsistent environment: Python, dependencies, Gunicorn, port mapping, volume mounts, healthcheck.16.2 Key filesDockerfile — builds image, runs Gunicorn on port 8080docker-compose.yml — loads .env, maps ports, mounts data/, artifacts/, and logs/.dockerignore — excludes venv, data payloads, logs, artifacts, .env from build context16.3 Build and startdocker compose build --no-cachedocker compose up -d16.4 Check status and logsdocker compose psdocker compose logs -f web16.5 Custom port$env:APP_HOST_PORT="8082"docker compose up -d16.6 Stopdocker compose down17. Recommended Sequence for a New UserClone the repositoryCreate .envInstall dependencies or use DockerIf a DVC remote already exists, run dvc pull; otherwise run python main.py to recreate data/raw/ and data/processed/Configure DVC remote access if you want shared data versioningReview config/config.yaml, params.yaml, schema.yamlStart the application with docker compose up -d or python app.pyConfirm data in data/ and artifacts in artifacts/Confirm MLflow logs on DagsHubTest /predict and background training18. How to Check Results18.1 Local artifactsAfter successful training:data/raw/data.zipdata/raw/winequality-red.csvdata/processed/train.csvdata/processed/test.csvartifacts/model_trainer/model.joblibartifacts/model_evaluation/metrics.jsondata/raw.dvcdata/processed.dvc18.2 LogsGet-Content .\logs\logging.log -WaitGet-Content .\logs\training.log -WaitGet-Content .\logs\training.log -Tail 5018.3 DagsHub / MLflowOn the run page verify: rmse, mae, r2, parameters, model artifact.In model registry verify: ElasticnetModel, latest version, tags.19. How to Test the Project19.1 Syntax checkpython -m py_compile app.pypython -m py_compile main.py19.2 Pipeline checkpython main.pySuccess: no exception, data directories created or reused, metrics JSON written, DagsHub run created.19.3 Web app check/ loads/train starts background job/train/status transitions running → idle/predict returns prediction19.4 Docker checkdocker compose build --no-cachedocker compose up -ddocker compose psdocker compose logs -f web20. Common Operational Checks21. Troubleshootingtrain hangs or errors/train uses subprocess.Popen — it should return immediatelyMonitor logs/training.logRebuild Docker if using containersGunicorn worker timeoutdocker compose downdocker compose build --no-cachedocker compose up -dNo MLflow logs on DagsHubCheck .env, username, token, and mlflow_uri in config/config.yaml.Metrics not obvious on model version pageMetrics live primarily on the MLflow run page. Model version links back to the run. This project also tags versions with metric values.uv warning in MLflow logsNon-fatal. MLflow falls back if uv is unavailable.Git warning in DockerImage installs git; GIT_PYTHON_REFRESH=quiet reduces noise.22. What a Successful Run Looks Likeall five pipeline stages completeraw data under data/raw/processed data under data/processed/metrics.json savedMLflow run URL in logsnew ElasticnetModel version created/train/status returns idle/predict works with trained model23. Recommended Daily WorkflowPull latest codeUpdate config or parameters if neededStart Docker or local environmentTrigger trainingMonitor logsCheck DagsHub MLflow resultsTest prediction UICommit only intended changes24. Useful Commands Referencepip install -r requirements.txtdvc pull./.venv/Scripts/dvc.exe remote add -d dagshub s3://dvc./.venv/Scripts/dvc.exe remote modify dagshub endpointurl https://dagshub.com//.s3./.venv/Scripts/dvc.exe remote modify --local dagshub access_key_id ./.venv/Scripts/dvc.exe remote modify --local dagshub secret_access_key ./.venv/Scripts/dvc.exe remote list./.venv/Scripts/dvc.exe push -r dagshubpython main.pypython app.pydocker compose build --no-cachedocker compose up -ddocker compose logs -f webdocker compose downGet-Content .\logs\training.log -Wait25. External ReferencesDagsHub experiment tracking: https://dagshub.com/docs/feature_guide/experiment_tracking/DagsHub track ML experiments: https://dagshub.com/docs/use_cases/track_ml_experiments/DagsHub connect existing repo: https://dagshub.com/docs/quick_start/connect_existing_project/MLflow docs: https://mlflow.org/docs/latest/Wine Quality dataset (UCI): https://archive.ics.uci.edu/ml/datasets/wine+qualityscikit-learn ElasticNet: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html26. Quick ReferenceTHEORY Dataset: 11 chemistry features → predict wine quality (regression) Model: ElasticNet (L1 + L2 regularized linear regression) Metrics: RMSE ↓, MAE ↓, R² ↑ = better predictionsFLOW ingest → validate → split → train → evaluate → serveCONFIG config.yaml = paths & MLflow params.yaml = alpha, l1_ratio schema.yaml = columns & targetDATA DVC tracks: data/raw and data/processed artifacts/: model, metrics, validation status, logs remain runtime outputsRUN dvc pull # optional, if remote is configured python main.py # full pipeline python app.py # web UI docker compose up # containerizedIMPROVE tune params → scale features → engineer features → try other models → log all in MLflow27. Final NotesThis repository is structured so a new user can:understand the theory behind the dataset, model, and metricstrace how every file and stage connectsset up credentials and run the training flowinspect artifacts and DagsHub MLflow resultsserve predictions through the browseriterate toward better wine quality predictions with measurable metric gainsKeep .env local, rebuild Docker after runtime changes, and monitor logs/training.log plus DagsHub MLflow for a smooth end-to-end experience.Minimal rebuild path from zero:Clone the repositoryCreate .envInstall dependencies with pip install -r requirements.txtRun dvc pull if the DVC remote is already configured; otherwise run python main.pyStart with docker compose up -d or python app.pyFor day-to-day commands, README.md and this medium.md stay aligned — use this file when you need theory and architecture, and either file for operations.Git Link: faizulkhan56/datascienceprojectDVC Link: https://dagshub.com/faizulkhan56/datascienceprojectDataset link: faizulkhan56/datasetsEnd-to-End Data Science Project — Complete Guide was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.