Predictive Modeling for Wine Ratings from Chemical Properties
Machine LearningModel answerLast updated
Build and validate a model that predicts wine ratings from chemical measurements, choosing appropriate problem framing, metrics, and feature analysis methods.
Task: Predict Wine Ratings from Chemical Measurements
You have a structured dataset containing red wine samples. Each sample includes approximately 10 chemical measurements (all numeric) and a rating score.
Target variable:
quality: Rating score ranging from 1 to 7 (integer)
Input variables (chemical properties):
fixed_acidity(float)volatile_acidity(float)citric_acid(float)residual_sugar(float)chlorides(float)free_sulfur_dioxide(float)total_sulfur_dioxide(float)density(float)pH(float)sulphates(float)alcohol(float)
Assumptions:
- The dataset contains no missing entries
- Rows represent independent samples (verify this assumption during exploration)
Your Task
Address each of the following:
-
Exploratory Analysis: Investigate the dataset structure and properties. Identify at least three specific observations (distribution patterns, relationships between variables, data quality issues, or target characteristics) and explain how each observation should influence your modeling decisions.
-
Feature Assessment: Before building a model, determine which chemical properties are likely to be predictive of wine ratings. Describe at least two different analytical techniques you would use to assess predictiveness, and explain what each technique reveals.
-
Model Development: Construct a predictive model. Your answer should clearly state:
- How you frame the prediction problem (as regression, classification, or another formulation) and your reasoning
- Your validation approach (splitting strategy or cross-validation design)
- Which evaluation metrics you use and why they are appropriate
-
Feature Interpretation: After training your model, how would you identify which chemical properties actually contribute to predictions? Describe a method suited to your chosen model type and discuss potential issues that could lead to incorrect conclusions (such as correlated features, data contamination, or artifacts of certain importance calculations).
Deliverable: Present your reasoning and methodology in a structured write-up. You may include code snippets or pseudocode (Python with pandas/scikit-learn) if helpful.
Hints
Hint 1
Check whether your data contains exact duplicate rows—this violates independence assumptions and can artificially inflate performance if splits aren't handled carefully.
Hint 2
The target distribution is likely imbalanced, with most samples concentrated in the middle rating values. This affects both metric selection and validation strategy.
Hint 3
Consider that rating scores have inherent ordering (a 6 is closer to a 5 than to a 3), which standard classification ignores but could be leveraged.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Wine Rating Prediction
This problem evaluates your ability to execute a complete modeling workflow on tabular data—from exploration through interpretation—while making principled choices at each stage. Strong responses connect every exploratory finding directly to a modeling decision.
1. Exploratory Analysis: Key Findings
When examining this dataset (typically ~1,600 samples), you should discover several patterns that directly impact modeling:
| Observation | What the Data Shows | Impact on Modeling |
|---|---|---|
| Imbalanced target distribution | Approximately 80% of samples cluster in two middle rating values (often 5 and 6), while extreme ratings (1, 2, 7) have very few examples | Simple accuracy is deceptive—predicting the most common class achieves ~40% accuracy. Require stratified cross-validation and metrics sensitive to ordering. Expect poor performance on rare classes. |
| Skewed feature distributions with extreme values | Variables like residual_sugar, chlorides, and sulfur dioxide measurements show long right tails with outliers | Apply log transformations for linear models to reduce skew, or use tree-based methods which handle this naturally. Avoid removing outliers without chemical justification—they may represent valid wine samples. |
| Strong multicollinearity | fixed_acidity correlates highly with citric_acid and density; pH is inversely correlated with fixed_acidity (~-0.68); density and alcohol show negative correlation; sulfur dioxide measurements are correlated | Apply regularization (Ridge/Lasso) to stabilize linear models. Recognize that feature importances will be distributed across correlated features, complicating interpretation. |
| Non-linear relationships | sulphates shows positive association with quality up to ~0.8 g/L, then plateaus; volatile_acidity's negative effect is strongest at high concentrations | Tree-based models or spline features in linear models will capture these patterns better than plain linear terms. |
| Duplicate observations | The standard dataset contains ~240 exact duplicate rows | This violates the independence assumption. Random train/test splits place duplicates in both sets, creating data leakage and inflated metrics. Either remove duplicates or use grouped cross-validation. |
The duplicate detection distinguishes thorough analysis from superficial work and directly addresses the independence assumption in the problem statement.
2. Pre-Model Feature Assessment
Use multiple complementary approaches to assess predictive potential:
A. Spearman Rank Correlation
- Robust to outliers and monotonic transformations
- Captures monotonic relationships with the ordinal target
- Typical findings:
alcohol(+0.48),-0.38),volatile_acidity(sulphates(+0.38),+0.21)citric_acid( - Low correlation features:
residual_sugar,free_sulfur_dioxide,pH(all near zero)
B. Mutual Information
- Detects non-monotonic and non-linear dependencies that correlation misses
- Usually confirms the same top features but may reveal additional signal in
total_sulfur_dioxideordensity - More computationally expensive but catches threshold effects
C. Visual Analysis
- Box plots grouped by rating level show monotonic trends and threshold effects
- Bin continuous features and plot mean rating per bin to visualize relationships
D. Domain Knowledge
volatile_acidityprimarily represents acetic acid, which creates vinegar-like off-flavors—negative association expectedsulphatesserve as antimicrobial preservativesalcoholcorrelates with grape ripeness and wine bodydensityis largely determined by alcohol and sugar content—likely redundant rather than independently informative
Caveat: Univariate analysis misses interaction effects and double-counts correlated features. Treat these as hypotheses requiring validation in the full model.
3. Model Development
Problem Framing
The target is ordinal: rating 6 is closer to 7 than to 3, but the intervals may not be equal. Each standard framing has weaknesses:
- Multiclass classification: Ignores ordering and struggles with rare classes
- Regression: Respects ordering but produces non-integer predictions and assumes equal spacing
Recommended approach: Use regression with learned thresholds. Train a gradient boosting regressor to output continuous predictions, then determine optimal cutpoints that map predictions to integer classes. Tune these thresholds on out-of-fold predictions to maximize ordinal agreement metrics. This combines regression's ability to interpolate with classification's discrete outputs.
Alternative: Ordinal logistic regression (proportional odds model) provides an interpretable baseline with proper ordinal treatment.
Validation Strategy
- Remove or group duplicates to prevent leakage
- Stratified 5-fold cross-validation, repeated 3-5 times to reduce noise from the modest sample size
- Nested cross-validation or hold-out test set for hyperparameter tuning
- Fit all preprocessing (scaling, transformations, threshold selection) only on training folds
Evaluation Metrics
- Mean Absolute Error (MAE): Primary metric; interpretable as "average rating points off"
- Quadratic Weighted Kappa (QWK): Measures ordinal agreement; penalizes large errors more heavily
- Exact accuracy and within-±1 accuracy: Stakeholder-friendly metrics
- Per-class confusion matrix: Shows performance breakdown, revealing poor recall on extreme ratings
Expected Performance:
- Baseline (mean prediction): MAE ≈ 0.68
- Regularized linear model: MAE ≈ 0.50
- Gradient boosting: MAE ≈ 0.42-0.47, exact accuracy ≈ 60-65%, QWK ≈ 0.5-0.6
Claims of >85% accuracy typically indicate duplicate leakage.
Implementation Outline
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedGroupKFold
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, cohen_kappa_score
# Load and prepare data
df = pd.read_csv("wine_data.csv")
X = df.drop(columns="quality")
y = df["quality"].values
# Create groups for duplicate samples
groups = pd.util.hash_pandas_object(df, index=False).values
# Cross-validation with duplicate handling
cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)
predictions, actuals = [], []
for train_idx, test_idx in cv.split(X, y, groups):
X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]
y_train, y_test = y[train_idx], y[test_idx]
# Train regressor
model = HistGradientBoostingRegressor(
learning_rate=0.05,
max_leaf_nodes=15,
min_samples_leaf=20,
l2_regularization=1.0
)
model.fit(X_train, y_train)
# Get continuous predictions
pred_continuous = model.predict(X_test)
# Convert to discrete ratings using learned thresholds
# (fit thresholds on training fold predictions)
thresholds = optimize_thresholds(
model.predict(X_train), y_train
)
pred_discrete = discretize_predictions(pred_continuous, thresholds)
predictions.extend(pred_discrete)
actuals.extend(y_test)
# Evaluate
print(f"MAE: {mean_absolute_error(actuals, predictions):.3f}")
print(f"QWK: {cohen_kappa_score(actuals, predictions, weights='quadratic'):.3f}")
4. Feature Importance Interpretation
Method Selection
For gradient boosting models, use permutation importance on held-out data:
- Randomly shuffle each feature independently in the test set
- Measure the decrease in model performance
- Features whose shuffling causes large performance drops are important
This is model-agnostic and reflects actual predictive contribution rather than tree structure artifacts.
Common Pitfalls
-
Impurity-based importances (Gini, split count) are biased toward high-cardinality and continuous features, and don't reflect actual predictive power
-
Multicollinearity splits importance across correlated features.
fixed_acidityandcitric_acidmay each show moderate importance when their combined effect is large. Solution: examine groups of correlated features together -
Data leakage: Computing importance on training data overstates the contribution of overfit features
-
Confounding: A feature may appear important because it correlates with the true causal factor rather than being directly predictive
-
SHAP values provide more granular insights (feature effects per sample, interaction detection) but are computationally expensive for large datasets
Recommended approach: Use permutation importance as the primary method, supplemented by partial dependence plots to visualize the direction and shape of feature effects, and validate that top features align with domain expectations.