A Colour It Never Saw

Machine Learning in CodeMedium+10 XP+10

A Colour It Never Saw

A paint shop's model has a colour column. Training taught it some colours. Later, a customer asks about a colour it has never seen, and that must not crash anything.

Task: write encode_colours(train_colours, new_colours).

  • Put each list in a one-column DataFrame whose column is named "colour".
  • Fit a OneHotEncoder(handle_unknown="ignore") on the training colours.
  • Transform the new colours with it. An unseen colour comes out as all zeroes.
  • Return a dict:
    • "columns": the encoder's output column names, from get_feature_names_out(), as a list of strings.
    • "rows": the encoded new colours as a list of lists of whole numbers (0 or 1), one inner list per new colour.

Examples

train_colours = ["red", "green", "red", "blue"]
new_colours = ["blue", "yellow"]
returns {'columns': ['colour_blue', 'colour_green', 'colour_red'], 'rows': [[1, 0, 0], [0, 0, 0]]}
train_colours = ["tan", "teal", "tan"]
new_colours = ["teal", "tan", "teal"]
returns {'columns': ['colour_tan', 'colour_teal'], 'rows': [[0, 1], [1, 0], [0, 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