Blog

Inspect milk quality using machine learning

Screen milk quality from routine product observations

This three-class model combines pH, temperature, colour and four binary quality observations to estimate whether a sample matches the dataset’s high-, medium- or low-quality patterns. The example shows how classification can support triage in a dairy quality workflow while keeping release decisions with validated laboratory and food-safety procedures.

1,059labelled records
3quality classes
96.7%testing accuracy
83unique input combinations

Dairy plants need rapid, consistent ways to prioritize samples for review, but product release and food-safety decisions require validated measurement methods and traceable quality procedures. This example demonstrates a compact classifier that converts seven recorded attributes into three probabilities and a suggested quality class.

1. Industrial challenge

This is a multiclass classification problem. For each sample, the network returns probabilities for high_quality, medium_quality and low_quality; the largest probability determines the suggested class.

Prioritize quality checksUse a consistent preliminary score to identify samples that deserve faster confirmatory analysis.
Standardize triageCombine several recorded attributes through one documented classification rule.
Support traceabilityStore input values, class probabilities and the model version alongside each screening decision.

Potential users include dairy quality managers, food technologists, laboratory supervisors, production managers, process engineers and digital-quality teams.

Dairy qualityFood technologyLaboratory operationsProduction managementDigital quality
Scope of this example. The model is a demonstration classifier for preliminary screening. It does not measure microbiological safety, adulteration, shelf life or regulatory compliance and must not be used as an automatic batch-release system.

2. Data set

The downloadable milkquality.csv contains 1,059 observations, seven inputs and the categorical target grade. There are no missing values in the published file.

VariableMeaning in the datasetType / unitObserved range
pHMeasured acidity/alkalinitypH3.0 to 9.5
temperatureSample temperature°C34 to 90
tasteDataset quality flag: 1 acceptable, 0 not acceptableBinary0 or 1
odorDataset quality flag: 1 acceptable, 0 not acceptableBinary0 or 1
fatDataset quality flag: 1 acceptable, 0 not acceptableBinary0 or 1
turbidityDataset quality flag: 1 acceptable, 0 not acceptableBinary0 or 1
colourColour value on the dataset scaleNumeric240 to 255
gradeMilk quality classTargetHigh, medium or low
Distribution of high, medium and low milk quality classes
Class balance. Low quality accounts for 40.5%, medium quality for 35.3% and high quality for 24.2%.
Pearson correlations between milk attributes and the encoded quality grade
Indicative associations. Turbidity and temperature show the largest coefficients, but Pearson correlation with an encoded multiclass target depends on the class coding and is not a causal importance measure.

The configured random split contains 637 training, 211 selection and 211 testing records.

3. Neural network

The baseline network scales seven inputs, uses three tanh neurons in one hidden layer and applies a softmax output for the three classes. Continuous inputs use mean-and-standard-deviation scaling, while the four binary flags use minimum–maximum scaling.

Initial milk quality neural network with seven inputs and three hidden neurons

Neural Designer displays grade as one logical categorical output. The exported model evaluates three logits internally and normalizes them into probabilities that sum to one.

4. Training strategy

The classifier minimizes multiclass cross-entropy with the quasi-Newton method. Training and selection losses fall quickly during the first epochs and then stabilize, with the selection curve remaining above the training curve as expected when performance is evaluated on held-out rows.

Quasi-Newton training and selection cross-entropy history for the milk quality classifier

The curve supports convergence for the configured split. Because duplicate input vectors can occur across subsets, the selection loss should not be treated as an independent estimate of performance on a new batch or plant.

5. Model selection

The growing-neurons task compares hidden layers from one to ten neurons. Most of the cross-entropy reduction occurs by three neurons, after which the selection curve changes only slightly. The final exported network contains 10 hidden neurons.

Training and selection cross-entropy as hidden neurons increase from one to ten
The selection curve reaches a broad plateau, so repeated grouped validation is needed to determine whether the larger network delivers a meaningful generalization gain.
Final milk quality neural network with seven inputs and ten hidden neurons
The deployed 7–10–3 classifier matches the exported Python model used in the deployment example.

6. Testing analysis

The confusion matrix below is reproduced from the regenerated Neural Designer output. Rows are observed classes and columns are model predictions.

96.7%testing accuracy
96.3%macro-F1
211testing records
40.3%testing majority baseline

Confusion matrix

Actual / predictedHigh qualityLow qualityMedium qualityTotal
High quality470653
Low quality084185
Medium quality007373
Total478480211

Per-class metrics

ClassTesting supportPrecisionRecallF1
High quality53100.0%88.7%94.0%
Low quality85100.0%98.8%99.4%
Medium quality7391.3%100.0%95.4%

In this split, no low-quality sample is classified as high quality. Six high-quality samples and one low-quality sample are assigned to the medium class. That error pattern is useful for triage, but it must be re-estimated on genuinely independent batches before defining operational thresholds.

Interpretation. The 96.7% result is substantially above the 40.3% majority-class baseline, but duplicate leakage makes it unsuitable as a claim of expected factory performance.

7. Model deployment

A practical screening workflow should capture the sample identifier and batch, validate measurement ranges and sensor status, calculate the three probabilities, and send the result to the laboratory information or quality-management system for review.

Sample and batch record
Measurement and range checks
Three-class probability model
Review, confirm or place on hold

Representative incoming-lot screening case

The following row is present in the published dataset and is evaluated with the final exported Python model. Binary values retain the dataset’s own acceptable/not-acceptable convention.

InputValue
pH6.6
Temperature37 °C
Taste flag1 — acceptable
Odor flag0 — not acceptable
Fat flag1 — acceptable
Turbidity flag0 — not acceptable
Colour255
Model outputProbability
High quality97.04%
Medium quality2.96%
Low quality<0.01%

Result: the model suggests high_quality with 97.04% probability. However, the two non-acceptable binary flags show why a professional implementation should preserve the raw measurements and apply documented business rules: this output can prioritize review, but it should not release the lot without the required confirmatory checks.

Integrate the exported model

The deployment package contains the exact Neural Designer Python export and a README with the input order and example call. The returned probability order is high_quality, low_quality, medium_quality.

from model import NeuralNetwork

model = NeuralNetwork()
probabilities = model.calculate_outputs([6.6, 37, 1, 0, 1, 0, 255])
Deployment boundary. Add schema validation, batch-level traceability, probability monitoring, drift detection and a low-confidence/manual-review policy. The classifier is not a microbiological test, certified analyser or regulatory release function.

8. Scope and limitations

  • The 1,059 records collapse to only 83 unique input combinations, so random row validation is vulnerable to duplicate leakage.
  • The dataset does not identify farms, suppliers, plants, production batches, collection dates, instruments or operators; transfer across these groups is untested.
  • Taste, odor, fat and turbidity are already encoded as “acceptable” or “not acceptable”, which can make the model partly reproduce prior human or rule-based judgement rather than infer quality from raw sensor measurements.
  • Colour is provided on a 240–255 dataset scale without an instrument definition or calibration procedure.
  • Inputs inside their individual ranges can still form combinations that were never represented among the 83 unique vectors.
  • The target is a broad three-level quality label. Microbiological hazards, contaminants, adulteration, allergens and shelf-life behaviour are outside the model.
  • Production use requires an independent, batch-grouped validation set, calibrated instruments, documented sampling procedures and periodic monitoring for class, data and concept drift.
  • Final release, rejection and food-safety decisions must remain within the plant’s validated quality system and applicable laboratory or regulatory procedures.

References