# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/SuperDataWorld/Python/blob/main/Linear_Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="y8HYCkhXvsoq"
# ## Standard Imports

# + id="BLcUO6J7umhS"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression

# + [markdown] id="UCPEnPDpyM14"
# ## Build Test Data 

# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="rHCoapSd4REN" outputId="b306983c-b246-4c37-ee5c-0993943abfa9"
# a = 3 b = 2 c = 1

a = [1,2,3,4,5,1,0]  
b = [2,1,5,3,7,2,2]
c = [6,3,4,5,7,1,1]
tot = [13,11,23,223,236,28,25]

df = pd.DataFrame({'a':a,'b':b,'c':c,'tot':tot})
df.head()

# + [markdown] id="P2qL4cLdygus"
# # Create Linear Regression Model

# + colab={"base_uri": "https://localhost:8080/"} id="Ui_DU7V6yF4x" outputId="546cc593-9c2f-4339-c89b-15700d09cfba"
# Assign the Training Data
X = df[['a','b','c']]
y = df.tot

# Select a linear model
model = LinearRegression()

# Train the model
model.fit(X, y)

# + [markdown] id="-EwIrPgwyut8"
# # Test Model Accuracy

# + colab={"base_uri": "https://localhost:8080/"} id="5WbE5XUgyn96" outputId="02fcc6c4-badd-48c2-a316-9e76df0229d8"
model.coef_

# + colab={"base_uri": "https://localhost:8080/"} id="8ZJrRnicyoHM" outputId="cf2b6fd1-d550-4e73-bb3b-a6cff042da72"
# Make a prediction 
X_test = [[1,10,22],[2,4,8],[3,3,3],[20,2,10]]  
y_test = [45,22,18,74]


y_pred = model.predict(X_test)

print('pred')
print(y_pred)
print('test')
print(y_test)

# + [markdown] id="BzwKnU7xy4oI"
# # More Complex Example

# + [markdown] id="jhzm-wa7v2gy"
# ## Get Data

# + id="PmD0nWFJvj6E" colab={"base_uri": "https://localhost:8080/"} outputId="827d224c-d970-4124-daaf-4a48027f6ebf"
# ! wget https://raw.githubusercontent.com/SuperDataWorld/Python/main/Data/bikerental.csv 

# + colab={"base_uri": "https://localhost:8080/", "height": 293} id="iaQxndU_uWXz" outputId="f5eaa818-dc3f-4b0c-bd2a-130b119939b2"
df = pd.read_csv('bikerental.csv')
df.head()

# + [markdown] id="mbgciFDA26TB"
# # Deal with Categorical Data 

# + colab={"base_uri": "https://localhost:8080/", "height": 293} id="gyBFZK9q1jGS" outputId="7b805110-ac98-470e-b590-e83eb26d0475"
df.head()

# + colab={"base_uri": "https://localhost:8080/"} id="eeFK_ybc6DSm" outputId="166477d3-4efa-473f-c247-50919f49f0cf"
df.yr.value_counts()


# + colab={"base_uri": "https://localhost:8080/"} id="nlZ6anAo6aJk" outputId="c35a86a3-3bd7-41a1-887b-3591320d277a"
df.mnth.value_counts()

# + colab={"base_uri": "https://localhost:8080/"} id="JO3zuZjF6ucb" outputId="e9b54df8-6d8e-4e69-aff5-b99c3eb50bd2"
df.columns

# + id="lWwAZCeg6aG3"
df.drop(['instant','dteday','registered', 'casual'], axis = 1, inplace = True)

# + [markdown] id="_WPhJfhU4Pqq"
# ## Create Data for ML and Split

# + id="Ajx7i4xH7Q5x"
y = df['cnt']
X = df.drop(['cnt'], axis = 1)

# + id="TxTJGnhT4f-o"
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .2, random_state = 42)

# + [markdown] id="u99KJyAm44_y"
# ## Train and Fit Model

# + colab={"base_uri": "https://localhost:8080/", "height": 423} id="Vg2m3fYB_ImZ" outputId="76a7d7e1-0402-4562-9789-f5c42bfa4e84"
X

# + colab={"base_uri": "https://localhost:8080/"} id="SwFVSE07455Y" outputId="205a2957-fd97-490a-a58a-b7661b5cbe98"
model = LinearRegression()
model.fit(X_train, y_train)

# + id="Rc6nZrl_45qf"
y_pred = model.predict(X_test)

# + colab={"base_uri": "https://localhost:8080/", "height": 283} id="O_oTORw77plL" outputId="5fcfefbb-d208-49e9-b461-8ee032f62ca1"
y_test.hist()

# + colab={"base_uri": "https://localhost:8080/", "height": 283} id="V8VpOySX8ABY" outputId="38b52c7e-c508-4459-d685-b567a0b0449b"
pd.Series(y_pred).hist()

# + [markdown] id="RJlkllSN56Rz"
# ## Performance

# + id="h31x8pfh54av"
from sklearn.metrics import mean_squared_error, r2_score

# + colab={"base_uri": "https://localhost:8080/"} id="WgZuktM753-q" outputId="99874096-1532-416b-a5da-41184bc004de"
print('Coefficients:', model.coef_)
print('Intercept:', model.intercept_)
print('Root Mean squared error (RMSE):', np.sqrt(mean_squared_error(y_pred, y_test)))
print('Coefficient of determination', r2_score(y_pred, y_test))

# + id="9BZntzs9-bN-" colab={"base_uri": "https://localhost:8080/", "height": 283} outputId="a14871d7-8609-41b2-8319-2e7bf218ecbd"
plt.scatter(y_test, y_pred)

# + colab={"base_uri": "https://localhost:8080/", "height": 425} id="xvVHqHubB1ah" outputId="bce229f8-6ee1-4e34-f890-a58ec411c919"
df2 = pd.DataFrame([pd.Series(y_test.values), pd.Series(y_pred), pd.Series(X_test.mnth.values)]) 
df2 = df2.transpose()
df2.columns = ['Actual', 'Prediction', 'Month']
df2 = df2.groupby(by = 'Month').sum().reset_index()
df2['% diff'] = round((df2['Prediction'] / df2['Actual']) - 1, 2)
df2

# + id="7olLcK18ELeE"


StarcoderdataJupyterScriptsDedupFiltered