Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

fit and predict

~10 mincode completion

Every model in scikit-learn has the same two methods, and once you have seen them once you have seen them all:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X, y)              # learn from the data
model.predict(X_new)         # apply what was learned

That uniformity is the library's whole design. Swapping LinearRegression for RandomForestRegressor changes one line and nothing else.

Shapes matter, and this is where everybody's first attempt fails. X must be 2-D, shaped (n_samples, n_features), even when there is only one feature. y is 1-D, one label per sample.

X = np.array([1, 2, 3])              # shape (3,)  -> ValueError
X = np.array([[1], [2], [3]])        # shape (3, 1) -> correct
X = np.array([1, 2, 3]).reshape(-1, 1)   # the usual fix

reshape(-1, 1) means "one column, and work out the number of rows yourself". You will type it many times.

After fitting a linear model you can read what it learned: model.coef_ holds the slope per feature, model.intercept_ the offset. The trailing underscore is a scikit-learn convention meaning "learned during fit", so it does not exist until you have called fit.

Your task:

Write fit_and_predict(x_train, y_train, x_new) that fits a LinearRegression 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.

Example Tests

A perfect doubling relationship is learned exactly

Input: {"x_new":[5],"x_train":[1,2,3,4],"y_train":[2,4,6,8]}

Expected: [10]

A line with an offset is learned, intercept included

Input: {"x_new":[3,4],"x_train":[0,1,2],"y_train":[1,3,5]}

Expected: [7,9]

One prediction is returned per input row

Input: {"x_new":[10,20,30],"x_train":[1,2,3],"y_train":[1,2,3]}

Expected: [3]

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…