Understand the idea
Expansion, scaling and Ridge belong together inside CV. Scaling after expansion makes regularisation act on comparable terms. Compare a curve with a line on identical folds. Ridge adds an L2 penalty that discourages large expanded-feature coefficients (alpha=1 by default); expansion creates the terms, scaling makes their numerical units comparable, and Ridge learns the prediction weights.
Illustrative data
| Column | Values |
|---|---|
x | 0, 1, 2, 3, 4, 5 |
Click the highlighted code to change the result.
model = Pipeline([
("polynomial", PolynomialFeatures(degree=, include_bias=False)),
("scale", StandardScaler()),
("model", Ridge()),
])
answer = model.named_steps["polynomial"].fit_transform(example[["x"]])The polynomial step creates 2 power columns. This expands the inputs; it does not fit the prediction model.
What the syntax does
model.named_steps['polynomial']- named_steps selects a
Pipelinestep by its declared name. - Here polynomial expands
xinto power columns. - Calling its
fit_transformprepares those columns; the scale and prediction model steps have not been fitted.
- The prepare step contains fitted preparation; model contains the prediction estimator.
- A ColumnTransformer also exposes its named_transformers_ when inspecting encoded categories.
- named_steps selects a
Supplied for this practice
These objects are prepared afresh before your editor runs.
X- Feature dataframe for the declared population, preserving row indices.
X = df[['x']] y- Target series, aligned with
X.y = df.y X_train/X_test/y_train/y_test- Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with
X_train. Final-test targets, aligned withX_test.X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Outputs you create
answer- The requested result, with the values, labels and row order described by this task.
x | y |
|---|---|
| -3 | 15.9571 |
| -2.87234 | 13.0709 |
| -2.74468 | 14.9362 |
| -2.61702 | 14.45 |
| -2.48936 | 9.39011 |
| -2.3617 | 9.68978 |
| -2.23404 | 11.2101 |
| -2.10638 | 9.96814 |
- Create the degree-two polynomial pipeline.
- Store the transformed training
xandx² columns inanswer, one row per training example.
answerHints
Think: Expansion belongs before scaling and the regularised estimator.
Tools: Pipeline, PolynomialFeatures, StandardScaler and Ridge.
Approach: Build the three named steps, then inspect the polynomial step’s training output.
Explained solution
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures,StandardScaler
from sklearn.linear_model import Ridge
model=Pipeline([('polynomial',PolynomialFeatures(degree=2,include_bias=False)),('scale',StandardScaler()),('model',Ridge())])
answer=model.named_steps['polynomial'].fit_transform(X_train)
The dimensions expose the representation entering later preparation; they do not by themselves establish predictive quality.