Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Regression lessons
Curves and trees · ML-R07 · 25–40 MIN

Make curved features

Understand expansion before fitting.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeAdapt the Python
  3. TransferAdapt the Python
  4. ApplyBuild a guided full workflow

Understand the idea

PolynomialFeatures constructs powers and interactions. The subsequent regression remains linear in those expanded features, while predictions can curve in the original inputs.

Illustrative data

Illustrative data
ColumnValues
x0, 1, 2, 3, 4, 5

Click the highlighted code to change the result.

expander = PolynomialFeatures(degree=, include_bias=False)
expanded = expander.fit_transform(example[["x"]])
Degree 2 creates powers 1 through 2. The next lesson fits a model to these columns.input xfeature xfeature x^200011122433944165525

Degree 2 creates powers 1 through 2. The next lesson fits a model to these columns.

What the syntax does

PolynomialFeatures(degree=2, include_bias=False)
  • Creates powers and products of the input columns.
  • include_bias: False, True
  • degree: 1, 2, 4
  • degree is a nonnegative integer; the default is 2. include_bias=False omits the all-ones feature when the later estimator supplies an intercept.
  • Greater degree adds flexibility and terms; use matching training folds and inspect extrapolation risk.

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
CURVE48 · first 8 rows
xy
-315.9571
-2.8723413.0709
-2.7446814.9362
-2.6170214.45
-2.489369.39011
-2.36179.68978
-2.2340411.2101
-2.106389.96814
Your task
  1. Expand CURVE48 x into x and x squared.
answer
Hints

Think: A curved representation can be built before fitting a linear estimator.

Tools: PolynomialFeatures, degree and include_bias.

Approach: Fit the degree-two expansion to the single x column and inspect its transformed columns.

Explained solution
from sklearn.preprocessing import PolynomialFeatures
expander=PolynomialFeatures(degree=2,include_bias=False)
answer=expander.fit_transform(df[['x']])

Excluding the bias avoids a duplicate constant term; the two output columns carry the original input and its square.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.