Linear Regression

Python · Machine Learning (Scikit-Learn)

Theory

Linear regression predicts a number as a weighted sum of the features plus a constant: price = coef x area + intercept. fit finds the coefficients that minimise the sum of squared errors on the training data. Each coefficient (model.coef_) says how much the prediction changes when that feature rises by one unit with the others held fixed, and model.intercept_ is the prediction when all features are 0.

Regression is judged on held-out data with error metrics. MAE (mean absolute error) is the average size of a miss in the target's units, such as 1.1 lakh. RMSE (root mean squared error) squares errors before averaging, so large misses count more; compute it as np.sqrt(mean_squared_error(y, pred)). R-squared (r2_score) is the share of variance explained: 1 is perfect, 0 is no better than predicting the mean, and it can go negative.

Why we use it

It is fast, needs little data and is easy to explain: every coefficient has a direct meaning. It is the baseline every regression problem should start with, and its metrics tell you how far off predictions typically are.

When to use it

Use it for numeric targets with roughly straight-line relationships, such as price from area or sales from ad spend. For curved relationships or interactions try trees or random forests; with many correlated features use Ridge or Lasso.

How it works

  1. Numeric target y and features X
  2. Split into train and test
  3. LinearRegression().fit(X_train, y_train) minimises squared error
  4. Read coef_ and intercept_
  5. predict(X_test) and compute MAE, RMSE, R-squared
  6. Errors acceptable and residuals patternless? Yes: Use or deploy the model. No: Try features, Ridge or tree models.
  7. Numeric predictions

Syntax

from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X_train, y_train)
model.coef_, model.intercept_
pred = model.predict(X_test)
mean_absolute_error(y_test, pred)  r2_score(y_test, pred)
np.sqrt(mean_squared_error(y_test, pred))

Example

model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print(mean_absolute_error(y_test, pred), r2_score(y_test, pred))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic