Let the Held-Back Rows Decide

Machine Learning in CodeMedium+10 XP+10

Let the Held-Back Rows Decide

You have one set of points and several degrees to choose from. The honest way to choose is to hold some points back and see which degree does best on them.

Write pick_degree(xs, ys, degrees, seed).

  • Split the points with train_test_split(X, ys, test_size=0.3, random_state=seed), where X is xs as a one-column table.
  • For each degree in degrees, fit make_pipeline(PolynomialFeatures(degree), LinearRegression()) on the training part and score it on both parts.
  • Pick the degree with the highest test score, comparing scores rounded to 3 places. If two degrees tie, pick the smaller degree.

Return a dict:

  • "degree": the chosen degree, as an int.
  • "train": its training score, rounded to 3 decimal places.
  • "test": its test score, rounded to 3 decimal places.

Examples

xs = [0.34, 0.38, 0.45, 0.64, 0.95, 1.14, 1.56, 1.72, 1.73, 1.92, 2.07, 2.33, 2.35, 2.59, 2.94, 2.95, 3.21, 3.83]
ys = [12.05, 11.77, 12.18, 13.6, 14.29, 14.34, 14.93, 15.16, 15.71, 14.59, 14.29, 14.03, 13.2, 12.5, 11.35, 11.18, 9.69, 7.09]
degrees = [1, 2, 3]
seed = 0
returns {'degree': 3, 'train': 0.984, 'test': 0.944}
xs = [0.34, 0.38, 0.45, 0.64, 0.95, 1.14, 1.56, 1.72, 1.73, 1.92, 2.07, 2.33, 2.35, 2.59, 2.94, 2.95, 3.21, 3.83]
ys = [12.05, 11.77, 12.18, 13.6, 14.29, 14.34, 14.93, 15.16, 15.71, 14.59, 14.29, 14.03, 13.2, 12.5, 11.35, 11.18, 9.69, 7.09]
degrees = [1, 2]
seed = 1
returns {'degree': 2, 'train': 0.956, 'test': 0.914}

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