fit and predict

~10 mincode completion

Write fit_and_predict(x_train, y_train, x_new) that fits a on one feature and returns its predictions for x_new.

All three arrive as flat 1-D arrays, so you will need to reshape the two x arrays.

Examples

A perfect doubling relationship is learned exactly

Input
fit_and_predict([1, 2, 3, 4], [2, 4, 6, 8], [5])
Output
[10]

A line with an offset is learned, intercept included

Input
fit_and_predict([0, 1, 2], [1, 3, 5], [3, 4])
Output
[7, 9]

Hints

Hint 1

Reshape so the two arrays broadcast against each other.

Hint 2

Watch for this: passed 1d X to fit.

Requirements

  • x_train: 1-D array of training inputs

  • y_train: 1-D array of training targets

  • x_new: 1-D array of inputs to predict for

  • Return a 1-D array of predictions for x_new.

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

7 employers weight this skill

2 health and bio companies, 2 quant funds, 2 enterprise vendors, 1 AI product company. Top match scores 50.

Python
import numpy as np
from sklearn.linear_model import LinearRegression

def fit_and_predict(x_train, y_train, x_new):
    """
    Fit a one-feature linear model and predict.

    Args:
        x_train: 1-D array of training inputs
        y_train: 1-D array of training targets
        x_new: 1-D array of inputs to predict for

    Returns:
        A 1-D array of predictions for x_new.
    """
    # YOUR CODE HERE
    pass

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.