CodeBlanks Logo Icon CodeBlanks

Data and model

Data is the learning source for ML algorithms; it consists of feature and label columns.

Data: rows and columns

ML data is a table. Each row is an example (a house, a customer) and each column is a feature (square metres, age). In Python this table is usually a two-dimensional NumPy array:

import numpy as np
X = np.array([[50, 1],
              [80, 2],
              [120, 3]])
print(X.shape)   # (3, 2): 3 examples, 2 features

scikit-learn always expects X to be two-dimensional; even with a single feature it is written as [[50], [80]].

Model: learned parameters

Training means adjusting the model's parameters to fit the data. In linear regression the parameters are the slope and the intercept; scikit-learn stores them in attributes ending with an underscore:

from sklearn.linear_model import LinearRegression
m = LinearRegression().fit([[1], [2], [3]], [3, 5, 7])
print(m.coef_, m.intercept_)   # [2.] 1.0  ->  y = 2x + 1

The trailing _ is a scikit-learn convention showing that the value was learned during fit.

Practice Read the parameters

Fit a LinearRegression to the given data. Round the slope (coef_[0]) and the intercept (intercept_) to integers with round and print them separated by a space.

Starter code

model.py
from sklearn.linear_model import LinearRegression

X = [[1], [2], [3], [4]]
y = [5, 8, 11, 14]

# buraya yaz

Sample solution

model.py
from sklearn.linear_model import LinearRegression

X = [[1], [2], [3], [4]]
y = [5, 8, 11, 14]

m = LinearRegression().fit(X, y)
print(round(m.coef_[0]), round(m.intercept_))

Expected output

3 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If <code>X.shape</code> is <code>(200, 5)</code>, how many examples are in the dataset?

  • 200 Correct answer
  • 5
  • 1000
  • 205

Explanation: The first dimension is the number of rows (examples), the second the number of columns (features).

2 Print the dimensions of the array.

Question
X = np.array([[1, 2], [3, 4], [5, 6]])
print(X.____)
Answer
X = np.array([[1, 2], [3, 4], [5, 6]])
print(X.shape)

Explanation: shape gives the (rows, columns) pair; here (3, 2).

3 Match the terms.

Term Meaning
row One example
column One feature
coef_ Learned slope
intercept_ Learned intercept

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation