Machine Learning

Simple Linear Regression Program

In this article, we will show one example of Simple Linear Regression Program.

Simple Linear Regression Program

Import libraries
Import the dataset
Splitting the dataset into the Training set and Test set
Training the Simple Linear Regression model on the Training set
Predicting the Test set result
Visualizing the Training set result
Visualizing the Test set result

The formula is as follow:

y = b0 + b1 * x1

y = Dependent Variable (DV)
b0 = Constant
b1 = Coefficient
x1 = Independent Variable (IV)

Here is one example of the program:

Import Libraries

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

Import the dataset

dataset = pd.read_csv('dataset-file.csv')

x = dataset.iloc[:, :-1].values

x = dataset.iloc[:, -1].values

Replace the dataset-file.csv file with your file and mention full path of the file.

Splitting the dataset into the Training set and Test set

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)

Training the Simple Linear Regression model on the Training set

from sklearn.linear_model import LinearRegression

regressor = LinearRegression()

regressor.fit(x_train, y_train)

Prediction the Test set result

y_pred = regressor.predict(x_test)

Visualizing the Training set results

plt.scatter(x_train, y_train, color = 'red')

plt.plot(x_train, regressor.predit(x_train), color = 'blue')

plt.title('Name of the graph')

plt.xlabel('Name of the x label')

plt.ylabel('name of the y label')

plt.show()

Visualizing the Test set results

plt.scatter(x_test, y_test, color = 'red')

plt.plot(x_train, regressor.predit(x_train), color = 'blue')

plt.title('Name of the graph')

plt.xlabel('Name of the x label')

plt.ylabel('name of the y label')

plt.show()

We have shown Simple Linear Regression Program.

[Need assistance to fix this error or install tools? We’ll help you.]

Related Articles