Great question! The confusion arises from the difference between univariate polynomial features and multivariate polynomial features. Let's break it down:
Understanding Polynomial Features
When you apply a polynomial transformation to your dataset, especially with multiple features, the transformation doesn't just square each individual feature. Instead, it includes all possible combinations of features up to the specified degree. This includes:
- Original Features (Degree 1)
- Squared Features (Degree 2)
- Interaction Terms (Products of Different Features)
Calculating the Number of Features
For a polynomial degree of 2 and ( n ) original features, the total number of new features created can be calculated using the formula for combinations with repetition:
[
\text{Number of features} = \frac{(n + d)!}{n! \cdot d!}
]
Where:
- ( n ) = number of original features
- ( d ) = degree of the polynomial
In your case:
- ( n = 4 ) (original features)
- ( d = 2 ) (degree)
[
\text{Number of features} = \frac{(4 + 2)!}{4! \cdot 2!} = \frac{720}{24 \cdot 2} = 15
]
What Are These 15 Features?
Let's enumerate them for clarity:
- Bias Term (if
include_bias=True)
- Original Features:
- ( x_1 )
- ( x_2 )
- ( x_3 )
- ( x_4 )
- Squared Features:
- ( x_1^2 )
- ( x_2^2 )
- ( x_3^2 )
- ( x_4^2 )
- Interaction Terms:
- ( x_1x_2 )
- ( x_1x_3 )
- ( x_1x_4 )
- ( x_2x_3 )
- ( x_2x_4 )
- ( x_3x_4 )
Note: If include_bias=False is set in PolynomialFeatures, the bias term (constant 1) is excluded.
Why Not Just 8 Features?
You initially thought each of the 4 features would transform into 2 (the original and its square), totaling 8. However, this approach ignores the interaction terms, which are also part of the polynomial features in a multivariate setting. These interaction terms are crucial as they allow the model to capture relationships between different features, potentially improving its performance.
Visual Representation:
Here's a simple representation of how the transformation works for two features ( x_1 ) and ( x_2 ):
[
\text{Original Features}: x_1, x_2
]
[
\text{Degree 2 Polynomial Features}:
]
[
1, x_1, x_2, x_1^2, x_1x_2, x_2^2
]
This results in 6 features instead of just 4 * 2 = 8 if you were to naively double the feature count without considering interactions.
Conclusion
The PolynomialFeatures transformation in scikit-learn includes all polynomial combinations of the features up to the specified degree. For 4 original features and degree 2, this results in 15 features because it accounts for all individual, squared, and interaction terms.
I hope this clarifies why the feature count increases to 15!