Linear Regression | Learning Python

Ideakart
tech-daily
Published in
1 min readSep 11, 2023

A simple method of associating a dependent variable to an independent variable and which can be plotted on a x-y axis is the linear regression.

y = mx + c

where,

x , independent variable

y, dependent variable

m, slope or coefficient of the line

c, intercept at which the line crosses the y axis

Simple Linear Regression

`sklearn` library really makes it easy to get the linear regression expression for the problem that we are trying to solve. For e.g. Using data from here, we can get csv of the temperatures of a month and store it in a data.csv

Data preparation

import pandas as pd
tempdata = pd.read_csv('data.csv')
tempdata.columns = ['Date','Temperature','Anomaly']
tempdata.Date = tempdata.Date.floordiv(100)
tempdata.Temperature = (tempdata.Temperature - 32) * 5/9
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(tempdata.Date.values.reshape(-1,1),tempdata.Temperature.values)

Training and Testing

We can import the library and initialise the instance.

from sklearn.linear_model import LinearRegression
linear_regression = LinearRegression()
linear_regression.fit(X=X_train, y=y_train)
prediction = linear_regression.predict(X_test)
expected = y_test

We can find the difference between the expected and predicted values, and see if the model is behaving expectedly or not.

Prediction
We can also create a lambda expression as the linear_regression instance gives us two methods to get the coefficient and the intercept.

coefficient, intercept = linear_regression.coef_, linear_regression.intercept_
predict = lambda x: x * coefficient + intercept
predict(1991)
predict(2050)

This is how we can build our predict expressions and use it to predict the temperature for a given year.

--

--