TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Domain Features, Text Statistics and Media Descriptors

Domain Features, Text Statistics and Media Descriptors

The last three families of feature engineering go beyond arithmetic on columns. Domain features encode what experts already know (a doctor looks at body-mass index, not at height and weight separately). Text statistics turn free text into a few numbers that often carry surprising signal (spam shouts in capitals). Image and audio descriptors summarise a whole picture or recording as a short vector of measurable properties: brightness, edges, loudness, pitch. Before deep learning these hand-crafted descriptors were the main way to use media; today they remain the fast, explainable baseline, and learned embeddings from a pretrained network are their modern replacement.

Domain features: write down what experts know

A model can in principle discover that risk depends on weight relative to height squared, but only with lots of data. Giving it the expert's formula is cheaper and makes the model easier to explain:

python · try it yourself
import pandas as pd

patients = pd.DataFrame({
    "height_cm": [182, 165, 158, 175], "weight_kg": [78, 90, 52, 101],
    "systolic": [128, 150, 112, 165], "diastolic": [82, 95, 70, 85],
    "steps_per_day": [8200, 2100, 11500, 3900],
})
f = patients.copy()
f["bmi"] = f["weight_kg"] / (f["height_cm"] / 100) ** 2
f["pulse_pressure"] = f["systolic"] - f["diastolic"]
f["hypertension_stage"] = pd.cut(f["systolic"], [0, 120, 130, 140, 300],
                                 labels=["normal", "elevated", "stage 1", "stage 2"], right=False)
f["active"] = (f["steps_per_day"] >= 7000).astype(int)
print(f[["bmi", "pulse_pressure", "hypertension_stage", "active"]].round(1))
    bmi  pulse_pressure hypertension_stage  active
0  23.5              46           elevated       1
1  33.1              55            stage 2       0
2  20.8              42             normal       1
3  33.0              80            stage 2       0

Each new column comes with a citation-worthy reason: BMI and the blood-pressure stages are clinical conventions, pulse pressure is a known cardiovascular marker. Domain thresholds such as the stage boundaries are fixed, not learned from the data, so they cannot leak. Write such features down with their source; they are part of the model's documentation.

Text statistics

Before any bag-of-words or tokenizer (Working with Text, Preparing Text Data), a handful of counts describes a message's style. They are cheap, language-independent and work well next to word features:

python · try it yourself
import re
import numpy as np
import pandas as pd
from sklearn.preprocessing import FunctionTransformer

def text_stats(texts):
    rows = []
    for t in texts:
        words = re.findall(r"\w+", t.lower())
        letters = [c for c in t if c.isalpha()]
        rows.append({
            "chars": len(t),
            "words": len(words),
            "mean_word_len": np.mean([len(w) for w in words]) if words else 0.0,
            "upper_share": sum(c.isupper() for c in letters) / max(len(letters), 1),
            "digits": sum(c.isdigit() for c in t),
            "exclaims": t.count("!"),
            "urls": len(re.findall(r"https?://", t)),
            "type_token": len(set(words)) / max(len(words), 1),
        })
    return pd.DataFrame(rows)

messages = [
    "Meeting moved to 3pm, see you there.",
    "WIN A FREE PHONE!!! Call 0900 123 456 NOW!!!",
    "Your parcel is waiting: http://x.example/track?id=99",
    "ok ok ok ok thanks",
]
stats = FunctionTransformer(text_stats)          # usable as a pipeline step
print(stats.fit_transform(messages).round(2).to_string())
   chars  words  mean_word_len  upper_share  digits  exclaims  urls  type_token
0     36      7           4.00         0.04       1         0     0         1.0
1     44      9           3.33         0.85      10         6     0         1.0
2     52     10           4.00         0.03       2         0     1         1.0
3     18      5           2.80         0.00       0         0     0         0.4

The spam message stands out on almost every column: 85 % capital letters, 6 exclamation marks, 10 digits. The type-token ratio (distinct words / words) catches repetitive text such as the last message (0.4). In a real pipeline, a ColumnTransformer would send the text column both to TfidfVectorizer and to this FunctionTransformer, and concatenate the results.

Image descriptors

A colour image of 512 × 512 pixels is 786,432 numbers. A descriptor summarises it in a few dozen: the brightness and contrast, a colour histogram, how much of the image is edges, and texture measures such as HOG (histograms of oriented gradients). Here they are computed for three sample images that ship with scikit-image:

python · try it yourself
import numpy as np
from skimage import data, color, feature, transform

images = {"camera": data.camera(), "coins": data.coins(), "astronaut": data.astronaut()}
print(f"{'image':10s} {'shape':>13s} {'mean':>6s} {'std':>6s} {'edges':>6s} {'hog_len':>7s}  top hue bin")
for name, img in images.items():
    gray = color.rgb2gray(img) if img.ndim == 3 else img / 255.0
    small = transform.resize(gray, (128, 128), anti_aliasing=True)
    edges = feature.canny(small, sigma=2).mean()                     # share of edge pixels
    hog = feature.hog(small, pixels_per_cell=(32, 32), cells_per_block=(2, 2))
    if img.ndim == 3:
        hue = color.rgb2hsv(img)[..., 0]
        hist, _ = np.histogram(hue, bins=6, range=(0, 1))
        top = f"{int(hist.argmax())} of 6"
    else:
        top = "(grey)"
    print(f"{name:10s} {str(img.shape):>13s} {gray.mean():6.3f} {gray.std():6.3f} {edges:6.3f} {hog.size:7d}  {top}")
image              shape   mean    std  edges hog_len  top hue bin
camera        (512, 512)  0.506  0.289  0.047     324  (grey)
coins         (303, 384)  0.380  0.207  0.087     324  (grey)
astronaut  (512, 512, 3)  0.442  0.296  0.106     324  0 of 6

Every image, whatever its size, becomes the same short vector, so a classical model (logistic regression, gradient boosting) can use it. The HOG vector has 324 values here: 3 × 3 block positions of 2 × 2 cells with 9 orientation bins each. Resize to a fixed size before computing descriptors, otherwise the edge share and HOG length depend on the resolution. Image preparation itself is the topic of Preparing Image Data.

Audio descriptors

The same idea for sound. Three classic descriptors, computed per short frame and then averaged, separate many kinds of audio: RMS energy (loudness), zero-crossing rate (how often the waveform changes sign, high for noise and hissing sounds) and the spectral centroid (the "centre of mass" of the spectrum, perceived as brightness). Synthetic signals make the meaning visible:

python · try it yourself
import numpy as np

sr = 16000
t = np.arange(sr) / sr                                   # one second
rng = np.random.default_rng(0)
signals = {
    "hum 220 Hz": 0.5 * np.sin(2 * np.pi * 220 * t),
    "whistle 2 kHz": 0.2 * np.sin(2 * np.pi * 2000 * t),
    "white noise": 0.3 * rng.normal(0, 1, sr),
}

def describe(x, frame=1024):
    frames = x[: len(x) // frame * frame].reshape(-1, frame)
    rms = np.sqrt((frames ** 2).mean(axis=1)).mean()
    zcr = (np.abs(np.diff(np.sign(frames), axis=1)) > 0).mean()
    spec = np.abs(np.fft.rfft(frames * np.hanning(frame), axis=1))
    freqs = np.fft.rfftfreq(frame, 1 / sr)
    centroid = ((spec * freqs).sum(axis=1) / spec.sum(axis=1)).mean()
    return rms, zcr, centroid

print(f"{'signal':14s} {'rms':>6s} {'zcr':>6s} {'centroid Hz':>12s}")
for name, x in signals.items():
    rms, zcr, cen = describe(x)
    print(f"{name:14s} {rms:6.3f} {zcr:6.3f} {cen:12.0f}")
signal            rms    zcr  centroid Hz
hum 220 Hz      0.354  0.028          220
whistle 2 kHz   0.141  0.250         2000
white noise     0.299  0.499         4001

The pure tones put their centroid at their own frequency (220 and 2000 Hz), white noise spreads its energy evenly up to 8 kHz, so its centroid lands near the middle (4001 Hz) and its zero-crossing rate is 0.499, far above the tones. Real systems add the log-Mel spectrogram and MFCCs (Preparing Audio Data).

Descriptors versus embeddings

Hand-crafted descriptors Learned embeddings
What formulas: histograms, edges, RMS, word counts the activations of a pretrained network (CNN, audio model, sentence encoder)
Size tens to a few thousand numbers typically 128 to 1024 numbers
Strengths fast, explainable, no model download capture meaning ("a cat", "a happy review"), state of the art
Weak spots miss semantics need the model at serving time; inherit its biases

Embeddings are covered in Learned Embeddings and in the deep-learning courses. A good practice is to start with descriptors as the baseline and keep them as extra columns next to embeddings.

Pitfalls

  • Domain features that encode the label: "number of chemotherapy sessions" as a feature for predicting cancer is the diagnosis in disguise.
  • Inconsistent media preprocessing: descriptors computed on JPEGs from one camera and PNGs from another differ for reasons unrelated to the label; models then learn the camera. Normalise format, size and sample rate first.
  • Statistics that depend on the corpus (an IDF weight, "share of the dataset's vocabulary") are fitted steps: learn them on training data only, inside the pipeline.

Practice

  1. Suggest two domain features for predicting whether a flight will be delayed, given scheduled departure time, airport, aircraft id and the previous flight of the same aircraft.
Answer

The scheduled turnaround time (departure minus the aircraft's previous scheduled arrival: short buffers propagate delays) and the departure hour as a cyclical feature or a "peak hour at this airport" flag. Both are known before departure. The previous flight's actual delay may be used only if it is known at prediction time.

  1. Why does the zero-crossing rate of white noise come out near 0.5?
Answer

Independent samples with mean zero have a 50 % chance of having a different sign from the previous sample, so about half of all consecutive pairs cross zero.

Test yourself

Why are clinical thresholds such as blood-pressure stages safe from leakage?

  1. They are categorical
  2. They are fixed by domain knowledge, not computed from the dataset
  3. They are always correct
  4. They are scaled

Which descriptor best separates a hiss from a low hum?

  1. Duration
  2. Zero-crossing rate or spectral centroid
  3. File name
  4. Number of channels

Why resize images to a fixed size before computing HOG features?

  1. HOG fails on colour
  2. The length of the HOG vector and the edge statistics depend on the image size
  3. To remove noise
  4. It is faster to train

A message has 40 % of its letters in capitals and 6 exclamation marks. Which feature family captured that?

  1. Domain features
  2. Text statistics
  3. Embeddings
  4. Lag features