Just Enough Bend

Machine Learning in CodeMedium+10 XP+10

Just Enough Bend

More bend costs more columns, so you want the smallest degree that already fits the data well.

Write smallest_good_degree(xs, ys, max_degree, target).

  • Try each degree from 1 up to max_degree, in order.
  • For each one, fit make_pipeline(PolynomialFeatures(degree), LinearRegression()) on all the points, with xs as the only feature.
  • Score it on the same points with score (this gives R²).
  • Return the first degree whose R² is at least target, as an int.
  • If no degree up to max_degree reaches target, return 0.

Compare the unrounded R² with target.

Examples

xs = [0, 1, 2, 3, 4, 5, 6]
ys = [2.0, 1.1, 2.1, 4.9, 10.2, 16.8, 26.1]
max_degree = 4
target = 0.99
returns 2
xs = [1, 2, 3, 4, 5]
ys = [3.1, 4.9, 7.2, 8.8, 11.1]
max_degree = 3
target = 0.95
returns 1

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run