You are on page 1of 2

#importing the required libraries

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

#loading the data


data = pd.read_csv("data.csv")

#defining the feature and target variables


X = data.iloc[:,:-1].values
y = data.iloc[:,1].values

#splitting the data into training 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)

#fitting the model


regressor=LinearRegression()
refressor.fit(X_train,y_train)

#predicting the results


y_pred=regressor.predict(X_test)

#evaluating model
from sklearn.metrics import r2_score
r2_score=r2_score(y_test,y_pred)
print('R2 score:',r2_score)
EXPLANATION:

This code is a simple example of machine learning linear regression using python and
matplotlib. The necessary packages such as numpy and matplotlib are imported. Then the
necessary variables, x and y are defined. The graph is plotted using the plot function of
matplotlib, and labels and title are added to the graph. Then, the linear regression model from
sklearn is imported and the model is defined. The x and y variables are converted into 2D
arrays, and the model is fitted. The predicted values of y are calculated and the regression line
is plotted on the graph. Finally, the graph is shown.

You might also like