← All Google Cloud AI guidesFundamentals · 2.1, 3.1

ML fundamentals 1: data, feature engineering and class imbalance

The data half of ML fundamentals: framing a problem, splitting data without leaking the answer, every common feature-engineering technique and when to use it, missing values, feature selection, and a deep treatment of class imbalance (weights, resampling, SMOTE, thresholds, probability correction). Maps each technique to BigQuery ML, TensorFlow Transform and Dataflow.

1. Framing the problem before touching data

Many exam questions are lost before any modelling: the problem was framed wrongly. Before choosing a model, answer these:

QuestionWhy it matters
Is ML needed at all?If a rule or a SQL query solves it reliably, that's cheaper and explainable. ML is for patterns too complex to write by hand.
What exactly is predicted, and when?"Will this customer cancel in the next 30 days, predicted on the 1st of each month" defines the label, the prediction time and which data is allowed.
What kind of problem is it?Binary or multi-class classification, multi-label, regression, forecasting, ranking/recommendation, clustering, anomaly detection, generation.
What's the baseline?A majority-class guess, last value, a simple rule, or a linear model. Every model must beat it to be worth shipping.
What's the business metric, and what does each error cost?Decides the evaluation metric and the threshold (see Fundamentals 2).
Do labels exist, and how quickly do they arrive?No labels: unsupervised, weak supervision, or a labelling project. Late labels: retraining and monitoring must account for the delay.
Write the prediction as a sentence with a time: "At time t, using only data available before t, predict y over window w." Most leakage bugs are violations of that sentence.

2. Data quality and exploration

Exploratory data analysis (EDA) finds problems that would otherwise surface as a mysteriously bad or suspiciously good model.

CheckWhat to look forOn Google Cloud
Schema and typesNumbers stored as strings, mixed date formats, IDs read as numbersBigQuery schema, INFORMATION_SCHEMA, TensorFlow Data Validation (TFDV) schema
Missing valuesRates per column, and whether missingness is itself informativeCOUNTIF(col IS NULL), data profile scans (Dataplex)
Distributions and outliersHeavy tails, impossible values (negative ages), sentinel values like -999APPROX_QUANTILES, TFDV statistics, notebook histograms
Label quality and balanceClass ratios, noisy or inconsistent labels, label definition drift over timeGROUP BY label, label audits
DuplicatesExact or near duplicates across train and test inflate scoresHash rows; dedupe before splitting
CorrelationsFeatures nearly identical to the label (leakage suspects), or to each other (redundancy)CORR(), feature importance
Time coverageGaps, seasonality, sudden changes in how data was recordedCounts per day; plot over time

3. Splitting data correctly

Split typeWhenWhy
Random train / validation / test (for example 80/10/10)Independent rows, no time dependenceSimple and unbiased when rows really are independent
StratifiedClassification, especially imbalancedKeeps the class ratio equal in every split, so the rare class appears in validation and test
Time-based (train on the past, test on the future)Forecasting, or any data where the world changes over time (fraud, churn, prices)A random split lets the model learn from the future it's tested on
Group-basedSeveral rows per user, patient, device or sessionAll rows of one group stay in one split, or the model memorizes the entity instead of learning the pattern

4. Data leakage

Leakage means the model sees information during training that it won't have at prediction time. It produces excellent offline metrics and poor production results, and it's one of the most tested fundamentals.

TypeExamplePrevent it
Target leakagePredicting churn with "cancellation_reason" or "refund_issued", recorded only after the customer leavesFor each feature, ask "is this known at prediction time?"; build features as of the prediction timestamp
Temporal leakageRandom split of time-series data; a 30-day rolling average that includes future daysTime-based splits; windows that end before the prediction time; point-in-time feature lookups
Train-test contaminationScaling or imputing with statistics computed on all data; duplicates in both splitsFit transforms on training data only; deduplicate before splitting
Group leakageThe same patient's scans in training and testGroup-based splits
Target encoding leakageReplacing a category with the average label computed including the row itselfOut-of-fold target encoding with smoothing
Proxy leakageAn "account_closed_date" column that's null for active customersInspect features with suspiciously high importance
A sudden jump to near-perfect validation scores after adding one feature almost always means leakage, not a breakthrough. Check feature attributions: a single dominant feature is the usual tell.

On Google Cloud, point-in-time lookups in the Feature Store (and ML.FEATURES_AT_TIME / ML.ENTITY_FEATURES_AT_TIME in BigQuery) return each feature's value as it was at the label's timestamp, which prevents temporal leakage when building training sets.

5. Feature engineering: numeric features

TechniqueWhat it doesUse whenBigQuery ML
Standardization (z-score)(x − mean) / stdLinear models, neural networks, k-means, anything with gradients or distancesML.STANDARD_SCALER
Min-max scalingRescale to [0, 1]Bounded inputs, neural networks; sensitive to outliersML.MIN_MAX_SCALER
Robust scalingUses median and interquartile rangeOutliers presentML.ROBUST_SCALER
Log transformlog(x + 1)Heavy right tails (income, counts, prices)LOG(x + 1) in TRANSFORM
Bucketizing (binning)Turns a number into rangesNon-linear effects in linear models (age bands); quantile buckets give equal-sized binsML.BUCKETIZE, ML.QUANTILE_BUCKETIZE
ClippingCaps values at percentilesExtreme outliers that would dominate trainingLEAST/GREATEST
Polynomial featuresx², x·yCurved relationships in linear modelsML.POLYNOMIAL_EXPAND
Ratios and differencesspend per visit, days since last orderDomain knowledge; often the strongest featuresSQL expressions
Tree-based models (boosted trees, random forests) don't need scaling or log transforms: they split on thresholds. Linear models, neural networks and distance-based methods do.

6. Feature engineering: categorical features

TechniqueHowUse whenWatch out
One-hot encodingOne binary column per valueFew distinct values (tens)Explodes with high cardinality; unseen values at serving need a default
Label / ordinal encodingInteger per valueTruly ordered values (small < medium < large), or tree modelsImplies an order linear models will misuse
Feature hashing (hash buckets)hash(value) mod NVery high or unbounded cardinality (URLs, IDs); new values appear constantlyCollisions merge unrelated values; pick N to keep them rare
EmbeddingsLearned dense vectors per valueHigh cardinality in neural networks (user IDs, products, words)Need enough data per value; cold start for new values
Target (mean) encodingReplace a value with the mean label for itHigh-cardinality features in tree modelsLeakage unless out-of-fold and smoothed
Frequency encodingReplace with how often the value occursPopularity mattersDifferent values can share a frequency
Grouping rare valuesMap values below a count to "OTHER"Long tails; keeps vocabularies stableChoose the threshold on training data
"Few: one-hot. Many: hash or embed. Ordered: ordinal. Interacting: cross."

7. Text, image, time and geospatial features

DataClassic featuresModern features
TextBag of words, n-grams, TF-IDF (term frequency–inverse document frequency); ML.NGRAMS, ML.TF_IDF in BigQuery MLEmbeddings from a pretrained model (Gemini embeddings via ML.GENERATE_EMBEDDING), or fine-tuning a transformer
ImagesResizing, normalization, colour histogramsTransfer learning from a pretrained CNN or vision transformer; augmentation (flip, crop, rotate) to add variety
Time / datesHour, day of week, month, holiday flag; cyclical encoding with sine and cosine so 23:00 is close to 00:00Lags (value 1, 7, 28 days ago), rolling means and counts over windows that end before the prediction time
GeospatialLatitude and longitude buckets, crosses of lat × long, distance to points of interestGeohash or S2 cells, BigQuery GIS functions (ST_DISTANCE)
Sequences / eventsCounts per window, time since last eventSequence models, session embeddings
Rolling and lag features must be computed with windows that end before each prediction time. A window centred on the event, or computed over the full table, leaks the future.

8. Missing values

ApproachWhen
Drop rowsFew rows affected, missing at random, plenty of data
Drop the columnMostly missing and not informative
Impute mean or median (numeric), most frequent (categorical)Simple baseline; median for skewed data. ML.IMPUTER in BigQuery ML
Add a "was missing" indicatorMissingness carries signal (no phone number on file)
Model-based imputationStrong relationships between features; more effort
Let the model handle itGradient-boosted trees (XGBoost, BigQuery ML boosted trees) learn a default direction for missing values
Whatever you choose, apply the same imputation values at serving, computed from training data. BigQuery ML's TRANSFORM, TensorFlow Transform and in-model preprocessing layers do this automatically.

9. Feature selection

FamilyExamplesTrade-off
Filter methodsCorrelation with the label, mutual information, chi-squared, variance thresholdFast, model-independent; miss interactions
Wrapper methodsForward selection, backward elimination, recursive feature eliminationModel-aware; expensive
Embedded methodsL1 (lasso) regularization drives useless weights to zero; tree feature importanceSelection happens during training
Attribution-basedShapley values, permutation importance, ML.FEATURE_IMPORTANCE, ML.GLOBAL_EXPLAINExplains a trained model; good for pruning
Dimensionality reductionPCA (model_type='PCA'), autoencodersCompresses correlated features; components lose direct meaning

Fewer, better features mean faster training and serving, less overfitting, simpler monitoring and fewer things that can drift or break.

10. Class imbalance in depth

Imbalance means one class is much rarer than the other (fraud at 0.1%, defects at 0.5%). It causes three problems: misleading metrics (accuracy looks great), a model that ignores the rare class (the loss is dominated by the majority), and too few positive examples to learn from.

1. Measure correctly first

2. Change how the model learns

TechniqueHowProsCons
Class weightsMultiply the loss of rare-class errors (for example weight = N / (2 × Nclass))No data thrown away; one parameter. auto_class_weights=TRUE in BigQuery ML, class_weight in Keras, scale_pos_weight in XGBoostProbabilities become miscalibrated (too high for the rare class)
Downsampling the majority (undersampling)Keep a fraction of majority rowsFaster training; often fine with huge dataDiscards information; probabilities need correction
Downsample + upweightDownsample the majority by factor k, then weight those rows by kGoogle's recommended pattern: fast training with calibrated probabilitiesOne more parameter
Oversampling the minorityDuplicate rare rowsSimpleOverfits the duplicated rows; oversample after splitting, never before
SMOTE (synthetic minority oversampling)Creates synthetic rare examples between neighboursMore variety than duplicationCan create unrealistic points; tabular numeric data only; apply only to training
Focal lossDown-weights easy, well-classified examplesStrong for dense detection and extreme imbalance in deep learningExtra hyperparameter
Anomaly-detection framingModel "normal" and flag deviations (autoencoder, k-means distance, isolation forest)When positives are extremely rare or unlabelledHarder to target a specific kind of positive
Collect or label more positivesActive learning, labelling campaigns, data from related sourcesOften the biggest gainTime and cost

3. Choose the operating point

Resample only the training set, after splitting. Oversampling before the split copies the same rare rows into test, and evaluating on a rebalanced test set reports precision you'll never see in production.

11. Class imbalance calculator

Enter your class counts and a downsampling plan. The calculator gives balanced class weights, the training ratio after downsampling, the weight that restores calibration, and how to convert a probability from the downsampled model back to the real-world probability.

12. Doing feature engineering on Google Cloud

ToolFeature engineering role
BigQuery ML TRANSFORMScalers, bucketizers, imputers, crosses, n-grams stored with the model and applied at prediction automatically
TensorFlow Transform (on Dataflow)Full-pass statistics (vocabularies, means) computed at scale and exported into the serving graph
Keras preprocessing layers, scikit-learn Pipeline / ColumnTransformerPreprocessing saved inside the model artifact
Dataflow / SparkLarge-scale joins, windows and streaming features
Feature Store on Agent PlatformShared, versioned features with point-in-time training data and online serving
Data preparation in BigQuery, Gemini in BigQueryLow-code cleaning suggestions
The exam's theme: one implementation of preprocessing, used for training and serving. Different code paths are the main cause of training-serving skew.

13. "Which technique?" chooser

Pick an item to see what it means, why, and the tempting wrong choice.

Pick one above.

14. Scenarios

Exam-style situations: how to diagnose each one, the likely cause and the fix.

15. Searchable reference

ItemMeaning

16. Flashcards (click to flip)

17. Common gotchas in one list

  1. Ask of every feature: is it known at prediction time? If not, it leaks.
  2. Random splits leak the future for time-dependent data; split by time.
  3. Keep each user, patient or device in one split.
  4. Fit preprocessing on training data only and reuse the same statistics at serving.
  5. Resample only the training set; validate and test at the real class ratio.
  6. Accuracy hides imbalance; use precision, recall, PR AUC.
  7. Class weights and resampling distort probabilities: recalibrate, or downsample and upweight.
  8. Trees don't need scaling; linear models, neural networks and k-means do.
  9. One-hot for few values; hashing or embeddings for many; plan for unseen values.
  10. Linear models need feature crosses for interactions.
  11. Target encoding must be out-of-fold, or it leaks the label.
  12. A sudden near-perfect score means leakage until proven otherwise.
  13. Windows must end before the prediction time for lag and rolling features.
  14. Often the best imbalance fix is more positive examples.

18. Practice quiz (22 questions)

Score: 0 / 0
← Exam overview and strategyNext: ML fundamentals 2: bias-variance and metrics →