Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › Linear Regression in Python: Train, Predict, and Read the Re

Linear Regression in Python: Train, Predict, and Read the Result

Linear regression in Python means training a model that estimates a numeric value from other variables, using libraries such as scikit-learn and Pandas. The workflow has three steps: prepare the data, call fit() to train, and predict() to generate estimates. R² helps measure fit, but it does not prove that one variable causes another.

Topics: regressão, machine learning

What do you need in place before you run a linear regression in Python?

Three things: somewhere to run code, data organized in a table, and a numeric target variable. The environment is usually an IDE or Jupyter Notebook, and NumPy and Pandas handle the table work.

Before training, the data goes through cleaning and preparation: missing values, wrong types, duplicated columns, and outliers. Outliers matter a lot in linear regression because the method minimizes squared error, so one point far from the rest pulls the line toward it.

You do not need to know how to program first. The Python for Data Science and Analytics course starts at the basics — IDE and Jupyter Notebook setup, basic functions, loops and conditionals — and only then moves into machine learning.

How do you train a linear regression model with scikit-learn?

scikit-learn keeps the workflow to a few lines. You separate X (input variables) and y (target), split into train and test, and call the estimator. from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = LinearRegression() model.fit(X_train, y_train)

fit() adjusts the coefficients to minimize the sum of squared errors on the training set. random_state fixes the split so the result is reproducible.

A single train/test split can mislead you. Cross-validation runs training across several partitions and shows whether performance holds up. That is the difference between a stable fit and a lucky number.

How do you make predictions and compare them with actual values?

After fit(), predict() returns an estimate for each row. On the test set you compare y_pred with y_test. y_pred = model.predict(X_test)

To measure error, MAE and RMSE are more informative than R² when you want to know the size of the error in the target's own unit. RMSE penalizes large errors more; MAE is easier to read.

It is worth looking at residuals: the gap between predicted and actual. If residuals form a pattern — a curve, a funnel, growth over time — the linear model is leaving structure out.

What does R² actually tell you — and what does it not tell you?

R² measures how much of the target's variation the model explains inside the set being evaluated. On training data it usually lands between 0 and 1, and on test data it can go negative when the model is worse than simply predicting the mean.

A high R² does not prove causality. It also does not prove the model will work on new data, or that the variables you used are the right ones.

There are well-known ways to inflate R² without real predictive power: adding many variables, using variables that are consequences of the target, leaving a time trend on both sides, or evaluating on the same set used for training.

That is why the number alone decides nothing. It sits alongside cross-validation, residual analysis, and domain knowledge.

How do you interpret coefficients without confusing correlation with causation?

Each coefficient says how much the prediction changes when that variable increases by one unit, holding the others constant. That is a statement about the model, not about the world.

If you measure hours studied and exam score, the coefficient tells you what the fitted line does with those two columns. It does not tell you that adding hours causes the score to rise for every student, because other things — prior knowledge, sleep, test format — are not in the model.

A useful habit: read the coefficient, then ask what is missing from the model. Causal claims need design — random assignment, control groups, or causal inference methods — not a regression coefficient.

Feature selection and cross-validation, both covered in the course, help you check whether a variable is carrying weight or just noise.

Where does linear regression fit in a full data science workflow?

Linear regression is usually the first model you learn and the baseline you compare everything else against. It is fast, readable, and it shows whether the problem is even linear.

From there, the same workflow extends to logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, and LightGBM — all covered in the course, along with feature selection and cross-validation.

The Python for Data Science and Analytics course runs from zero to advanced across three main modules — Basic, Intermediate, and Advanced — plus bonus modules, and closes with a final project: exploratory analysis and end-to-end machine learning. Lessons are recorded, watched at your own pace, and access does not expire. There are guided exercises, real market projects for a portfolio, a certificate of completion, and an exclusive community. Enrollment is R$ 470, or 12 payments of R$ 20,37 on a card, through the Hotmart checkout, which also accepts boleto. Details are at https://python.paanalytics.net/.

MetricWhat it measuresWatch out for
R²Share of the target's variation explained inside the evaluated setOptimistic on training data; says nothing about causality
MAEAverage error in the target's own unitTreats large and small errors with the same weight
RMSEError in the target's unit, with larger errors weighted moreA few extreme points can dominate the score
Residual plotWhere the model is wrong and whether the error has structureHas to be read, not scored

Definitions of standard regression metrics; no product claims.

Start training your first linear regression model

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Do I need to know how to program before learning linear regression in Python?

No. The course assumes no prior programming experience and starts with IDE and Jupyter Notebook setup, basic functions, loops, and conditionals before it reaches machine learning.

Should I judge my model with R² or with RMSE?

Use both, because they answer different questions. R² tells you how much of the target's variation the model explains inside the evaluated set. RMSE tells you the typical error in the target's own unit, which is usually easier to explain to someone else.

Can R² be negative?

Yes, on test data. A negative R² means the model performs worse than predicting the mean of the target. It usually points to overfitting, an unlucky split, or a relationship a straight line cannot capture.

What comes after linear regression in a machine learning path?

Logistic regression for classification, then clustering and other supervised models: K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, and LightGBM. Feature selection and cross-validation run across all of them.

How is the course delivered, and how long do I keep access?

Lessons are recorded in high quality and watched at your own pace. Access is unlimited and does not expire, and the course includes guided exercises, real market projects for a portfolio, a certificate of completion, and an exclusive community.

Ler em português →