Sitemap

linear regression

7 min readNov 17, 2026

My First Linear Regression in Python

A beginner-friendly, step-by-step guide using pandas, NumPy, and statsmodels

Linear Regression is one of the most useful starting points in machine learning and data analysis. In this guide, we will build a simple regression model that uses a student’s SAT score to predict their GPA. We will explain every line of code, understand the most common beginner mistakes, and learn how to read the model output.

The goal is not to memorize code. The goal is to understand what each line does, what kind of data it expects, and why the steps are necessary.

1. What is Linear Regression?

Linear Regression is a statistical method used to describe the relationship between a dependent variable and one or more independent variables. It can also be used to make predictions.

For example, suppose we want to investigate whether a student’s SAT score is related to their GPA. We can use SAT as the input and GPA as the value we want to predict.

Y = b₀ + b₁X

· Y: the dependent variable — the value we want to predict (GPA).

· X: the independent variable — the input used to make the prediction (SAT).

· b₀: the intercept — the predicted value of Y when X equals zero.

· b₁: the slope — how much the predicted Y changes when X increases by one unit.

In a simple linear regression model, there is one independent variable. If we use two or more independent variables, we have multiple linear regression.

2. Meet the Dataset

Imagine that our pandas DataFrame is called data and contains these columns: SAT, Rand 1,2,3, and GPA. The first two columns could be used as predictors; GPA is the outcome we want to predict in this example.

import pandas as pd
import statsmodels.api as sm

# Example: load your dataset
# data = pd.read_csv(‘your_file.csv’)

print(data.head())
print(data.dtypes)

data.head() displays the first five rows by default. It helps us inspect the values. data.dtypes shows the data type of every column.

What do the data types mean?

· int64: whole-number values, such as 1200 or 3.

· float64: decimal values, such as 3.75.

· object or string: often text values, although an object column can also contain mixed types.

In our example, the output showed SAT and Rand 1,2,3 as int64, and GPA as float64. That tells us the columns in data are already numeric.

3. Series vs DataFrame: One Bracket or Two?

This distinction is important in pandas. Selecting one column with one pair of square brackets returns a Series. Selecting it with two pairs returns a DataFrame.

sat_series = data[‘SAT’] # Series (one-dimensional)
sat_frame = data[[‘SAT’]] # DataFrame (two-dimensional)

two_columns = data[[‘SAT’, ‘Rand 1,2,3’]]

Both sat_series and sat_frame contain the SAT values. The difference is their structure. statsmodels can work with either in many cases, but understanding the difference helps avoid shape and selection mistakes.

Code

What it selects

Result type

data[‘SAT’]

One column

Series

data[[‘SAT’]]

One column

DataFrame

data[[‘SAT’, ‘GPA’]]

Two columns

DataFrame

4. The Mistake That Caused UFuncTypeError

The error in our troubleshooting session was:

UFuncTypeError: ufunc ‘maximum’ did not contain a loop with signature matching types (dtype(‘<U10’), dtype(‘<U10’))

The important clue is dtype(‘<U10’). It indicates that NumPy was handling Unicode text values (strings), not numeric values. statsmodels tried to inspect the values while adding a constant, but it could not perform a numeric operation on text.

The key mix-up

x1 = [[‘SAT’, ‘Rand 1,2,3’]]

This creates a Python list containing the literal text ‘SAT’ and ‘Rand 1,2,3’. It does not select the SAT values from the DataFrame. The column names are labels; they are not the actual observations.

To select the actual data, we must select the columns from the DataFrame:

x1 = data[[‘SAT’]]

Remember: data[[‘SAT’]] means “get the SAT column from the DataFrame named data.” [[‘SAT’]] by itself is only a list containing text.

Why did data.dtypes look correct?

Because data and x1 are separate variables. data can contain numeric columns while x1 still contains an incorrectly created list of strings. Always inspect the variable you are actually passing into the model.

print(type(x1))
print(x1)
print(getattr(x1, ‘dtype’, ‘No dtype’))

A pandas DataFrame has .dtypes (plural), while a pandas Series or NumPy array has .dtype (singular). A plain Python list does not have a .dtype attribute, which is why getattr(…, ‘No dtype’) displayed ‘No dtype’.

5. Build a Simple Linear Regression Model

Step 1 — Choose X and Y

x1 = data[[‘SAT’]]
y = data[‘GPA’]

x1 contains the independent variable (SAT). y contains the dependent variable (GPA). Notice that we use double brackets for x1 so it remains a two-dimensional DataFrame, and single brackets for y so it is a Series.

Step 2 — Convert the data type if necessary

x1 = x1.astype(float)
y = y.astype(float)

astype(float) converts the selected values to floating-point numbers. In our example, SAT was already int64 and GPA was already float64, so this conversion was not strictly necessary. It is included to make the numeric type explicit. If a column contains non-numeric text, astype(float) may fail; inspect and clean the data first.

Step 3 — Add the constant

x = sm.add_constant(x1)

Get Maryam Meshref’s stories in your inbox

Join Medium for free to get updates from this writer.

statsmodels does not automatically add the intercept column in this workflow. add_constant() adds a column of 1s. This allows the model to estimate b₀ in the equation Y = b₀ + b₁X.

Step 4 — Fit the model

results = sm.OLS(y, x).fit()

OLS stands for Ordinary Least Squares. It estimates the coefficients by finding the line that minimizes the sum of squared differences between the actual GPA values and the values predicted by the line. The .fit() method performs the estimation and stores the fitted results.

Step 5 — Display the summary

results.summary()

This displays a report containing the estimated coefficients, model fit statistics, and statistical tests.

6. The Complete Code

Here is the full workflow in one place. Run it after loading your dataset into a DataFrame named data.

import pandas as pd
import statsmodels.api as sm

# Inspect the dataset
print(data.head())
print(data.dtypes)

# Select the independent and dependent variables
x1 = data[[‘SAT’]]
y = data[‘GPA’]

# Make the numeric types explicit (optional if already numeric)
x1 = x1.astype(float)
y = y.astype(float)

# Add the intercept column
x = sm.add_constant(x1)

# Fit the Ordinary Least Squares model
results = sm.OLS(y, x).fit()

# Display the regression report
print(results.summary())

7. How to Read results.summary()

The coefficients

Look at the coef column. The row named const is the estimated intercept (b₀). The row named SAT is the estimated slope (b₁). Your fitted equation will have this form:

Predicted GPA = intercept + (SAT coefficient × SAT)

Use the actual coefficient values shown in your own output. Do not copy example values from another dataset.

R-squared

R-squared describes how much of the variation in the dependent variable is explained by the model, within the dataset used to fit it. For example, an R-squared of 0.70 means the model explains about 70% of the variation in GPA in that sample. It does not mean that 70% of predictions are correct.

P-value

The P>|t| column reports a p-value for each coefficient. A small p-value (often compared with 0.05) is evidence against the null hypothesis that the coefficient is zero, under the model’s assumptions. Statistical significance does not automatically mean the relationship is large, useful, or causal.

Other useful fields

· Adj. R-squared: adjusts R-squared for the number of predictors.

· F-statistic and Prob (F-statistic): assess the model as a whole.

· Confidence interval: a range of plausible values for a coefficient under the model assumptions.

· No. Observations: the number of observations used by the model.

8. What if I Want to Use Two Predictors?

If the task asks you to use both SAT and Rand 1,2,3 as independent variables, select both columns from data. This becomes multiple linear regression.

x1 = data[[‘SAT’, ‘Rand 1,2,3’]]
y = data[‘GPA’]

x = sm.add_constant(x1)
results = sm.OLS(y, x).fit()
print(results.summary())

The model now estimates one coefficient for SAT and another for Rand 1,2,3, plus the intercept. Only include predictors that make sense for your assignment and analysis.

9. Common Errors and Quick Fixes

Error or symptom

Likely reason

What to check

UFuncTypeError with dtype(‘<U10’)

Text values were passed where numbers were expected.

Print x1 and type(x1); make sure you selected data[[‘SAT’]], not a list of column names.

AttributeError: DataFrame has no attribute ‘dtype’

Used .dtype on a DataFrame.

Use .dtypes for a DataFrame; .dtype for a Series or NumPy array.

ValueError converting to float

A selected column contains non-numeric text.

Inspect values; clean or encode text appropriately before conversion.

Missing-data error

The selected columns contain NaN values.

Check data[[‘SAT’, ‘GPA’]].isna().sum() and decide how to handle missing rows.

A useful debugging checklist

print(type(x1))
print(x1.head())
print(x1.dtypes) # if x1 is a DataFrame
print(y.head())
print(y.dtype) # if y is a Series

10. A Few Important Things to Remember

· A column name is not the same thing as the data stored in that column.

· data[[‘SAT’]] selects values from the DataFrame; [[‘SAT’]] alone creates a list of text.

· Check the type and contents of the exact variable passed into a function.

· X is the predictor; Y is the outcome you want to explain or predict.

· add_constant() adds the intercept column in this statsmodels workflow.

· OLS fits the model; .fit() estimates it; summary() reports the results.

Conclusion

Our error was not really a Linear Regression problem. It was a data-selection problem: the model was receiving text labels instead of the numeric SAT observations. Once we selected the real column with data[[‘SAT’]], the regression workflow could run.

The biggest lesson for a beginner is simple: before fitting a model, inspect your data, understand the shape of each variable, and make sure you are passing the values you intend to use. Understanding those small steps makes the rest of data analysis much easier.

You can adapt this tutorial to your own dataset by changing the predictor column (SAT), the target column (GPA), and the file-loading step.

--

--