# Simple Linear Regression in Python In this article, we will see step-by-step process of Simple Linear Regression using Python.

If you don’t like to read, here’s the video on the same.

You can read all the steps or can get the code on GitHub.

Let’s start coding step by step.

Importing the dataset (created in last video) and libraries.

```import pandas as pd
import numpy as np
import matplotlib.pyplot as plt #for visualization

X=dataset.iloc[:,2]
y=dataset.iloc[:,3]

```

Replacing nan in numerical columns by mean value of the column values.

```X.fillna(X.mean(),inplace=True)
y.fillna(y.mean(),inplace=True)
```

Now the missing values are replaced by the mean of other values from the column.

Now we split the data.

```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=1)
```

for visualization we will need X_train and X_test in original form (before scaling).

```X_train1=X_train
X_test1=X_test
```

Depending on the algorithm, we should choose whether to scale the data features(columns) or not. Now we will scale. The reason is to prevent the data leakage from X_train to X_test. We splitted the data and then doing scaling.

```from sklearn.preprocessing import StandardScaler
sc=StandardScaler()
X_train=X_train.values.reshape(-1,1)
X_test=X_test.values.reshape(-1,1)
X_train=sc.fit_transform(X_train)
X_test=sc.transform(X_test)
```

This is why we first splitted the dataset and then did fit_transform on training data and just transform it on a test set to prevent the leakage to the test set.

Now you can use any algorithm to do your task. Preprocessing ends here for this dataset. We are doing Simple Linear Regression.

```from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X_train,y_train)

#predicting test set results

y_pred=regressor.predict(X_test)

#Plotting the graphs first for train data

plt.scatter(X_train1,y_train,color='red')
plt.plot(X_train1,regressor.predict(X_train),color='blue')
plt.title('Age vs Salary')
plt.xlabel('Age')
plt.ylabel('Salary')
plt.show()

#decently fit
#plotting now for train data
plt.scatter(X_test1,y_test,color='red')
plt.plot(X_train1,regressor.predict(X_train),color='blue')
plt.title('Age vs Salary')
plt.xlabel('Age')
plt.ylabel('Salary')
plt.show()

from sklearn.metrics import r2_score
print(r2_score(y_test,y_pred))
```

That’s it. Now you have learned to implement Simple Linear Regression in Python. You can build a similar model for predicting missing data as well.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5888183,"math_prob":0.9299512,"size":2560,"snap":"2021-04-2021-17","text_gpt3_token_len":589,"char_repetition_ratio":0.12871675,"word_repetition_ratio":0.019933555,"special_character_ratio":0.22578125,"punctuation_ratio":0.16833667,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99980015,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-01-26T05:39:44Z\",\"WARC-Record-ID\":\"<urn:uuid:52900823-36d0-4b84-979c-bb786b5f131d>\",\"Content-Length\":\"98806\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:af2dd884-09a2-48c7-bc00-6e9c430cad92>\",\"WARC-Concurrent-To\":\"<urn:uuid:d95c2108-f296-4077-804a-204d7e343087>\",\"WARC-IP-Address\":\"172.67.139.53\",\"WARC-Target-URI\":\"https://www.spiderposts.com/2021/01/02/simple-linear-regression-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=simple-linear-regression-in-python\",\"WARC-Payload-Digest\":\"sha1:XMYITEUQGPMGNZVVQTXTW6BMWILBXOJI\",\"WARC-Block-Digest\":\"sha1:QMP6I7FQUSUAQH5O3ZYFXIRHO4SPK5E3\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-04/CC-MAIN-2021-04_segments_1610704798089.76_warc_CC-MAIN-20210126042704-20210126072704-00106.warc.gz\"}"}