Problem 271880 · easy · Level 02 Linear Data Structures

Which Fare Rule Fits Best?

loss functions · model selection · squared error · absolute error · outliers

A taxi company wants a simple rule for its fares: "a pounds plus b pounds per kilometre". The analysts proposed several rules rules[k] = (a, b), and the company has a log of trips: trip i covered km[i] kilometres and cost fare[i] pounds. Rule k predicts a + b * km[i] for trip i.

Write pick_rules(km, fare, rules) that returns a tuple (best_sq, best_abs): the index of the rule with the smallest mean squared error on the log, and the index of the rule with the smallest mean absolute error. On a tie, the smaller index wins.

Examples

Input:  km = [1, 2, 3, 4, 5], fare = [3, 5, 7, 9, 30], rules = [(1, 2), (-3, 5)]
Output: (1, 0)
Explanation: rule 0 predicts 3, 5, 7, 9, 11: perfect except for the last trip (a long wait
in traffic), which it misses by 19. Squared errors 0 + 0 + 0 + 0 + 361 = 361, absolute 19.
Rule 1 predicts 2, 7, 12, 17, 22 and misses by 1, 2, 5, 8, 8: squared 158, absolute 24.

Input:  km = [2, 4], fare = [6, 10], rules = [(2, 2), (0, 3), (2, 2)]
Output: (0, 0)

Constraints

  • 1 <= len(km) <= 2000, 1 <= len(rules) <= 50
  • km, fare, a and b are whole numbers between -10**4 and 10**4

Goals

  • Score several candidate prediction rules on the same data with two different losses
  • Choose the best rule under each loss
  • See that one unusual example can make the two losses disagree
Starting Python…