Simple Linear Regression Model using Python

1. Importing the Libraries:

# importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

2. Importing Data:

User rating data
# importing data
dataset = pd.read_csv('file_name.csv')
# spliting into independent and dependent variable
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1:].values

3. Splitting the data into training and testing sets:

# importing the scikit learn library
from sklearn.model_selection import train_test_split
# Spliting the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

4. Training a simple linear regression model:

# Training the model
from sklearn.linear_model import LinearRegression
LR = LinearRegression()
LR.fit(X_train, y_train)

5. Predicting the result:

# prediting the test
LR.predict(X_test)

Note: You have to use 2D array to give a user input cause our X and y matrixs are 2D arrays.

# predicting the result using users input
LR.predict([[4.5],[4.9]])

6. Visualizing the result:

# Scattering our data
plt.scatter(X_train, y_train, color = 'red')
# ploting the linear line
plt.plot(X_train, LR.predict(X_train), color = 'blue')
# giving the title
plt.title('User rating VS Price - training result')
# Xlabel
plt.xlabel('User rating')
# ylabel
plt.ylabel('Price')
# Showing the plot
plt.show()
# Scattering our data
plt.scatter(X_test, y_test, color = 'red')
# ploting the linear line
plt.plot(X_train, LR.predict(X_train), color = 'blue')
# giving the title
plt.title('User rating VS Price - testing result')
# Xlabel
plt.xlabel('User rating')
# ylabel
plt.ylabel('Price')
# Showing the plot
plt.show()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store