Part III — Preparing the data · Chapter 6

Feature engineering, encoding, scaling, dimensionality reduction

~45 min read6 interactive widgets4 plates

In this chapter

  1. Feature engineering
  2. Encoding: ordinal, Likert, one-hot
  3. Case study: encoding wrong data types (Y2K22)
  4. Feature scaling
  5. Skewed distributions and the long tail
  6. Aggregation and binning
  7. Too many features: the curse of dimensionality
  8. Feature selection: filter, wrapper, embedded
  9. Feature extraction: PCA
  10. Integrate and format data
  11. Sequences of transformations, ETL and ELT
  12. Check your understanding

1. Feature engineering

Three situations open the section, all asking the same thing — is the dataset ready for machine learning?

Feature engineering refers to the manipulation — addition, deletion, combination, mutation — of your data set to improve machine learning model training. Derived attributes should be added if they ease the modeling algorithm:

Area           = Length x Width
Loyalty_Score  = Total_Purchases x 0.4 + Avg_Order_Value x 0.3 + Frequency x 0.3
Ocean_Proximity = distance((Ocean_Latitude, Ocean_Longitude),
                           (District_Latitude, District_Longitude))

Encoding may be necessary to transform symbolic fields ("definitely yes", "yes", "don't know", "no") to numeric values.

Key idea

You have already seen a whole chapter of feature engineering without the name: Chapter 3. NP is a derived attribute built from raw power readings; IF = NP/FTP is a normalisation; TSB = CTL − ATL is a combination of two aggregations. The three lines above are the same operation applied to a table — and the Ocean_Proximity example is exactly the housing lab of the course.

2. Encoding: ordinal, Likert, one-hot

Encoding is the process of converting categorical variables into numeric features.

Categorical features can be nominal or ordinal:

KindDefinitionExample
NominalDo not have a defined ranking or inherent orderColors
OrdinalHave an inherent order or rankingSize

One-hot encoding and ordinal encoding are the most common methods to transform categorical variables into numerical features.

Ordinal encoding

Ordinal encoding replaces each category with an integer value. These numbers are, in general, assigned arbitrarily. Ordinal encoding is a preferred option when the categorical variable has an inherent order.

Before encodingAfter encoding (small = 0, medium = 1, large = 2)
ProductIdSizeProductIdSizeSize_Enc
P1smallP1small0
P2mediumP2medium1
P3largeP3large2
P4smallP4small0

One-hot encoding

One-hot encoding (OHE) replaces categorical variables by a set of binary variables, each representing a category in the variable. The binary variable takes the value 1 if the observation shows the category, and 0 otherwise. One-hot encoding treats each category independently.

Before encodingAfter encoding
ProductIdColorProductIdColorredgreenblue
P1redP1red100
P2greenP2green010
P3blueP3blue001
P4redP4red100

OHE increases the dimensionality of the dataset, and it may not be suitable for encoding high cardinality features. To prevent a massive increase in the feature space, we can one-hot encode only the most frequent categories in the variable; less frequent values are then treated collectively and represented as 0s in all the binary variables.

ONE COLUMN, TWO ENCODINGS, TWO DIFFERENT CLAIMS Color red green blue red ordinal encoding on a nominal feature 0 1 2 0 the model now believes red < green < blue, and that blue is twice green. fine for small/medium/large, wrong for colors. one-hot encoding redgreenblue 1 0 0 0 1 0 0 0 1 each category is independent: no order is implied cost: one new column per category with high cardinality, encode only the most frequent categories; the rest become all-zero rows
Plate 6.1 — Encoding is not a formatting step, it is a claim about the data. Ordinal encoding asserts an order and a distance; one-hot encoding asserts independence and pays for it in columns.

Widget — encode a column

The Likert scale

The Likert scale is widely used in social work research and is commonly constructed with four to seven points[*, **, ***, ****, *****] or [1, 2, 3, 4, 5]. And then the trap: what about averaging?

It is usually treated as an interval scale, but strictly speaking it is an ordinal scale, where arithmetic operations cannot be conducted (Wu and Leung 2017). The passage quoted on the slide is worth reading twice:

Careful

Converting responses to a Likert-type question into an average seems an obvious and intuitive step, but it doesn't necessarily constitute good methodology. One important point is that respondents are often reluctant to express a strong opinion and may distort the results by gravitating to the neutral midpoint response. It also assumes that the emotional distance between mild agreement or disagreement and strong agreement or disagreement is the same, which isn't necessarily the case. At its most fundamental level, the problem is that the numbers in a Likert scale are not numbers as such, but a means of ranking responses.

And the empirical companion: the J-shaped distribution of product reviews (Hu, Zhang, and Pavlou 2009). People tend to write reviews only when they are either extremely satisfied or extremely unsatisfied; people who feel the product is average might not bother to write a review. So the sample is not merely ordinal — it is also selected, which is the self-selection face of the biases in Chapter 4.

3. Case study: encoding wrong data types (Y2K22)

The Y2K22 bug: encoding the date 2022-01-01T00:01 into a signed integer 2201010001.

A signed integer is a 32-bit datum that represents an integer in the range:

[ -2^31 , 2^31 - 1 ] = [ -2147483648 , 2147483647 ]

however   2201010001 > 2147483647

The date, encoded that way, does not fit. The deck points to the year 2000 problem as the ancestor of the same mistake.

Key idea

Encoding decisions have a range, and the range is part of the decision. The pattern YYMMDDHHmm was a perfectly reasonable encoding until the year rolled over to 22 and the concatenation crossed a boundary nobody had checked. Same lesson as the CAGR case study of Chapter 5, from the opposite direction: there, semantics were ignored; here, the physical type was.

4. Feature scaling

If data values vary widely, objective functions will not work properly without normalization in some ML algorithms. For example, many classifiers calculate the distance between two points using the Euclidean distance:

d(p, q) = sqrt( (p1-q1)^2 + (p2-q2)^2 + ... + (pn-qn)^2 )
        = sqrt( SUM over i of (pi - qi)^2 )

If one of the features has a broad range of values, the distance will be governed by this particular feature. The worked example, with age ∈ [0, 120] and income ∈ [0, 100000]:

PointageincomeDistance from p1
p15010000
p25020000d(p1, p2) = 10000.00
p36010000d(p1, p3) = 10.00
p46020000d(p1, p4) = 10000.00

Read the last row: p4 differs from p1 in both features, and yet its distance is indistinguishable from p2, which differs only in income. Age has been erased by the units of income.

The three scalers

MethodFormulaWhat it guarantees
Min-max normalizationx' = a + (x - min(x))(b - a) / (max(x) - min(x))Rescales the feature into [a, b], typically [0, 1]
Standardizationx' = (x - mean(x)) / sd(x)Zero mean and unit variance for every feature
Robust scalingx' = (x - Q2(x)) / (Q3(x) - Q1(x))Designed to be robust to outliers: built on the median and the IQR, not the mean and the range
THE SAME FOUR POINTS, BEFORE AND AFTER MIN-MAX NORMALIZATION raw units age 0 .. 120 income 0 .. 100000 p1 p2 p3 p4 d(p1,p2) = 10000.00 d(p1,p3) = 10.00 d(p1,p4) = 10000.00 income decides everything after min-max into [0,1] age scaled 0 .. 1 income scaled 0 .. 1 p1 p2 p3 p4 d(p1,p2) = 0.100 d(p1,p3) = 0.083 d(p1,p4) = 0.130 both features now speak rescale
Plate 6.2 — Why scaling is not cosmetic. In raw units, p4 (different in age and income) is exactly as far from p1 as p2 (different in income only). After min-max normalization the three distances finally rank as they should.

Widget — distances before and after scaling

On Iris the deck runs the same demonstration in the other direction: it multiplies petal_length by 10 and adds a single outlier at [petal_length=100, petal_width=100], and shows what the transformed dataset does to the plot. One point, one unit change, and the picture is unreadable.

For the exam

Know which algorithms care. Anything built on distances — k-NN (Chapter 8), k-means, SVM — and anything built on gradient descent over a shared learning rate (Chapter 7) is sensitive to scale, and so is PCA (which is why standardization is its first step). Decision trees, which cut one feature at a time, are not. In Chapter 8 you will see exactly this: the k-NN decision boundary with and without min-max normalization.

5. Skewed distributions and the long tail

Long Tail refers to the concept where a large number of niche products collectively generate more sales than a few bestsellers. E-commerce sites such as Amazon stock a vast array of products that traditional retailers would not carry due to space constraints. The Long Tail phenomenon is directly related to skewed distributions, specifically a type of right-skewed distribution.

What happens to mean values? The deck compares two distributions:

Gaussian distribution (heights)Skewed distribution (wealth)
Mean173 cm103 158 262 914
Median173 cm36 666 524 821

In the Gaussian case the two coincide. In the skewed case the mean is nearly three times the median — and neither number describes a typical individual. Skewed distributions can be transformed using mathematical functions such as the logarithm.

WHERE THE MEAN GOES WHEN THE TAIL GETS LONG mean = median Gaussian mean 173 cm, median 173 cm median mean right-skewed (the long tail) mean 103 158 262 914 / median 36 666 524 821 the tail: many niche products after log transform the skew is compressed log mean imputation on a skewed column writes a value almost nobody has
Plate 6.3 — On a symmetric distribution mean and median agree, and mean substitution is defensible. On a right-skewed one the mean is dragged into the tail; the imputation of Chapter 5 then inserts a value that is typical of nothing.

6. Aggregation and binning

Aggregation and binning may be necessary to transform ranges to symbolic fields. The first example bins sales every 1000 €:

StoreIdDatesalessales_bin
S12024-10-041000[1000-2000)
S12024-10-051500[1000-2000)
S12024-10-062000[2000-3000)

Smoothing noise

A meteorologist analyzes hourly temperature readings, but the data has fluctuations due to temporary weather conditions:

HourTemperature (°C)
124.1
224.3
323.8
424.5
522.9 (sudden drop due to rain)
624.2
723.9

Using equal-width binning — grouping every 3 hours and averaging:

Time periodSmoothed temperature (°C)
1-3 AM24.0 (avg of 24.1, 24.3, 23.8)
4-6 AM23.9 (avg of 24.5, 22.9, 24.2)
7 AM23.9

Noise from sudden drops (e.g. 22.9°C at 5 AM) is smoothed, making temperature trends more reliable.

Aggregation

Aggregation computes new values by summarizing information from multiple records and/or tables — for example, converting a table of product purchases, with one record per purchase, into a new table with one record per store.

Careful — pay attention to the aggregation operator

Correct (sum of sums): (1 + 2) + (3 + 4 + 5) = 1 + 2 + 3 + 4 + 5 = 15.
Wrong (average of averages): avg(avg(1, 2), avg(3, 4, 5)) = avg(1.5, 4) = 2.75, whereas avg(1, 2, 3, 4, 5) = 3.
Sum is distributive over grouping; average is not, because the groups have different sizes. This is the same class of error as averaging returns in Chapter 5.

Binning

Data binning is a pre-processing technique that reduces the effects of minor observation errors: the original values that fall into a given interval (bin) are replaced by a central value representative of that interval. Histograms are an example of data binning, used to observe underlying frequency distributions.

Equal-widthEqual-frequency
RuleDivide the range of values into equal-sized intervalsDivide the values into bins that have the same number of observations
ExampleValues from 0 to 100 into 10 bins → each bin has width 10100 observations into 10 bins → each bin has 10 observations
AdvantageBin boundaries are interpretable and evenly spacedCreates balanced bins that handle skewed data and outliers better
DisadvantageCan create empty or sparse bins, especially if the data is skewed or has outliersCan distort the distribution of the data and create irregular bin widths

Widget — bin the temperatures

Widget — the aggregation trap

7. Too many features: the curse of dimensionality

A streaming platform wants to recommend movies based on user preferences. Each movie is represented by a vector of features: genre, director, lead actor, IMDB rating, budget, user reviews, box office revenue, soundtrack style… and many more — let us assume 100+ features per movie.

If movies had only 2 features (genre and IMDB rating) we could easily visualize clusters of similar movies. With 100+ features, the data points are spread out across a vast space:

Dimensionality reduction is the transformation of data from a high-dimensional space into a low-dimensional space.

The main approaches divide into feature selection and feature extraction.

8. Feature selection: filter, wrapper, embedded

Feature selection is the process of selecting a subset of relevant features (variables, predictors) for use in model construction.

Why not just try them all

The dummy algorithm: test each subset of features to find the one that minimizes the error. This is an exhaustive search of the space, and is computationally intractable for all but the smallest of feature sets. If S is a finite set of features with cardinality |S|, the number of all subsets is

|P(S)| = 2^|S| - 1        (the empty set is not considered)

  3 features  ->  2^3  = 8 subsets
  4 features  ->  2^4  = 16 subsets
 10 features  ->  2^10 = 1024 subsets

Feature selection approaches are therefore characterized by two things: a search technique for proposing new feature subsets, and an evaluation measure for scoring the different subsets.

Filter strategy: select variables regardless of the model, based only on general features like the correlation with the variable to predict.

Variance threshold. With mean = (1/n) SUM xi and Var(X) = (1/n) SUM (xi - mean)^2: features with low variance do not contribute much information to a model, so a variance threshold removes any feature with little to no variation in its values. Since variance can only be calculated on numeric values, this method only works on quantitative features.

StoreIdsalesPostalCode
1100047522
2150047522
3100047522

VAR(StoreId) = 0.67 (?), VAR(sales) = 55555.56, VAR(PostalCode) = 0. Selecting VAR(X) > 0.6 keeps StoreId and sales. The question mark on the slide is the point of the example: StoreId passes the numeric test while being a meaningless identifier.

Pearson's correlation measures the linear relationship between 2 numeric variables: a coefficient close to 1 is a positive correlation, -1 negative, 0 none. Two uses:

  • Between features: when two features are highly correlated with one another, keeping just one is enough — the second would only be redundant and contribute unnecessary noise.
  • Between feature and target: if a feature is not very correlated with the target — a coefficient between -0.3 and 0.3 — it may not be very predictive and can potentially be filtered out.

Wrapper strategy: each new feature subset is used to train a model, which is tested on a hold-out set. Counting the number of mistakes made on that hold-out set — the error rate of the model — gives the score for that subset. As wrapper methods train a new model for each subset, they are very computationally intensive but provide good results.

Methods include forward selection, backward elimination, and exhaustive search. Stepwise regression adds the best feature (or deletes the worst feature) at each round.

Backward elimination: start with the full model including all features, then incrementally remove the most insignificant feature, repeating until the final set of significant features remains.

  1. Choose a significance level (e.g. SL = 0.05, with 95% confidence).
  2. Fit a full model including all the features.
  3. Consider the feature with the highest p-value. If the p-value < SL, terminate the process.
  4. Remove the feature under consideration.
  5. Fit a model without this feature. Repeat the entire process from step 3.

Embedded strategy: add or remove features while building the model, based on prediction errors. A learning algorithm takes advantage of its own variable selection process and performs feature selection and classification simultaneously.

The linear regression model is y_hat_i = b1x1 + b2x2 + ... + bpxp, and the goal is minimizing the sum of squared errors between predicted and actual values:

min ( SUM over i of (yi - y_hat_i)^2 )

LASSO — Least Absolute Shrinkage and Selection Operator — adds a penalty proportional to the absolute values of the coefficients:

min ( SUM over i of (yi - y_hat_i)^2  +  lambda * SUM over j of |bj| )
  • bj are the coefficients of the model;
  • lambda is the regularization parameter controlling the penalty strength.

Lasso performs automatic feature selection: by shrinking some coefficients to 0, it removes irrelevant features. The optimal lambda can be determined with cross-validation techniques (Chapter 8). See also Katrutsa and Strijov (2017) and Chan et al. (2022) on multicollinearity.

Widget — filter the features

The variance-threshold table from the deck, with the threshold under your control.

9. Feature extraction: PCA

Feature projection (or feature extraction) transforms the data from the high-dimensional space to a space of fewer dimensions. The transformation may be linear, as in principal component analysis (PCA), but many nonlinear dimensionality reduction techniques also exist.

PCA is a linear dimensionality reduction technique:

Computing PCA

  1. PCA is sensitive to the scale of the data. The first step is usually to standardize the features (mean = 0, standard deviation = 1) to ensure that all features contribute equally to the analysis.
  2. Then, compute the covariance matrix.
    • Eigenvectors represent the directions of the principal components.
    • Eigenvalues represent the magnitude of variance in the direction of the corresponding eigenvector.
  3. The eigenvector with the largest eigenvalue is the first principal component, and so on.

PCA on Iris

Iris contains 4 features, so it cannot be plotted directly. Running PCA:

Principal componentExplained variance
PC 192.46%
PC 25.31%
PC 31.71%

Feature relevance for 3 components:

FeaturePC 1PC 2PC 3
Sepal Length (cm)0.3610.657-0.582
Sepal Width (cm)-0.0850.7300.598
Petal Length (cm)0.857-0.1730.076
Petal Width (cm)0.358-0.0750.546
PCA ON IRIS: ONE DIRECTION CARRIES ALMOST EVERYTHING 100% 50% 0% 92.46% PC1 5.31% PC2 1.71% PC3 explained variance per component original feature 1 (standardized) original feature 2 PC1 PC2 new axes: the direction of maximum variance, and what is left, orthogonal to it
Plate 6.4 — PCA finds a new coordinate system aligned with the variance. On Iris, PC1 alone explains 92.46% of it — and its heaviest loading, 0.857, is on petal length, the feature Chapter 4 already singled out by eye and Chapter 8 will rank at importance 1.0.

10. Integrate and format data

A hospital wants to analyze patient health records by integrating data from multiple sources: electronic health records (EHRs), wearable devices, and insurance claims. That is the integration problem.

Integration involves combining information from multiple tables or records to create new records or values. With table-based data, an analyst can join two or more tables that have different information about the same objects.

The worked example: a retail chain has one table with each store's general characteristics (floor space, type of mall), another with summarized sales data (profit, percent change in sales from the previous year), and another with the demographics of the surrounding area. These tables can be merged into a new table with one record for each store.

Data integration combines data residing in different sources and provides users with a unified view of them. Two strategies:

AspectSemantic integrationPrimary key-based integration
ApproachBased on meaning and understanding of the dataBased on matching unique keys
SuitabilityData with heterogeneous terminologies or structuresDatasets that have common, well-defined keys
ComplexityComplex to interpret and align meaningsSimpler, relies on exact key matches
FlexibilityIntegrates data with different schemas/representationsLess flexible, requires shared primary key fields
ChallengesRequires mapping of concepts and domain semanticsLimited to datasets that share a key

Primary key-based integration combines multiple sources by matching unique identifiers; it works when both datasets have a well-defined and consistent schema with common key fields. Semantic integration focuses on understanding the meaning of the data from different sources: the goal is to merge data that may use different names, terminologies, or structures to describe the same concepts. It involves the use of ontologies or data dictionaries to map similar concepts across datasets, and requires understanding the context, meaning and relationships within the data — for instance, spatial data can be easily integrated into maps.

Format data

In some cases the analyst will change the format (structure) of the data: sometimes to make it suitable for a specific modeling tool, in other instances to be able to pose the necessary data mining questions. Examples:

The slide carries the 5 V's of Big Data as a reference point for this discussion.

11. Sequences of transformations, ETL and ELT

Things are even more complex when applying sequences of transformations:

The verdict on the slide: more an art than a science… at least for now.

Key idea

Pre-processing steps do not commute. Every step changes the statistics the next step reads: standardization uses the mean and the standard deviation, so anything that changes the sample changes the standardization. This is the technical restatement of the warning at the start of Chapter 5 — data scientists cannot easily foresee the impact of pipeline prototypes, and there are no pre-defined rules on the impact of pre-processing transformations.

Overlap with Business Intelligence and Data Warehousing

ETL (Extract, Transform, Load) is one of the most widely used data integration techniques in data warehousing:

ELT (Extract, Load, Transform) loads data into a storage system (like a data lake) and then transforms within the storage system.

Overlap with Big Data and Cloud Platforms

Check your understanding

Define feature engineering and give three derived attributes.

Feature engineering is the manipulation — addition, deletion, combination, mutation — of your data set to improve machine learning model training. Derived attributes should be added if they ease the modeling algorithm: Area = Length x Width; Loyalty_Score = Total_Purchases x 0.4 + Avg_Order_Value x 0.3 + Frequency x 0.3; Ocean_Proximity = distance((Ocean_Lat, Ocean_Lon), (District_Lat, District_Lon)).

Why is encoding necessary, and which algorithms escape it?

Most machine learning algorithms — linear regression, support vector machines — require numeric input because they use numerical computations to learn the model, and are not inherently capable of interpreting categorical data. Some implementations of decision tree-based algorithms can directly handle categorical data.

Compare ordinal and one-hot encoding, and say when each is appropriate.

Ordinal encoding replaces each category with an integer, generally assigned arbitrarily; it is preferred when the variable has an inherent order (small = 0, medium = 1, large = 2). One-hot encoding replaces the variable with a set of binary variables, one per category, each taking 1 if the observation shows that category and 0 otherwise; it treats each category independently, which suits nominal features such as colors. OHE increases dimensionality and may not suit high-cardinality features; a remedy is to encode only the most frequent categories and let the rest be represented as 0s in all binary variables.

Why should Likert responses not simply be averaged?

Because the Likert scale is strictly an ordinal scale, even though it is usually treated as an interval one, and arithmetic operations cannot be conducted on it (Wu and Leung 2017). Three reasons are given: respondents are often reluctant to express a strong opinion and gravitate to the neutral midpoint; averaging assumes equal emotional distance between mild and strong (dis)agreement; and fundamentally, the numbers are not numbers as such, but a means of ranking responses. Add the J-shaped distribution of reviews (Hu, Zhang and Pavlou 2009): people write reviews only when extremely satisfied or extremely unsatisfied.

Explain the Y2K22 bug.

The date 2022-01-01T00:01 was encoded into the signed integer 2201010001. A signed 32-bit integer covers [-2^31, 2^31 - 1] = [-2147483648, 2147483647], and 2201010001 > 2147483647: the encoded date overflows the type. It is the modern descendant of the year 2000 problem.

Why does feature scaling matter for distance-based algorithms? Give the worked example.

Because many classifiers use the Euclidean distance, and if one feature has a broad range the distance is governed by that feature. With age ∈ [0,120] and income ∈ [0,100000]: p1 = (50, 10000), p2 = (50, 20000) at distance 10000.00, p3 = (60, 10000) at distance 10.00, and p4 = (60, 20000) at distance 10000.00 — indistinguishable from p2 although it differs in both features. Age has been erased by the units of income.

Write the three scaling formulas and say what each guarantees.

Min-max: x' = a + (x - min)(b - a)/(max - min), rescaling into [a,b], typically [0,1]. Standardization: x' = (x - mean)/sd, giving zero mean and unit variance. Robust scaling: x' = (x - Q2)/(Q3 - Q1), designed to be robust to outliers because it uses the median and the interquartile range instead of the mean and the range.

What happens to the mean in a skewed distribution, and what is the long tail?

The mean is dragged into the tail and separates from the median: on the Gaussian example both are 173 cm, on the skewed one the mean is 103 158 262 914 against a median of 36 666 524 821. The Long Tail is the concept where a large number of niche products collectively generate more sales than a few bestsellers — a right-skewed distribution, made possible on sites like Amazon that are not limited by shelf space. Skewed distributions can be transformed with mathematical functions such as the logarithm.

Contrast equal-width and equal-frequency binning.

Equal-width divides the range of values into equal-sized intervals (values 0 to 100 into 10 bins gives width 10); it can create empty or sparse bins, especially with skewed data or outliers. Equal-frequency divides the values into bins with the same number of observations (100 observations into 10 bins gives 10 each); it creates balanced bins that handle skewed data and outliers better, at the cost of distorting the distribution and creating irregular bin widths. Binning generally reduces the effects of minor observation errors by replacing the values in a bin with a representative central value.

What is the aggregation trap?

Averaging averages. Correct: sum of sums, (1+2) + (3+4+5) = 15. Wrong: avg(avg(1,2), avg(3,4,5)) = avg(1.5, 4) = 2.75, whereas avg(1,2,3,4,5) = 3. The group sizes differ, so the second average silently re-weights the data. Pay attention to the aggregation operator.

Why is exhaustive feature selection intractable?

Because the number of subsets of a feature set S is |P(S)| = 2^|S| - 1 (excluding the empty set): 8 subsets for 3 features, 16 for 4, 1024 for 10. The dummy algorithm — test each subset and keep the one minimizing the error — is therefore computationally intractable for all but the smallest feature sets. Real approaches are characterized by a search technique and an evaluation measure.

Distinguish the filter, wrapper and embedded strategies.

Filter: select variables regardless of the model, based on general properties such as variance or correlation with the target. Wrapper: train a model on each subset and score it by its error rate on a hold-out set — computationally intensive but good results; methods include forward selection, backward elimination and exhaustive search. Embedded: add or remove features while building the model, based on prediction errors, so that selection and classification happen simultaneously — LASSO being the standard example.

How does LASSO perform feature selection?

By adding to the least-squares objective a penalty proportional to the absolute values of the coefficients: min( SUM (yi - y_hat_i)^2 + lambda * SUM |bj| ). The regularization parameter lambda controls the strength of the penalty; the absolute-value penalty shrinks some coefficients to exactly 0, thereby removing irrelevant features. The optimal lambda is determined with cross-validation.

Explain the two uses of Pearson's correlation in feature selection.

Pearson's correlation measures the linear relationship between two numeric variables: close to 1 means positive correlation, -1 negative, 0 none. Between features: two highly correlated features are redundant, so keep one — the other contributes unnecessary noise. Between feature and target: a feature whose coefficient sits between -0.3 and 0.3 may not be very predictive and can potentially be filtered out.

Describe PCA and the steps to compute it.

PCA is a linear dimensionality reduction technique that preserves as much of the variance as possible in fewer dimensions, by linearly transforming the data onto a new coordinate system whose directions — the principal components — capture the largest variation; the first component captures the highest variance, the second the next, and so on. Steps: standardize the features (PCA is sensitive to scale), compute the covariance matrix, take its eigenvectors as the directions and eigenvalues as the magnitude of variance along them; the eigenvector with the largest eigenvalue is PC1. On Iris, PC1 explains 92.46%, PC2 5.31%, PC3 1.71%, and the heaviest PC1 loading is 0.857 on petal length.

Compare semantic and primary key-based integration.

Primary key-based integration matches unique identifiers, works when both datasets have a well-defined consistent schema with common key fields, is simpler but less flexible, and is limited to datasets that share a key. Semantic integration works from the meaning of the data, merging sources that use different names, terminologies or structures for the same concepts; it uses ontologies or data dictionaries to map concepts, is flexible across schemas, and is complex because it requires domain semantics — spatial data integrated into maps being the example given.

Why does the order of pre-processing transformations matter? Give the two examples.

Because each transformation changes the statistics the next one reads. Normalization should be applied before rebalancing, since rebalancing can alter average and standard deviations; and applying feature engineering before or after rebalancing produces different results depending on the dataset and the algorithm. The deck concludes: it is more an art than a science, at least for now.

What is the difference between ETL and ELT?

ETL — Extract (pull data from multiple sources: databases, APIs, flat files), Transform (clean, standardize, transform into the desired format), Load (into a target database or data warehouse). ELT loads the data into a storage system such as a data lake first, and then transforms it within the storage system.