#!/usr/bin/env python
# coding: utf-8

# ## Linear Regression with Python

# In this section we will see how the Python Scikit-Learn library for machine learning can be used to implement regression functions. We will start with simple linear regression involving two variables.

# #### Simple Linear Regression

# In this regression task we will predict the percentage of marks that a student is expected to score based upon the number of hours they studied. This is a simple linear regression task as it involves just two variables.

# #### Author: ABHISHEK DAS

# In[5]:


# Importing all libraries required in this notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')


# In[6]:


# Reading data from remote link
url = "http://bit.ly/w-data"
s_data = pd.read_csv(url)
print("Data imported successfully")
s_data.head(10)


# Let's plot our data points on 2-D graph to eyeball our dataset and see if we can manually find any relationship between the data.

# In[7]:


# Plotting the distribution of scores
s_data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()


# From the graph above, we can clearly see that there is a positive linear relation between the number of hours studied and percentage of score.

# ##### Preparing the data
# 
# The next step is to divide the data into "attributes" (inputs) and "labels" (outputs).

# In[8]:


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


# ##### Now that we have our attributes and labels, the next step is to split this data into training and test sets. We'll do this by using Scikit-Learn's built-in train_test_split() method:

# In[9]:


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)


# #### Training the Algorithm
# 
# ##### We have split our data into training and testing sets, and now is finally the time to train our algorithm.

# In[10]:


from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("Training complete.")


# In[11]:


coeff = regressor.coef_
print("Slope Coefficient :",coeff)
Intercept = regressor.intercept_
print("Intercept :",Intercept)
print("The equation of the best fitted line is:")
print("Y =",Intercept,"+",coeff,"* X")


# In[44]:


# Plotting the regression line
line = regressor.coef_*X+regressor.intercept_

# Plotting for the train data
plt.scatter(X_train, y_train, color='blue')
plt.plot(X_train, regressor.predict(X_train), color='red')
plt.title("Hours of Study vs. Scores (training set)")
plt.xlabel("Hours of Study")
plt.ylabel("Percentage of Scores")
plt.show()


# In[12]:


# Plotting for the test data
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, regressor.predict(X_test), color='red')
plt.title("Hours of Study vs. Scores (test set)")
plt.xlabel("Hours of Study")
plt.ylabel("Percentage of Scores")
plt.show()


# #### Making Predictions
# 
# ##### Now that we have trained our algorithm, it's time to make some predictions.

# In[13]:


print(X_test) # Testing data - In Hours
y_pred = regressor.predict(X_test) # Predicting the scores


# In[14]:


# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df


# In[15]:


# Now it is time to test with our data
hours = 9.25
hours = np.array(hours).reshape(-1,1)
own_pred = regressor.predict(hours)
own_pred


# #### Evaluating the model
# 
# ##### The final step is to evaluate the performance of algorithm. This step is particularly important to compare how well different algorithms perform on a particular dataset. For simplicity here, we have chosen the mean square error. There are many such metrics.

# In[16]:


from sklearn import metrics
print('Mean Absolute Error:',metrics.mean_absolute_error(y_test, y_pred))


# #### Therefore,
# #### If a student studies for 9.25 hrs/ day , The predicted score of the student will be 94.19%





9af4c15d955002a7d9f91351fb58a53631177587
<mask token>

<mask token>
get_ipython().run_line_magic('matplotlib', 'inline')
<mask token>
print('Data imported successfully')
s_data.head(10)
s_data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
<mask token>
regressor.fit(X_train, y_train)
print('Training complete.')
<mask token>
print('Slope Coefficient :', coeff)
<mask token>
print('Intercept :', Intercept)
print('The equation of the best fitted line is:')
print('Y =', Intercept, '+', coeff, '* X')
<mask token>
plt.scatter(X_train, y_train, color='blue')
plt.plot(X_train, regressor.predict(X_train), color='red')
plt.title('Hours of Study vs. Scores (training set)')
plt.xlabel('Hours of Study')
plt.ylabel('Percentage of Scores')
plt.show()
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, regressor.predict(X_test), color='red')
plt.title('Hours of Study vs. Scores (test set)')
plt.xlabel('Hours of Study')
plt.ylabel('Percentage of Scores')
plt.show()
print(X_test)
<mask token>
df
<mask token>
own_pred
<mask token>
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))

<mask token>
get_ipython().run_line_magic('matplotlib', 'inline')
url = 'http://bit.ly/w-data'
s_data = pd.read_csv(url)
print('Data imported successfully')
s_data.head(10)
s_data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
X = s_data.iloc[:, :-1].values
y = s_data.iloc[:, 1].values
<mask token>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
<mask token>
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print('Training complete.')
coeff = regressor.coef_
print('Slope Coefficient :', coeff)
Intercept = regressor.intercept_
print('Intercept :', Intercept)
print('The equation of the best fitted line is:')
print('Y =', Intercept, '+', coeff, '* X')
line = regressor.coef_ * X + regressor.intercept_
plt.scatter(X_train, y_train, color='blue')
plt.plot(X_train, regressor.predict(X_train), color='red')
plt.title('Hours of Study vs. Scores (training set)')
plt.xlabel('Hours of Study')
plt.ylabel('Percentage of Scores')
plt.show()
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, regressor.predict(X_test), color='red')
plt.title('Hours of Study vs. Scores (test set)')
plt.xlabel('Hours of Study')
plt.ylabel('Percentage of Scores')
plt.show()
print(X_test)
y_pred = regressor.predict(X_test)
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df
hours = 9.25
hours = np.array(hours).reshape(-1, 1)
own_pred = regressor.predict(hours)
own_pred
<mask token>
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
url = 'http://bit.ly/w-data'
s_data = pd.read_csv(url)
print('Data imported successfully')
s_data.head(10)
s_data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
X = s_data.iloc[:, :-1].values
y = s_data.iloc[:, 1].values
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)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print('Training complete.')
coeff = regressor.coef_
print('Slope Coefficient :', coeff)
Intercept = regressor.intercept_
print('Intercept :', Intercept)
print('The equation of the best fitted line is:')
print('Y =', Intercept, '+', coeff, '* X')
line = regressor.coef_ * X + regressor.intercept_
plt.scatter(X_train, y_train, color='blue')
plt.plot(X_train, regressor.predict(X_train), color='red')
plt.title('Hours of Study vs. Scores (training set)')
plt.xlabel('Hours of Study')
plt.ylabel('Percentage of Scores')
plt.show()
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, regressor.predict(X_test), color='red')
plt.title('Hours of Study vs. Scores (test set)')
plt.xlabel('Hours of Study')
plt.ylabel('Percentage of Scores')
plt.show()
print(X_test)
y_pred = regressor.predict(X_test)
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df
hours = 9.25
hours = np.array(hours).reshape(-1, 1)
own_pred = regressor.predict(hours)
own_pred
from sklearn import metrics
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))

#!/usr/bin/env python
# coding: utf-8

# ## Linear Regression with Python

# In this section we will see how the Python Scikit-Learn library for machine learning can be used to implement regression functions. We will start with simple linear regression involving two variables.

# #### Simple Linear Regression

# In this regression task we will predict the percentage of marks that a student is expected to score based upon the number of hours they studied. This is a simple linear regression task as it involves just two variables.

# #### Author: ABHISHEK DAS

# In[5]:


# Importing all libraries required in this notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')


# In[6]:


# Reading data from remote link
url = "http://bit.ly/w-data"
s_data = pd.read_csv(url)
print("Data imported successfully")
s_data.head(10)


# Let's plot our data points on 2-D graph to eyeball our dataset and see if we can manually find any relationship between the data.

# In[7]:


# Plotting the distribution of scores
s_data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()


# From the graph above, we can clearly see that there is a positive linear relation between the number of hours studied and percentage of score.

# ##### Preparing the data
# 
# The next step is to divide the data into "attributes" (inputs) and "labels" (outputs).

# In[8]:


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


# ##### Now that we have our attributes and labels, the next step is to split this data into training and test sets. We'll do this by using Scikit-Learn's built-in train_test_split() method:

# In[9]:


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)


# #### Training the Algorithm
# 
# ##### We have split our data into training and testing sets, and now is finally the time to train our algorithm.

# In[10]:


from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("Training complete.")


# In[11]:


coeff = regressor.coef_
print("Slope Coefficient :",coeff)
Intercept = regressor.intercept_
print("Intercept :",Intercept)
print("The equation of the best fitted line is:")
print("Y =",Intercept,"+",coeff,"* X")


# In[44]:


# Plotting the regression line
line = regressor.coef_*X+regressor.intercept_

# Plotting for the train data
plt.scatter(X_train, y_train, color='blue')
plt.plot(X_train, regressor.predict(X_train), color='red')
plt.title("Hours of Study vs. Scores (training set)")
plt.xlabel("Hours of Study")
plt.ylabel("Percentage of Scores")
plt.show()


# In[12]:


# Plotting for the test data
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, regressor.predict(X_test), color='red')
plt.title("Hours of Study vs. Scores (test set)")
plt.xlabel("Hours of Study")
plt.ylabel("Percentage of Scores")
plt.show()


# #### Making Predictions
# 
# ##### Now that we have trained our algorithm, it's time to make some predictions.

# In[13]:


print(X_test) # Testing data - In Hours
y_pred = regressor.predict(X_test) # Predicting the scores


# In[14]:


# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df


# In[15]:


# Now it is time to test with our data
hours = 9.25
hours = np.array(hours).reshape(-1,1)
own_pred = regressor.predict(hours)
own_pred


# #### Evaluating the model
# 
# ##### The final step is to evaluate the performance of algorithm. This step is particularly important to compare how well different algorithms perform on a particular dataset. For simplicity here, we have chosen the mean square error. There are many such metrics.

# In[16]:


from sklearn import metrics
print('Mean Absolute Error:',metrics.mean_absolute_error(y_test, y_pred))


# #### Therefore,
# #### If a student studies for 9.25 hrs/ day , The predicted score of the student will be 94.19%




