Interaction features capture the combined effect of two features that may not be visible when looking at each feature independently. For example, a model predicting house prices might benefit from a "rooms x area_per_room" interaction that neither feature alone conveys. Pairwise interactions are generated by multiplying each unique pair of features.
Given a feature matrix (samples x features), generate all pairwise interaction features by multiplying each unique pair of features, and append them to the original features.
For each sample with d features [x_1, x_2, ..., x_d], compute all unique pairwise products:
interactions=[xi⋅xj∣1≤i<j≤d]The output per sample is the original features followed by the interactions. The number of interactions is d(d-1)/2.
Input:
X = [[1, 2, 3]]
Output:
[[1, 2, 3, 2, 3, 6]]
Original features: [1, 2, 3]. Pairwise products: 12=2, 13=3, 2*3=6. Result: [1, 2, 3, 2, 3, 6].
Input:
X = [[1, 2], [3, 4]]
Output:
[[1, 2, 2], [3, 4, 12]]
With 2 features there is one interaction per sample: 12=2 and 34=12.
For each row, use nested loops: for i in range(d), for j in range(i+1, d), append row[i] * row[j] to the interactions list. Then concatenate original features with interactions.
Make sure to use list(row) to copy the original features before concatenating, so you don't modify the input. The key constraint is i < j to avoid self-interactions and duplicates.
Sign in to take notes on this problem
Accepts: array
Interaction features capture the combined effect of two features that may not be visible when looking at each feature independently. For example, a model predicting house prices might benefit from a "rooms x area_per_room" interaction that neither feature alone conveys. Pairwise interactions are generated by multiplying each unique pair of features.
Given a feature matrix (samples x features), generate all pairwise interaction features by multiplying each unique pair of features, and append them to the original features.
For each sample with d features [x_1, x_2, ..., x_d], compute all unique pairwise products:
interactions=[xi⋅xj∣1≤i<j≤d]The output per sample is the original features followed by the interactions. The number of interactions is d(d-1)/2.
Input:
X = [[1, 2, 3]]
Output:
[[1, 2, 3, 2, 3, 6]]
Original features: [1, 2, 3]. Pairwise products: 12=2, 13=3, 2*3=6. Result: [1, 2, 3, 2, 3, 6].
Input:
X = [[1, 2], [3, 4]]
Output:
[[1, 2, 2], [3, 4, 12]]
With 2 features there is one interaction per sample: 12=2 and 34=12.
For each row, use nested loops: for i in range(d), for j in range(i+1, d), append row[i] * row[j] to the interactions list. Then concatenate original features with interactions.
Make sure to use list(row) to copy the original features before concatenating, so you don't modify the input. The key constraint is i < j to avoid self-interactions and duplicates.
Sign in to take notes on this problem
Accepts: array