Predicting Red Wine Quality Ratings
Medium · Machine Learning · Data Scientist · Technical Screen
Prompt
You are handed a clean CSV file of red wine laboratory measurements with zero missing entries. Each row represents one wine sample (assumed i.i.d. unless your exploratory checks uncover evidence to the contrary).
- Target column:
quality— an integer sensory score from1to7. - Predictor columns: roughly a dozen continuous numeric chemistry measurements, including
fixed_acidity,volatile_acidity,citric_acid,residual_sugar,chlorides,free_sulfur_dioxide,total_sulfur_dioxide,density,pH,sulphates, andalcohol.
Walk through how you would design, validate, and interpret a predictive model for quality across four stages (optionally illustrating your workflow with pandas and scikit-learn code):
- Exploratory data analysis (EDA): What checks would you run first (such as target balance, heavy tails, correlated feature clusters, non-linear relationships, or duplicate records), and how would at least three specific findings change your modeling pipeline?
- Pre-model signal assessment: Before fitting a final model, which chemical predictors would you expect to carry strong signal for
quality, and what distinct techniques (at least two—for example, rank correlation, mutual information, quantile response curves, or wine-chemistry domain knowledge) would you combine to evaluate them without leaking validation data? - Problem framing, validation, and metrics: Explain whether you would formulate
qualityprediction as continuous regression, standard multiclass classification, or ordinal regression/classification (and why), alongside your cross-validation / splitting scheme and primary evaluation metrics. - Post-model feature attribution: Once your model is trained, how would you measure which variables genuinely drive held-out performance, and what interpretation pitfalls (such as multicollinearity, data leakage, or bias in tree split-impurity scores) must you guard against?
Scope & Expectations
- Actionable EDA & leakage hygiene: Tie distributional findings (rare extreme ratings, skewed concentrations, collinear acid/density variables, duplicate chemistries) directly to preprocessing and data-splitting choices.
- Principled ordinal framing: Contrast unordered classification, plain regression, and ordinal approaches on an imbalanced
1–7integer scale, pairing the chosen formulation with metrics that respect rating distance. - Rigorous validation & post-hoc interpretation: Keep all transformations and threshold tuning strictly inside training folds, and select model-appropriate held-out attribution methods that account for correlated predictors.
Step-by-step walkthrough
Explore the data: turn every EDA finding into a modeling choice
Good exploratory data analysis (EDA) is not a gallery of plots—every check asks: "How does what I see here change my preprocessing, model family, or validation split?" Five quick
pandaschecks surface the structure of red-wine physicochemical data:import pandas as pd df = pd.read_csv("wine.csv") X = df.drop(columns="quality") y = df["quality"] print(y.value_counts().sort_index()) # 1) class counts and missing grades print(X.describe(percentiles=[0.01, 0.5, 0.99]).T) # 2) scales and extreme tails print(X.skew().sort_values(ascending=False)) # 3) right-skewed concentrations print(X.corr(method="spearman").round(2)) # 4) collinear chemistry clusters print(df.duplicated().sum()) # 5) exact duplicate rows print(X.duplicated(keep=False).sum()) # identical chemistry, check label agreementFive concrete findings typical of red-wine chemistry data and the exact decisions they drive:
Illustrative target distribution (N = 1,600 wines on a 1-7 scale): Grade 1: 0 | Grade 2: 10 | * Grade 3: 50 | *** Grade 4: 680 | ********************************** Grade 5: 640 | ******************************** Grade 6: 200 | ********** Grade 7: 20 | *- Severe target imbalance concentrated in the middle (
4and5hold 82.5% of rows): Always predicting the mode (4) achieves680 / 1,600 = 42.5%accuracy, and always predicting the median (5) achieves a Mean Absolute Error (MAE) of(10*3 + 50*2 + 680*1 + 0 + 200*1 + 20*2) / 1,600 = 1,050 / 1,600 = 0.656grade points. Decision: never rely on raw accuracy, benchmark every model againstMAE = 0.656, use stratified cross-validation, and avoid naive rounding that erases rare grades (2and7). - Heavy right skew in concentration features (
residual_sugar,chlorides,free_sulfur_dioxide,total_sulfur_dioxide,sulphates): Most wines are dry and low-chloride while a small tail has 5–10x the median level. Decision: applynp.log1p+StandardScalerinside linear-model pipelines so a handful of sweet wines do not dominate regression slopes; keep valid extreme wines rather than deleting them (only drop physically impossible entries like negative concentrations orpH > 14). - Collinear chemistry clusters:
fixed_acidity,citric_acid,pH, anddensitymove together (higher acid lowerspHand raisesdensity, while higheralcohollowersdensitybecause ethanol is less dense than water), andfree_sulfur_dioxideis part oftotal_sulfur_dioxide. Decision: use regularized linear models (Ridge) or tree ensembles for stability, consider domain ratios likefree_sulfur_dioxide / total_sulfur_dioxide, and evaluate feature importance on correlated groups rather than single columns alone. - Monotonic but saturating non-linear trends: Plotting mean
qualityacross 10 equal-sized bins (deciles) of each variable typically showsalcoholclimbing steadily, whereassulphateshelps up to a moderate level and then plateaus or dips. Decision: include a non-linear tree ensemble (HistGradientBoostingRegressor) alongside an interpretable linear/ordinal baseline. - Duplicate rows violate the i.i.d. assumption: Real red-wine tables (such as the classic 1,599-row physicochemical dataset, where 240 rows—15%—are exact duplicates) often contain repeat measurements of the same batch. Decision: deduplicate exact rows or group identical
Xvectors into the same cross-validation fold so copies never leak across train and test; if identicalXrows have differentqualitylabels, their spread estimates the human-taster noise ceiling no model can beat.
- Severe target imbalance concentrated in the middle (
Screen feature usefulness before modeling (without leaking)
No single univariate metric catches every pattern, so combine four complementary lenses (computed on training data only!):
- Spearman rank correlation (linear correlation computed on sorted ranks instead of raw values): captures any rising or falling monotonic trend without letting one extreme outlier distort the score. For instance, on
x = [1, 2, 3, 4, 100]andy = [1, 2, 3, 4, 5], Pearson correlation drops to0.725, whereas Spearman is1.00. - Mutual information (MI) (
sklearn.feature_selection.mutual_info_regression): measures how much knowing a feature reduces uncertainty aboutqualityacross any functional shape—including U-shaped "sweet spot" curves where both too little and too much hurt quality (where Spearman can be near0). Compare each feature's MI against the MI of a randomly shuffled shadow column to see what clears small-sample noise. - Decile mean-target profiles: split each feature into 10 quantile bins and inspect
mean(quality) ± standard_errorper bin to see both effect size and curve shape. - Enology (wine chemistry) domain reasoning:
alcohol(+): reflects riper grapes, fuller body, and stronger flavor extraction—typically the strongest positive predictor.volatile_acidity(-): primarily acetic acid, which smells like vinegar at elevated levels—typically the strongest negative predictor.sulphates(+, saturating) &citric_acid(+): antimicrobial/antioxidant protection and perceived freshness.density(redundant): largely a physical consequence ofalcohol,residual_sugar, andfixed_acidity, so its standalone correlation largely vanishes oncealcoholis controlled for.
Anti-leakage rule: use pre-model screening to build intuition and catch data bugs. If you drop or select columns algorithmically, do that inside each cross-validation training fold—filtering features on the full CSV before splitting leaks validation labels into model selection.
- Spearman rank correlation (linear correlation computed on sorted ranks instead of raw values): captures any rising or falling monotonic trend without letting one extreme outlier distort the score. For instance, on
Frame the target: why ordinal regression beats plain classification
qualitytakes ordered integer values on1..7. Comparing the three candidate framings shows why ordinal modeling fits best:Framing Uses grade order? Handles rare grades (2, 7)? Valid integer output? -------------------------------- ------------------ ---------------------------- --------------------- Plain multiclass classification No (2 vs 7 costs Poorly (only 10-20 rows in Yes same as 6 vs 7) extreme classes) Regression + naive round(y_hat) Yes Shrinks toward mean (~4.5), Yes (after clipping) rarely predicts 2 or 7 Regression + tuned cut points Yes Yes (cut points adjust for Yes (or cumulative-logit ordinal) shrinkage on training folds)- Why plain classification falls short: Cross-entropy and accuracy treat class labels as unordered names, penalizing a 1-point miss (
6vs7) identically to a 5-point miss (2vs7), while starving rare grades of training examples. - Chosen approach: Train a gradient-boosted regressor (
HistGradientBoostingRegressor) to predict a continuous quality score—pooling statistical signal across all 1,600 ordered ratings and capturing non-linearities and feature interactions—then map scores to integer grades using ordered cut points (theta_1 < theta_2 < ...) tuned inside each training fold, benchmarked against a cumulative-logit ordinal model (P(quality <= k | x) = sigmoid(theta_k - w · x)) andRidgeregression.
See why raw accuracy fails on a 10-wine mini-example with true grades
[4, 4, 4, 4, 5, 5, 5, 5, 6, 6]:True grades: 4 4 4 4 5 5 5 5 6 6 Model A predicts: 4 4 4 5 4 5 5 6 5 6 -> Accuracy = 6/10 (60%), MAE = 4/10 = 0.40 Model B predicts: 4 4 4 6 6 5 5 4 4 6 -> Accuracy = 6/10 (60%), MAE = 6/10 = 0.60 ^ ^ off by 2 grades! off by 2 grades!Both models get 6 out of 10 exact matches, yet Model A never misses by more than 1 point while Model B makes wild 2-grade errors.
- Why plain classification falls short: Cross-entropy and accuracy treat class labels as unordered names, penalizing a 1-point miss (
Design a leak-free validation strategy and ordinal metrics
Validation strategy:
- Deduplicate or group identical chemistries: drop exact duplicates (
df.drop_duplicates()), or assign identicalXvectors a sharedchem_idand split withStratifiedGroupKFoldwhen different tasters graded the same wine. - Repeated stratified 5-fold cross-validation (
RepeatedStratifiedKFold(n_splits=5, n_repeats=3)): on 1,600 rows with only 20 grade-7 wines, a single 80/20 split puts just ~4 grade-7 wines in validation. Repeating 5-fold stratified CV gives stablemean ± stdestimates across 15 folds (merging sparse tails like<= 3for the stratification key if any grade has fewer than 5 rows). - Fit every step inside the fold: log transforms, scaling, hyperparameters, and ordinal cut points must all be fit strictly on training folds (using
Pipelineand nested inner splits).
Evaluation metrics:
- Primary — MAE (
mean_absolute_error): measured in grade points on the final integer predictions (0.40vs baseline0.656), easy to explain to stakeholders. - Primary ordinal agreement — Quadratic Weighted Kappa (QWK): measures agreement beyond chance (
1.0= perfect,0.0= random agreement matching marginal histograms) with squared error weightsw_{i,j} = (i - j)^2 / (K - 1)^2. - Diagnostics: within-1-grade accuracy (
P(|y - y_hat| <= 1)) and per-grade confusion matrix / rare-grade recall (grade >= 6andgrade <= 3).
Hand-computed QWK on the 10-wine example above over active grades
{4, 5, 6}(w = 0for exact,0.25for off-by-1,1.0for off-by-2):Model A confusion matrix O (rows=true 4,5,6; cols=pred 4,5,6) Chance matrix E = row_sum * col_sum / 10 pred 4 5 6 row_sum pred 4 5 6 true 4 [ 3, 1, 0 ] 4 true 4 [ 1.6, 1.6, 0.8 ] true 5 [ 1, 2, 1 ] 4 true 5 [ 1.6, 1.6, 0.8 ] true 6 [ 0, 1, 1 ] 2 true 6 [ 0.8, 0.8, 0.4 ] col_sum 4 4 2 10 Weighted observed penalty = 0.25 * (1 + 1 + 1 + 1) + 1.0 * (0 + 0) = 1.0 Weighted expected penalty = 0.25 * (1.6 + 1.6 + 0.8 + 0.8) + 1.0 * (0.8 + 0.8) = 1.2 + 1.6 = 2.8 QWK(Model A) = 1 - 1.0 / 2.8 = 0.643 (whereas Model B gets 1 - 2.5 / 3.3 = 0.242!)import numpy as np def quadratic_weighted_kappa(y_true, y_pred, labels): """Compute Quadratic Weighted Kappa from scratch for ordered integer labels.""" k = len(labels) pos = {label: idx for idx, label in enumerate(labels)} observed = np.zeros((k, k), dtype=float) for truth, pred in zip(y_true, y_pred): observed[pos[truth], pos[pred]] += 1.0 row_totals = observed.sum(axis=1) col_totals = observed.sum(axis=0) expected = np.outer(row_totals, col_totals) / observed.sum() idx = np.arange(k, dtype=float) weights = (idx[:, None] - idx[None, :]) ** 2 / ((k - 1) ** 2) return float(1.0 - (weights * observed).sum() / (weights * expected).sum()) def scores_to_grades(scores, cutoffs, min_grade): """Map continuous predictions to integer grades using sorted cutoffs.""" return min_grade + np.searchsorted(cutoffs, scores, side="right")- Deduplicate or group identical chemistries: drop exact duplicates (
End-to-end Python modeling outline (pandas + scikit-learn)
Below is a clean, leak-free modeling outline comparing a
log1p + Ridgelinear baseline againstHistGradientBoostingRegressor, tuning ordinal cutoffs strictly inside each training fold before scoring the held-out fold:import numpy as np import pandas as pd from sklearn.base import clone from sklearn.ensemble import HistGradientBoostingRegressor from sklearn.linear_model import Ridge from sklearn.metrics import cohen_kappa_score, mean_absolute_error from sklearn.model_selection import StratifiedKFold from sklearn.pipeline import make_pipeline from sklearn.preprocessing import FunctionTransformer, StandardScaler SKEWED_COLS = [ "residual_sugar", "chlorides", "free_sulfur_dioxide", "total_sulfur_dioxide", "sulphates", ] def log_transform_skewed(df_in): out = df_in.copy() for col in SKEWED_COLS: out[col] = np.log1p(out[col]) return out def tune_cutoffs_coordinate_search(scores, y_true, min_grade, max_grade): """Coordinate search on training-fold out-of-bag/inner predictions to minimize MAE.""" cutoffs = np.arange(min_grade + 0.5, max_grade, 1.0) for _ in range(3): for idx in range(len(cutoffs)): lo = cutoffs[idx - 1] + 0.05 if idx > 0 else min_grade - 0.5 hi = cutoffs[idx + 1] - 0.05 if idx + 1 < len(cutoffs) else max_grade + 0.5 grid = np.linspace(lo, hi, 41) best_c, best_mae = cutoffs[idx], np.inf for candidate in grid: trial = cutoffs.copy() trial[idx] = candidate preds = min_grade + np.searchsorted(trial, scores, side="right") mae = np.mean(np.abs(y_true - preds)) if mae < best_mae: best_c, best_mae = candidate, mae cutoffs[idx] = best_c return cutoffs def evaluate_pipeline(df_path): df = pd.read_csv(df_path).drop_duplicates().reset_index(drop=True) X = df.drop(columns="quality") y = df["quality"].to_numpy() min_g, max_g = int(y.min()), int(y.max()) candidates = { "ridge_baseline": make_pipeline( FunctionTransformer(log_transform_skewed), StandardScaler(), Ridge(alpha=1.0), ), "hist_gbdt": HistGradientBoostingRegressor( learning_rate=0.05, max_iter=300, min_samples_leaf=20, random_state=0 ), } outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) for name, base_model in candidates.items(): oof_preds = np.zeros_like(y) for train_idx, val_idx in outer_cv.split(X, y): X_tr, y_tr = X.iloc[train_idx], y[train_idx] X_va = X.iloc[val_idx] # Inner out-of-fold scores strictly inside X_tr to learn ordinal cutoffs inner_cv = StratifiedKFold(n_splits=4, shuffle=True, random_state=0) inner_scores = np.zeros(len(y_tr), dtype=float) for in_tr, in_va in inner_cv.split(X_tr, y_tr): m_in = clone(base_model).fit(X_tr.iloc[in_tr], y_tr[in_tr]) inner_scores[in_va] = m_in.predict(X_tr.iloc[in_va]) cutoffs = tune_cutoffs_coordinate_search(inner_scores, y_tr, min_g, max_g) fitted = clone(base_model).fit(X_tr, y_tr) oof_preds[val_idx] = min_g + np.searchsorted(cutoffs, fitted.predict(X_va), side="right") mae = mean_absolute_error(y, oof_preds) qwk = cohen_kappa_score(y, oof_preds, weights="quadratic") within_1 = np.mean(np.abs(y - oof_preds) <= 1) print(f"{name:15s} | MAE={mae:.3f} | QWK={qwk:.3f} | Within-1={within_1:.3f}")Measure post-model feature importance and avoid classic traps
Once the final model is validated, measure which variables actually drive its held-out accuracy using methods aligned with tree ensembles and pipelines:
- Held-out permutation importance (
sklearn.inspection.permutation_importanceon each validation fold): randomly shuffle one column inX_val, keep the fitted model fixed, and record how much validation MAE increases. Unlike training-set metrics, a feature that only memorized noise scores<= 0on held-out folds. - Grouped (cluster) permutation & drop-column retraining: shuffle correlated chemistry clusters (
["fixed_acidity", "citric_acid", "pH", "density"]and["free_sulfur_dioxide", "total_sulfur_dioxide"]) together using the same row permutation, and confirm by retraining without that cluster (drop-column importance). - TreeSHAP attributions: decompose each wine's prediction into per-feature directional pushes, showing how
alcohollifts quality whilevolatile_aciditypulls it down.
Watch out for four textbook interpretation pitfalls:
- Collinearity dilutes single-column importance: Suppose
y = x + noisewithVar(x) = 1. In Model A (y_hat = x), shufflingxraises MSE by2 * Var(x) = 2.0. In Model B with two identical features (y_hat = 0.5 * x_1 + 0.5 * x_2), shufflingx_1alone changes predictions by0.5 * (x_1' - x_1)and raises MSE by only2 * (0.5^2) * Var(x) = 0.5—a 4x underestimate, and0.5 + 0.5 = 1.0is still half of2.0! Shuffling[x_1, x_2]together restores the full2.0and also avoids evaluating the model on chemically impossible combinations (like high acid + high pH). - Bias in tree impurity importance (MDI /
feature_importances_): Standard tree split-gain importance is computed on training splits, so it systematically inflates high-cardinality continuous features that split noise deep in the tree. Always rank on held-out folds instead. - Data leakage disguised as a "super-feature": If a single variable accounts for 80% of held-out importance, verify immediately that it was measured before tasting and was not derived from cellar pricing or tier labels assigned after grading.
- Associational vs causal reading:
alcoholranking #1 means higher-alcohol wines in this sample came from riper, higher-quality grapes—not that pouring pure ethanol into a vat causes quality to rise.
import numpy as np def grouped_permutation_importance(predict_fn, X_val, y_val, feature_groups, n_repeats=10, seed=0): """Measure validation MAE increase when correlated column groups are shuffled together.""" rng = np.random.default_rng(seed) baseline_mae = float(np.mean(np.abs(y_val - predict_fn(X_val)))) importances = {} for group_name, col_indices in feature_groups.items(): deltas = [] for _ in range(n_repeats): X_shuffled = X_val.copy() perm = rng.permutation(len(X_val)) X_shuffled[:, col_indices] = X_val[perm][:, col_indices] shuffled_mae = float(np.mean(np.abs(y_val - predict_fn(X_shuffled)))) deltas.append(shuffled_mae - baseline_mae) importances[group_name] = float(np.mean(deltas)) return importances- Held-out permutation importance (
Intuition & how it works
Predicting a 1–7 wine quality score from ~10 lab measurements is like predicting a gymnastics judge's score from jump height, spin rate, and landing angle: the target is an ordinal variable (ordered whole numbers where 6 is much closer to 7 than 2 is, even if intervals between grades are not perfectly uniform), and the inputs form overlapping physical groups (just as acidity, citric acid, pH, and density echo one another in wine chemistry). The winning strategy connects every step in one chain: explore the data to spot skew, duplicates, and rare grades; predict a continuous score with a non-linear tree ensemble (HistGradientBoostingRegressor) plus ordinal cut points (sorted thresholds tuned on training folds to map continuous scores back to integer grades 1..7); validate with leak-free stratified cross-validation; and measure feature usefulness on held-out folds across correlated feature groups.
Simpler shortcuts fail at each stage. Treating 1–7 as unordered multiclass labels throws away grade order (punishing 6 vs 7 identically to 2 vs 7) and starves rare grades (2 and 7) of training data, while scoring with plain accuracy rewards a trivial model that guesses 4 every time (42.5% accurate when 680 of 1,600 wines are 4s). Meanwhile, random train/test splits let duplicate wine rows leak across folds, and reading default tree split-gain (feature_importances_) misleads both when continuous columns overfit training noise and when correlated acids split credit between columns.
Walk through a concrete 10-wine mini-example with true grades [4, 4, 4, 4, 5, 5, 5, 5, 6, 6] to see why ordinal framing and metrics matter:
1. Model A predicts [4, 4, 4, 5, 4, 5, 5, 6, 5, 6] (6 exact hits, four 1-grade misses).
2. Model B predicts [4, 4, 4, 6, 6, 5, 5, 4, 4, 6] (6 exact hits, two 1-grade misses and two 2-grade misses).
3. Raw accuracy ties them at 60%, yet Mean Absolute Error (MAE) (average absolute grade difference |true - pred|) separates Model A (0.40) from Model B (0.60), and Quadratic Weighted Kappa (QWK) (chance-corrected agreement weighted by squared grade distance) jumps from 0.242 on Model B to 0.643 on Model A.
Key points
- Action-oriented EDA: Check five concrete signals—middle-heavy target imbalance (benchmark against constant-median
MAE = 0.656), right-skewed concentrations (np.log1pfor linear models), collinearity (strong correlation among input variables likefixed_acidity,citric_acid,pH, anddensity), curved/saturating feature effects, and exact duplicate rows (~15% in standard red-wine datasets) that break the i.i.d. assumption (independent and identically distributed samples). - Multi-lens pre-model feature screening: Combine Spearman rank correlation (correlation on sorted ranks, immune to single outliers and sensitive to monotonic trends), mutual information (a measure of general statistical dependence that catches U-shaped sweet spots), decile mean-quality plots, and wine-chemistry domain logic (
alcoholpositive, vinegar-likevolatile_aciditynegative)—always inside training data so validation folds never leak. - Ordinal problem framing: Pairing gradient-boosted regression (or a cumulative-logit model, which models
P(quality <= k | x)with shared feature weights and ordered intercepts) with training-fold-tuned cut points preserves grade ordering, shares signal into scarce extreme grades, and fixes regression's shrinkage toward the mean. - Leak-free validation & ordinal metrics: Deduplicate or group identical-chemistry wines (
StratifiedGroupKFold), use repeated stratified 5-fold cross-validation with every transform and cutoff fit strictly inside training folds, and report MAE + QWK + within-1-grade accuracy + rare-grade recall alongside baselines. - Post-model importance & traps: Use held-out permutation importance (measuring how much validation error worsens when a feature is shuffled) together with grouped-cluster permutation, drop-column refits, and SHAP values (per-sample additive feature attributions), avoiding training-set impurity importance (MDI) (total split-criterion reduction inside trees, which favors noisy continuous columns) and causal misinterpretation.
Common mistakes
- Using classification accuracy on an imbalanced 1–7 rating: Predicting the majority grade looks respectable on accuracy while failing completely on premium (
6–7) and faulty (2–3) wines, and treats off-by-1 and off-by-4 errors identically. - Naively rounding
np.rint(y_pred)on imbalanced targets: Least-squares and L1 regressors pull predictions toward the4–5center, so grades2and7are almost never predicted unless cut points are tuned on training folds. - Splitting randomly before checking
df.duplicated(): Identical rows landing in both train and validation artificially inflate validation scores, especially for flexible tree ensembles. - Fitting
StandardScaler, feature selection, or cut points on the full dataset before CV: Any statistic computed using validation rows causes data leakage (using held-out test information during training) and optimistic error estimates. - Dropping features with tiny single-column permutation importance in a collinear cluster: Two nearly redundant variables (or
acids + pH + density) back each other up when shuffled one at a time; shuffle the cluster together before concluding the chemistry signal is unimportant. - Confusing predictive importance with a causal lever: Seeing
alcoholat the top of SHAP or permutation charts reflects grape ripeness and harvest conditions in observational data, not a license to add alcohol directly to low-grade wine.
Follow-up questions
- How would your approach change if the business only wanted to identify reserve-grade wines (quality >= 6)? Re-frame or threshold specifically for the binary event
quality >= 6(which represents220 / 1,600 = 13.75%of wines in the illustrative distribution). You can either train a calibrated binary classifier (y >= 6) or keep the richer ordinal/regression score (which still learns from the distinction between2,3,4, and5!) and tune a single decision threshold on training folds to hit the business's target precision/recall trade-off, evaluating with PR-AUC (area under the precision-recall curve) and expected profit per bottle. - How would you verify whether a model trained on red wines transfers to white wines or a newly onboarded vineyard region? Treat deployment to a new wine style or region as covariate and concept shift (changes in input chemistry distributions and in how chemistry maps to human scores, since white wines have far higher
residual_sugarandtotal_sulfur_dioxidenorms than reds). Run adversarial validation—train a classifier to distinguish old rows (0) from new rows (1), where a high ROC-AUC flags shifted chemistry—and require a small blind-tasted labeled sample from the new source (or region-grouped cross-validationGroupKFoldacross wineries) before trusting predictions in production. - How could you provide a well-calibrated uncertainty interval or grade distribution alongside each wine prediction? For a continuous quality model, apply split conformal prediction: compute out-of-fold absolute residuals
r_i = |y_i - y_hat_i|on held-out calibration data, take their 90th percentileq_90, and output[y_hat - q_90, y_hat + q_90], which guarantees ~90% finite-sample coverage on exchangeable future wines without distributional assumptions (or combine conformal calibration with 5th/95th-percentile quantile boosting so interval width adapts to unusual wines). For a cumulative-logit ordinal model, return the full calibrated probability vectorP(quality = k | x)across grades1..7and check calibration via reliability diagrams.
Follow-up questions
- How would your approach change if the business only wanted to identify reserve-grade wines (quality >= 6)?
- How would you verify whether a model trained on red wines transfers to white wines or a newly onboarded vineyard region?
- How could you provide a well-calibrated uncertainty interval or grade distribution alongside each wine prediction?
Similar questions
- Recruiter Screen Behavioral Prompts
- Presenting Your Engineering Career Arc and Quantified Impact
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning