Machine Learning Wine Quality Prediction Project

Machine Learning project 15

Machine Learning Wine Quality Prediction Project

Build and evaluate a complete wine quality prediction workflow with reproducible Python code, explicit metrics, and honest limitations.

Explore Machine Learning training in VizagView all project ideas

Dataset and objective

The UCI Wine Quality dataset fetched by repository ID 186, containing physicochemical measurements and sensory quality scores.

Skills practised

  • Official dataset clients
  • Ordinal score regression
  • Random forests
  • Error metrics

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install pandas scikit-learn ucimlrepo
  • About 45-60 minutes to build and review

Machine Learning workflow

  1. Data: The UCI Wine Quality dataset fetched by repository ID 186, containing physicochemical measurements and sensory quality scores.
  2. Preprocessing: The official repository client returns feature and target tables, followed by a stratified training/holdout split across discrete score levels.
  3. Model: RandomForestRegressor learns nonlinear relationships between laboratory measurements and the numeric quality score.
  4. Evaluation: MAE in quality points, RMSE, and R-squared on holdout samples.

Complete Python code

Save the code as ml_wine_quality_prediction.py. The random state and data handling are included so the result can be reproduced and reviewed.

"""Predict wine-quality scores from the UCI Wine Quality dataset."""

from __future__ import annotations

from math import sqrt

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from ucimlrepo import fetch_ucirepo


def load_wine_quality():
    dataset = fetch_ucirepo(id=186)
    features = dataset.data.features.copy()
    targets = dataset.data.targets.copy()
    target = targets.iloc[:, 0]
    return features, target


def train_model(random_state: int = 42):
    x, y = load_wine_quality()
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.25, random_state=random_state, stratify=y
    )
    model = RandomForestRegressor(
        n_estimators=300,
        min_samples_leaf=2,
        random_state=random_state,
        n_jobs=-1,
    )
    model.fit(x_train, y_train)
    predictions = model.predict(x_test)
    metrics = {
        "mae": mean_absolute_error(y_test, predictions),
        "rmse": sqrt(mean_squared_error(y_test, predictions)),
        "r2": r2_score(y_test, predictions),
    }
    return model, x, y, metrics


def main() -> None:
    _, x, _, metrics = train_model()
    print("UCI Wine Quality Regression")
    print(f"Rows: {len(x):,} | Features: {x.shape[1]}")
    print(f"MAE: {metrics['mae']:.3f} quality points")
    print(f"RMSE: {metrics['rmse']:.3f}")
    print(f"R-squared: {metrics['r2']:.3f}")
    print("Quality is a sensory score; predictions are educational and not product certification.")


if __name__ == "__main__":
    main()

How the pipeline works

The official repository client returns feature and target tables, followed by a stratified training/holdout split across discrete score levels.

RandomForestRegressor learns nonlinear relationships between laboratory measurements and the numeric quality score. MAE in quality points, RMSE, and R-squared on holdout samples.

Run the project

  1. Create and activate a virtual environment.
  2. Install the dependencies with python -m pip install pandas scikit-learn ucimlrepo.
  3. Run python ml_wine_quality_prediction.py.
  4. Review every printed metric together with the limitation below; a single score never proves deployment readiness.

How to interpret the evaluation

Classification projects report class-aware metrics so majority classes do not hide weak performance. Regression projects report errors in target units and include R-squared or a simple baseline where appropriate. Always verify the split strategy matches how new data will arrive.

Accuracy, ethics, and safety limits

Sensory quality is subjective and the dataset covers specific Portuguese wines. Predictions are educational, not certification, safety testing, or commercial grading.

Ways to extend the project

Compare ordinal classification, run repeated cross-validation, inspect permutation importance, separate wine types when metadata supports it, and cite the dataset licence.

Continue learning Machine Learning

Try the next project, return to the Softenant project library, or explore the Machine Learning course in Vizag for guided data preparation, model evaluation, and portfolio feedback.