Which measurable properties of a wine predict how experts rate it? Winemakers with lab results in hand ask this all the time: which levers should I focus on, and which variables are noise? This guide shows how to answer that with regression and random forest, how to read each output, and how to avoid the traps that come with observational data.
The research question: which of a set of physicochemical features (fixed acidity, volatile acidity, citric acid, residual sugar, chlorides, free and total sulfur dioxide, density, pH, sulphates, alcohol) drive sensory quality scores, and by how much? The approach uses both linear regression (for interpretable coefficients) and random forest (for feature importance rankings), then cross-checks findings with visual comparisons across quality bins. The goal is not to build the best possible wine quality predictor. It is to identify which variables matter, which are noise, and what that means for winemakers trying to hit a target quality tier.
Here is the catch: wine lab data is usually observational, not experimental. Wines were not randomized to different alcohol levels or volatile acidity treatments. You observe naturally occurring variation, which means you can detect associations ("higher alcohol wines tend to score better") but cannot claim causation without considering confounders. Maybe high-alcohol wines come from riper grapes grown in better vineyard sites. Maybe winemakers who control volatile acidity also control a dozen other quality factors. Still, if you are looking at your own lab results and wondering which levers to focus on, this analysis gives you a data-driven starting point.
Worked Example: Ranking Lab Measures in Made-Up Wine Data
This guide is a methods tutorial that uses a small made-up example, not an analysis of a real wine dataset. It shows how two models can rank lab measures. The results show patterns in the example, not causes in real wine.
Question: In these made-up wine lab results, which measures help predict a taste score?
Inputs: Simulated data, seed 42. The script makes 360 rows with four lab measures: alcohol, acid, volatile acidity (a lab acid measure, or VA), and sugar. It sets scores from those measures and random noise, then splits the rows into 270 train and 90 test rows. A forest model ranks each measure by how much the test R-squared score drops when that measure is mixed up. R-squared is a fit score. A linear model gives another view through its fitted weights, called coefficients.
What the script builds in: alcohol raises the score by 0.55 per unit, plus an extra curved bonus above 12. VA lowers it by 0.30 per unit. Acid acts only through a curve (minus 0.08 times acid squared), so a straight-line weight cannot see it. Sugar has no effect at all. VA shares variation with acid by design: 0.45 of the acid value is built into VA. The noise has a standard deviation of 0.45.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
SEED = 42
rng = np.random.default_rng(SEED)
n = 360
# Two simulated acid measures share some variation.
alcohol = rng.normal(12.0, 0.8, n)
acid = rng.normal(0.0, 1.0, n)
volatile_acidity = 0.45 * acid + rng.normal(0.0, 0.9, n)
sugar = rng.normal(5.0, 1.8, n)
X = np.column_stack([alcohol, acid, volatile_acidity, sugar])
feature_names = ["alcohol", "acid", "volatile_acidity", "sugar"]
# A made-up score with a curved alcohol link and random noise.
y = (
5.0
+ 0.55 * (alcohol - 12.0)
- 0.30 * volatile_acidity
- 0.08 * acid**2
+ 0.12 * np.maximum(alcohol - 12.0, 0.0) ** 2
+ rng.normal(0.0, 0.45, n)
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=SEED
)
forest = RandomForestRegressor(
n_estimators=300, min_samples_leaf=3, random_state=SEED
)
forest.fit(X_train, y_train)
base_r2 = r2_score(y_test, forest.predict(X_test))
perm = permutation_importance(
forest,
X_test,
y_test,
n_repeats=30,
random_state=SEED,
scoring="r2",
)
order = np.argsort(perm.importances_mean)[::-1]
linear = LinearRegression().fit(X_train, y_train)
print(f"Simulated data, seed {SEED}")
print(f"Rows: {n}; predictors: {len(feature_names)} ({', '.join(feature_names)})")
print(f"Train rows: {len(X_train)}; test rows: {len(X_test)}")
print(f"Random forest test R-squared: {base_r2:.3f}")
print("Permutation importance on test set (mean R-squared drop):")
for i in order:
print(f" {feature_names[i]}: {perm.importances_mean[i]:.3f}")
print("Linear model coefficients (score units per input unit):")
for name, coef in zip(feature_names, linear.coef_):
print(f" {name}: {coef:.3f}")
Real output from running the script with python3:
Simulated data, seed 42
Rows: 360; predictors: 4 (alcohol, acid, volatile_acidity, sugar)
Train rows: 270; test rows: 90
Random forest test R-squared: 0.468
Permutation importance on test set (mean R-squared drop):
alcohol: 0.710
volatile_acidity: 0.177
acid: 0.029
sugar: -0.011
Linear model coefficients (score units per input unit):
alcohol: 0.610
acid: -0.044
volatile_acidity: -0.276
sugar: 0.012
Result: The forest ranked alcohol first, then VA. Its test R-squared was 0.468. The linear model gave alcohol a weight of 0.610 and VA a weight of -0.276. In this made-up set, more alcohol went with a higher score, and more VA went with a lower score when the other measures stayed fixed. The linear weights are not the built-in values, in part because the alcohol link is curved.
The permutation numbers are the drop in test R-squared when one column is shuffled, measured on only 90 rows, so they are noisy. A drop can exceed the model's R-squared (alcohol 0.710 against 0.468) because shuffling a column can push the model's R-squared below zero. Sugar had no built-in effect, and its drop (-0.011) and linear weight (0.012) are both near zero. Acid acted only through a curve: a forest can follow a curve, but the linear acid weight (-0.044) misses it, and VA shares variation with acid by design.
Limit: These data use made-up patterns. They do not show what shapes real wine scores. A winery would need to study its own data before using these results.
Checking the Quality Score Distribution
Start by plotting a histogram of quality scores. Wine quality scores can be imbalanced when they are treated as classes: in many datasets, scores span a narrow band of the full rating scale, with a heavy concentration in the middle tiers and few wines at the extremes. Check this in your own data. This matters for two reasons.
First, your model will be far better at predicting "average" wines than exceptional or terrible ones. When you train a random forest or logistic classifier on such data, it sees many examples of mediocre wine and few of great wine. Expect high overall accuracy but poor recall on the tails. If your goal is to find the next top wine or catch a spoiled batch early, you will need targeted sampling or oversampling techniques such as SMOTE.
Second, a narrow score range suggests the data may come from pre-filtered commercial wines rather than experimental batches. Winemakers rarely bottle their worst mistakes. This truncation limits variance and tends to attenuate regression coefficients: the true effect of a fault like volatile acidity might be steeper if wines that were dumped before bottling had been included. For applied winemaking that is usually fine, since you are optimizing within the commercial range. Just do not extrapolate coefficients to values outside the observed range.
Sample Size Check: The needed sample size depends on the model and the goal, so treat any simple count as a rough guide. Check the model on data it did not train on. Small datasets risk overfitting and unstable estimates; consider regularization (ridge or LASSO) or fewer predictors.
Reading the Feature Correlation Matrix
The heatmap shows Pearson correlation coefficients for all variables (predictors plus quality). First read the quality column: which features correlate most strongly, positively and negatively, with the score? Be alert to mechanically linked variables. For example, density is linked to alcohol content because ethanol is less dense than water, so a density-quality correlation may be a confounded relationship, not an independent driver.
Then check the off-diagonal cells for multicollinearity. Some chemical properties are expected to correlate with each other: fixed acidity with citric acid and with pH (pH measures acidity, so a negative correlation is expected), and free sulfur dioxide with total sulfur dioxide (free SO₂ is a subset of total). When predictors correlate strongly, regression coefficients become unstable and hard to interpret. A model might assign a large positive coefficient to one acidity measure and a large negative one to another, not because the second hurts quality, but because it is "stealing" variance already explained by the first.
For linear regression, this means: do not over-interpret individual coefficients when predictors are collinear. Overall predictions may be fine, but coefficient magnitudes and signs can swing with small changes in the data. If you are building a prescriptive model, consider ridge regression or LASSO to stabilize estimates. For causal inference, you need domain knowledge to decide which variables are upstream causes and which are downstream consequences or measurement proxies.
Random forests can be less sensitive to correlated predictors than linear coefficients, but feature importance can still be diluted across correlated predictors. If two correlated features both matter, the forest may split on either one, spreading importance across both. So do not conclude they are independent drivers without further experiments.
Reading Random Forest Feature Importance
A horizontal bar chart ranks features by permutation importance. When you shuffle a feature's values randomly (breaking its relationship with quality), how much does the model's test-set R-squared drop? The example code averages that drop over 30 shuffles on the held-out test rows. The bigger the drop, the more important the feature.
Compare this ranking to the correlation matrix. If a feature ranks high in both, it is likely a robust predictor. If a feature ranks higher in the forest than in simple correlation, it may interact non-linearly with other features or show threshold effects, which random forests capture and Pearson correlation misses. If it ranks high in correlation but low in the forest, it may be redundant given other predictors.
Here is what random forest importance does not tell you: the direction of the effect. A feature may rank high because high values are bad or because low values are good. You need coefficients or partial dependence plots to get directionality. Also, importance scores are relative, not absolute. A high importance score would not mean "this feature explains that share of quality variance". It would mean test R-squared drops by that amount when the feature is permuted, and the scale depends on the model's baseline R-squared and the other features in the model.
Interpretation Trap: Feature importance in random forests is not the same as regression coefficients. Importance measures predictive contribution; coefficients measure marginal effects holding other variables constant. A feature can have high importance but a small coefficient (because it is collinear with other features) or low importance but a large coefficient (because it is redundant given other predictors). Use both methods together.
Reading Box Plots of a Feature by Quality Score
A box plot with the feature on the y-axis and quality score on the x-axis shows whether the median shifts monotonically across quality tiers, how wide the boxes are, and how much adjacent tiers overlap. If the middle half of each group overlaps, that alone does not show how well a measure predicts scores. Look at all score patterns, or test the model on data set aside for that check.
If alcohol rises with quality, why might that be? Three plausible mechanisms, none of which can be disentangled without experiments:
- Ripeness signal: Higher alcohol comes from riper grapes with more sugar. Riper grapes also tend to have better flavor development, thicker skins (more tannins and color), and balanced acidity. Alcohol may be a proxy for overall grape quality at harvest.
- Mouthfeel and body: Ethanol adds viscosity and warmth. Expert tasters may perceive higher-alcohol wines as fuller-bodied and more complex, especially if other flaws are absent.
- Selection bias: Winemakers may invest more care (better barrels, longer aging, stricter sorting) in high-potential fruit, which also yields higher alcohol. The winemaking process, not the alcohol itself, drives quality, but alcohol co-varies with process quality.
From a winemaking perspective, do not just spike the alcohol and expect higher scores. Chaptalizing (adding sugar before fermentation) raises alcohol but will not fix under-ripe fruit or poor fermentation management. The causal lever is often upstream: harvest riper fruit, or select vineyard blocks with better sun exposure.
Volatile acidity is a different kind of variable. It is primarily acetic acid (plus minor amounts of other volatile organic acids), formed when wine is exposed to oxygen in the presence of acetic acid bacteria. At high concentrations tasters perceive a sharp, vinegar-like smell that masks fruit aromas, and at high levels it is considered a fault. The chemistry is well understood: VA formation is a symptom of poor sanitation, oxidation, or stuck fermentation. Unlike alcohol, which may be a proxy for many upstream factors, VA is a direct, measurable flaw.
A known process can make a cause seem likely. Data from real-world watching alone do not prove it, and a test that changes one factor is needed. Reducing volatile acidity would be expected to reduce the vinegar aroma, because the mechanism is direct. Winemakers can target VA reduction through better barrel hygiene, minimizing headspace in tanks, adding SO₂ to inhibit acetic acid bacteria, and ensuring complete primary fermentation.
Threshold Effects: If the variance of a fault variable shrinks at higher quality tiers, that suggests a ceiling effect: to achieve top scores you must control the fault, but controlling it alone will not guarantee a top score. It is a necessary but not sufficient condition, a gatekeeper variable.
Reading Linear Regression Coefficients
An ordinary least squares model predicting quality from all the physicochemical features gives one coefficient per feature. Each coefficient is the change in predicted quality for a one-unit increase in that feature, holding all other variables constant. If coefficients are standardized, they are comparable across features; if not, units matter (a one-unit change in alcohol percent is not the same size as a one-unit change in g/L of volatile acidity), so compare effects in realistic ranges rather than raw magnitudes.
Sulphates (potassium or calcium salts added during winemaking) act as antioxidants and antimicrobial agents. If a coefficient for them is positive, it more likely reflects their role in preserving freshness and preventing off-flavors than a direct sensory contribution. Small coefficients on correlated features like chlorides and density may be artifacts of multicollinearity rather than true causal effects.
Before you treat coefficients as decision rules, remember the caveats. First, multicollinearity inflates standard errors and destabilizes estimates: confidence intervals can be wide even if point estimates look precise. Second, a linear model adds effects unless you add terms for inputs that work together. If two features interact (sulphates matter more at high alcohol, say), the model misses it. Third, unmeasured confounders such as grape variety, vintage, barrel type, aging duration, and vineyard site will bias the coefficients if they affect both a predictor and quality.
When the direction and rough magnitude of the top effects agree across correlation analysis, random forest importance, regression, and visual inspection, and with domain knowledge, that is consilience: multiple independent lines of evidence pointing the same way. It is not proof, but it is a reasonable basis for deciding where to focus QA resources.
How to Interpret Your Results
When you run this analysis on your own wine dataset (red wine, white wine, rosé, or even beer or coffee), you will get a similar set of outputs: a distribution of scores, a correlation matrix, feature importance rankings, box plots for top features, and regression coefficients. Here is how to interpret them without falling into the observational-data trap.
Step 1: Check your sample size and balance. Is your sample large enough for the model and the goal? Is your quality distribution balanced, or are most samples mediocre with very few excellent? If your dataset is small or imbalanced, your model will overfit to noise or ignore minority classes. Consider collecting more data, stratified sampling, or regularization (ridge or LASSO) to stabilize estimates. Do not proceed with causal interpretation if your sample is underpowered.
Step 2: Look at the correlation matrix for multicollinearity. Any strong pairwise correlations? A strong link between two inputs is a reason to look closer. It does not prove that they can replace each other. Check how much the link affects the model, or fit it again without one input and see if the result shifts. With strongly linked inputs the model may assign big coefficients to one and ignore the other, or flip signs between runs. Do not interpret those coefficients as independent causal effects. Instead, group correlated predictors conceptually (for example "acidity measures" and "sulfur compounds") and interpret them as a bundle, or use domain knowledge to pick the most causally upstream variable and drop the rest.
Step 3: Compare random forest importance with correlation. If a feature ranks high in both, it is likely a robust predictor. If it ranks high in the forest but low in correlation, it may have non-linear or interaction effects, so investigate with partial dependence plots. If it ranks high in correlation but low in the forest, it may be redundant given other predictors. Use this comparison to shortlist features for experimental follow-up.
Step 4: Visualize the top features with box plots or scatter plots. Do medians shift monotonically across quality bins? Is the separation clean, or is there massive overlap? Clean separation may point to a strong relationship. Messy overlap alone does not show the feature is weak, so test the model on data set aside for that check. If you see a J-curve or U-curve (low and high values both hurt quality), the linear regression coefficient will be near zero, which is misleading. Always plot.
Step 5: Interpret regression coefficients with humility. Coefficients tell you marginal effects conditional on the other variables in the model. They do not tell you what happens if you intervene on one variable in isolation. If alcohol and winemaking quality are confounded, the alcohol coefficient conflates both effects. To move from association to causation, you need experiments: randomize wines to different alcohol levels (by varying harvest date), measure quality, and check whether the coefficient holds. Until then, treat coefficients as hypothesis generators, not decision rules.
When Observational Data Is Enough (and When It Isn't)
Most driver analyses of wine lab data are observational, not experimental. That limits causal claims, but it does not make the analysis useless. Here is when observational driver analysis is sufficient, and when you need to run an experiment.
Observational data is enough when:
- You are triaging many potential features down to a shortlist. You cannot afford to run experiments on every physicochemical feature. Run a regression plus random forest screening first, identify the top few drivers, then design experiments around those.
- The mechanism is well understood and direct. Volatile acidity is acetic acid, which gives a vinegar smell. Observational data can show whether the relationship appears in your data.
- You are building a predictive model, not a causal model. If your goal is to predict quality from lab results so you can grade wines before bottling, you do not need causation. Train the model, check it on held-out data, and deploy it.
- You want to generate hypotheses for later experiments. If a regression suggests sulphates improve quality, design an experiment: take several barrels of the same wine, add different sulphate levels, age, and blind-taste.
You need an experiment when:
- Confounding is plausible and you need a causal estimate. Alcohol may proxy for ripeness, vineyard quality, winemaker skill, or other factors. To know its isolated effect, run a controlled fermentation experiment with matched fruit.
- You are making a costly intervention decision. If you are considering a large investment in precision temperature control to reduce VA, do not rely on observational data alone. Run a pilot with and without the intervention, measure VA and quality, and calculate return on investment.
- Non-linear or interaction effects are suspected. Maybe sulphates help at low alcohol but hurt at high alcohol. Observational data plus linear regression will not catch that. You need factorial designs or response surface methodology.
- You are making claims to skeptical stakeholders. Investors, regulators, and scientists want causal evidence. "Our data shows X is associated with Y" invites the follow-up "but did you randomize?"
For winemaking, a pragmatic approach is to use observational analysis to prioritize, then confirm with small-scale experiments. Suppose your analysis points to alcohol as a top driver. Take your next batches, randomize half to earlier harvest and half to later harvest, control everything else, and measure quality. If the effect holds, you have moved from correlation toward causation. If it does not, you have learned that the observational coefficient was confounded, without wasting money scaling up a false lead.
What a Wine Dataset Can't Tell You (And What to Measure Instead)
Any single wine dataset has blind spots. It reflects one region and style. Drivers found in one style, for example high-acidity, low-alcohol wines, may not generalize to other regions, grapes, or styles. Sensory preferences vary by region and consumer segment.
Many datasets also omit key winemaking process variables: fermentation temperature, yeast strain, maceration duration, barrel type, aging time, and filtration method. These variables directly affect flavor, aroma, and mouthfeel but are not captured in a post-hoc chemical assay. If you are building a quality driver model for your own winery, include process metadata in your feature set. You may find that barrel type explains more variance than a minor acid.
Quality scores usually come from expert sensory panels, not consumer ratings. Experts prioritize balance, typicity, and complexity; consumers often prioritize fruitiness, sweetness, and smoothness. If your objective is consumer appeal, you will need consumer preference data. Run blind tastings with your target demographic, collect ratings, and rebuild the model. The drivers may shift.
Finally, chemistry data carry no information on price, branding, or bottle design, which strongly affect purchase decisions. If you are optimizing for revenue or market share, chemical composition is only one input.
Practical Applications: From Lab Results to Production Decisions
Here are three scenarios that show how to use driver analysis, with hypothetical details only.
First scenario: Suppose harvest is in two weeks, and your vineyard manager says waiting another week would raise potential alcohol but carries weather and acid-loss risk. The regression on your own historical data is the right input. Pull lab results and scores from several past vintages and run the same regression. If alcohol has a strong positive coefficient in your data, a later harvest is more justified. If it does not (perhaps your terroir favors freshness over ripeness), harvest now. Analysis of external data can generate a hypothesis; analysis of your own cellar tests whether it applies to your context.
Second scenario: Suppose your lab flags a tank with elevated volatile acidity. Is it acceptable? Compare it to your own box plots: what VA levels do your highest-scoring wines show? If none of your premium wines exceed that level, the tank probably will not compete in the premium segment. Options include blending it into a lower tier or trying remediation and re-testing.
Third scenario: Suppose you are choosing a sulphate addition rate and a regression suggests higher sulphates improve quality. Check for interaction effects first. Sulphates inhibit bacteria and oxidation, which matters most in high-risk wines (low acidity, high pH, warm climate). If your wine already has high acidity and cold fermentation, extra sulphates may offer no benefit. Use the regression to prioritize, then run a bench test: split a tank, dose halves differently, age, and blind-taste. If tasters prefer the higher dose, adopt it. If not, you have saved money and avoided over-treating.
Decision Rule: Use driver analysis to rank interventions by expected impact, then check high-impact interventions with small-scale experiments before committing to production changes. This balances speed (observational analysis is fast) with rigor (experiments confirm causation).
Your turn
Bring your own data and the question you actually need answered.
MCP AnalyticsData science by email Send us your data and your question, and we will reply. ds@mcpanalytics.ai
FAQ: Wine Quality Drivers
How do I tell which physicochemical feature has the strongest effect on wine quality?
Use several methods together. Regression coefficients give the marginal effect of each feature holding the others constant, random forest permutation importance shows predictive contribution, and box plots by quality tier show whether the separation is clean. A feature that ranks high on all three is a stronger candidate than one that ranks high on only one. None of them proves causation.
How many wine samples do I need to identify quality drivers reliably?
The needed sample size depends on the model and the goal, so treat any simple count as a rough guide. Check the model on data it did not train on. Smaller datasets risk overfitting and unstable coefficient estimates. With fewer samples, use regularization (ridge or LASSO regression) or reduce the number of predictors by dropping highly correlated features.
Can I use drivers found in one wine type to predict quality for white wines or other varietals?
No. Do not extrapolate coefficients across wine types or grape varietals. Physicochemical drivers vary with fermentation processes, varietal characteristics, and sensory expectations. Build separate models trained on samples from your target population.
Should I use linear regression or random forest for wine quality prediction?
Use both, because they answer different questions. Linear regression gives interpretable coefficients showing the marginal effect of each feature. Random forest captures non-linear relationships and interaction effects and often predicts better. Start with linear regression for understanding, then use random forest when predictive accuracy matters more than interpretability.
What is volatile acidity and why is it considered a wine fault?
Volatile acidity (primarily acetic acid) is produced when wine is exposed to oxygen or contaminated by acetic acid bacteria. At high levels it creates a sharp, vinegar-like smell that dominates other aromas. Winemakers control it by minimizing oxygen exposure, maintaining proper SO2 levels, keeping barrels and tanks sanitary, and avoiding stuck fermentations. How strongly it predicts scores in your own data is something your analysis has to show.