Linear regression helps us find a straight line that best fits data points. It predicts one value from another using a simple formula.
Linear regression with scikit-learn in ML Python
from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) predictions = model.predict(X_test)
X_train should be a 2D array with features (like size, age).
y_train is a 1D array with target values (like price).
from sklearn.linear_model import LinearRegression model = LinearRegression() X = [[1], [2], [3], [4]] y = [2, 4, 6, 8] model.fit(X, y) pred = model.predict([[5]])
model = LinearRegression(fit_intercept=False) model.fit(X, y) pred = model.predict([[5]])
This program trains a linear regression model to predict exam scores based on hours studied. It prints the slope, intercept, prediction for 6 hours, and training accuracy.
from sklearn.linear_model import LinearRegression import numpy as np # Sample data: hours studied vs exam score X = np.array([[1], [2], [3], [4], [5]]) y = np.array([50, 60, 65, 70, 80]) # Create and train model model = LinearRegression() model.fit(X, y) # Predict score for 6 hours studied predicted_score = model.predict([[6]]) # Print coefficients and prediction print(f"Coefficient (slope): {model.coef_[0]:.2f}") print(f"Intercept: {model.intercept_:.2f}") print(f"Predicted score for 6 hours: {predicted_score[0]:.2f}") # Check training accuracy score = model.score(X, y) print(f"Training R^2 score: {score:.2f}")
Linear regression assumes a straight-line relationship between input and output.
Input features must be numeric and shaped correctly (2D array).
R^2 score shows how well the model fits the data (1.0 is perfect).
Linear regression finds a line to predict one value from another.
Use scikit-learn's LinearRegression to train and predict easily.
Check model quality with R^2 score and understand slope/intercept.
Practice
Solution
Step 1: Understand the purpose of linear regression
Linear regression aims to model the relationship between input variables and a continuous output by fitting a line.Step 2: Compare with other tasks
Classification assigns categories, clustering groups data, and feature reduction simplifies data, which are different tasks.Final Answer:
To find a line that predicts a continuous value from input data -> Option AQuick Check:
Linear regression predicts continuous values [OK]
- Confusing regression with classification
- Thinking linear regression clusters data
- Believing it reduces features
Solution
Step 1: Recall correct Python import syntax
Python imports classes using 'from module import ClassName' syntax.Step 2: Match with scikit-learn structure
LinearRegression is inside sklearn.linear_model, so correct import is from sklearn.linear_model import LinearRegression.Final Answer:
from sklearn.linear_model import LinearRegression -> Option AQuick Check:
Correct import syntax = from sklearn.linear_model import LinearRegression [OK]
- Using wrong import order
- Trying to import directly from sklearn
- Using incorrect module names
from sklearn.linear_model import LinearRegression import numpy as np X = np.array([[1], [2], [3], [4], [5]]) y = np.array([2, 4, 6, 8, 10]) model = LinearRegression() model.fit(X, y) print(round(model.coef_[0], 1))
Solution
Step 1: Understand the data relationship
X values are 1 to 5, y values are exactly double X (2,4,6,8,10), so slope should be 2.Step 2: Check model coefficient
LinearRegression fits y = coef * X + intercept. coef_ will be close to 2.0 here.Final Answer:
2.0 -> Option BQuick Check:
Slope of y=2x is 2.0 [OK]
- Confusing coefficient with intercept
- Not rounding output
- Assuming coefficient is 1 or 10
from sklearn.linear_model import LinearRegression X = [[1], [2], [3]] y = [2, 4, 6] model = LinearRegression() model.fit(X, y) print(model.predict([4]))
Solution
Step 1: Check input shapes for fit and predict
fit accepts list of lists for X, so no error there. But predict expects 2D array, [4] is 1D.Step 2: Fix predict input shape
Predict should get [[4]] (2D) not [4] (1D) to avoid shape error.Final Answer:
Predict input shape is incorrect, should be 2D array -> Option DQuick Check:
Predict input must be 2D array [OK]
- Passing 1D array to predict
- Assuming fit needs numpy arrays
- Wrong class instantiation
Solution
Step 1: Understand R² score meaning
R² (coefficient of determination) measures how well the model explains variance in the target.Step 2: Interpret 0.85 R²
A score of 0.85 means 85% of the variance in the target is explained by the model.Final Answer:
The model explains 85% of the variance in the target variable -> Option CQuick Check:
R² = variance explained, not accuracy or error rate [OK]
- Confusing R² with accuracy
- Thinking R² is probability
- Assuming R² is error rate
Ready to prove it?
Pass the test and this pattern moves unknown
