import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df=pd.read_csv('../input/shared-bikes-demand-prediction/day.csv')
df
df.season.value_counts()
"""
Season (1:spring, 2:summer, 3:fall, 4:winter)
"""
plt.figure(figsize=(12,6))
sns.lineplot(y=df.cnt,x=df.season)
plt.title('Season vs Number of vehicles registered')
plt.xlabel('Number of Vehicles')
plt.ylabel('Seasons')
"""
**NOTE:**Here we can see that in summer we have greatest number of vehicles getting registered
"""
plt.figure(figsize=(12,6))
sns.lineplot(y=df.cnt,x=df.weekday)
plt.title('Season vs Number of vehicles registered')
plt.xlabel('Number of Vehicles')
plt.ylabel('Working Days')
"""
Weekdays: Monday:0, Tuesday:1, Wednesday:2, Thursday:3, Friday:4, Saturday:5, Sunday:6
"""
"""
Here we can see that on wednesday and sturday, most of the bikes are shared.
"""
df.drop('instant',inplace=True,axis=1)
plt.figure(figsize=(12,6))
sns.lineplot(y=df.cnt,x=df.mnth)
plt.title('Months vs Number of vehicles')
plt.xlabel('Number of Month')
plt.ylabel('Number of Vehicles')
plt.figure(figsize=(12,6))
sns.barplot(y=df.cnt,x=df.mnth)
plt.title('Months vs Number of vehicles')
plt.xlabel('Number of Month')
plt.ylabel('Number of Vehicles')
"""
**NOTE:**Here we can easily say that most number of vehicles are shared when there is summer season that is it starts to rise from april and its at the peak in May.
"""
plt.figure(figsize=(12,6))
sns.barplot(y=df.cnt,x=df.holiday)
plt.title('Holiday vs Number of vehicles')
plt.xlabel('Is it a holiday or not')
plt.ylabel('Number of Vehicles')
"""
**NOTE:** Most of the bikes are used when there not a holiday
"""
plt.figure(figsize=(12,6))
sns.lineplot(x=df.temp,y=df.cnt)
plt.title('Temperature vs Number of vehicles')
plt.xlabel('Temperature')
plt.ylabel('Number of Vehicles')
plt.figure(figsize=(12,6))
sns.lineplot(y=df.cnt,x=df.atemp)
plt.title('Feeling Temperature vs Number of vehicles')
plt.xlabel('Feeling Temperature')
plt.ylabel('Number of Vehicles')
plt.figure(figsize=(12,6))
plt.plot(df.temp)
plt.plot(df.atemp)
plt.title('Temperature vs Number of vehicles')
plt.xlabel('Observations')
plt.ylabel('Temperature')
df['dteday']=df['dteday'].astype(str)
plt.figure(figsize=(12,8))
sns.heatmap(df.corr(),annot=True)
"""
* **NOTE:** Here we can see that registered users and count of vehicles are like more than 90 percent correlated which means that registeted users feature will have more weightage to predict the count of vehicles.

* **NOTE:** Here we can also see that the feeling temperature and temperature are nearly same so we can drop one of this feature so our complexcity of model decreases and also it reduces the curse of dimensionality to the model.
"""
plt.figure(figsize=(12,6))
sns.lineplot(y=df.cnt,x=df.hum)
plt.title('Humidity vs Number of vehicles')
plt.xlabel('Humidity')
plt.ylabel('Number of Vehicles')
"""
**NOTE:**We cannot properly say the relation between count of vehicles and humidity from this above graph.
"""
plt.figure(figsize=(12,6))
sns.lineplot(y=df.cnt,x=df.windspeed)
plt.title('Wind speed vs Number of vehicles')
plt.xlabel('Wind Speed')
plt.ylabel('Number of Vehicles')
"""
**NOTE:**We also cannot say with accurate judgement about the relationship about windspeed and count of vehicles.
"""
plt.figure(figsize=(12,6))
sns.histplot(df.temp)
plt.figure(figsize=(12,6))
sns.histplot(df.atemp)
"""
**NOTE:**Anyhow, we are getting almost same distribution and we have already decided to remove one of this features as they are highly correlate and may act like duplicate features.
"""
plt.figure(figsize=(12,6))
sns.histplot(df.windspeed)
"""
**NOTE:**Here we can see that we have a right skewed data, so if we want we can convert it to normal distribution.
"""
plt.figure(figsize=(12,6))
sns.histplot(df.registered)
plt.figure(figsize=(12,6))
sns.scatterplot(x=df.cnt,y=df.casual)
plt.figure(figsize=(12,6))
sns.scatterplot(x=df.cnt,y=df.registered)
"""
**NOTE:**Here we can clearly see that as the registered number of users increases, count also increases.
"""
plt.figure(figsize=(12,6))
sns.barplot(x=df.weathersit,y=df.cnt)
plt.xlabel('Weather of the Day')
plt.ylabel('Count of Vehicles')
plt.title(' Weather of the day vs Count of the vehicles')
"""
1. : Clear, Few clouds, Partly cloudy, Partly cloudy
2. : Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist
3. : Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds
4. : Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog
"""
"""
* **NOTE:**From above graph it is confirmed that when the weather is cool, and not very sunny, more number of bikes are used.
* **NOTE:**We also cannot see any values when there is heavy rain type of conditions and there is no number of vehicles.
"""
plt.figure(figsize=(12,6))
sns.barplot(y=df.cnt,x=df.yr)
"""
**NOTE:** Year:1 means 2019, and Year:0 means 2018, so we can see that in 2019, the count of vehicles have increases.
"""
plt.figure(figsize=(12,12))
df.corr().iloc[:, -1].plot(kind='barh')
print(df.corr().iloc[:, -1])
print('\n')
df.drop('atemp',axis=1,inplace=True)
df.drop('dteday',axis=1,inplace=True)
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
X=df.iloc[:,0:-1]
y=df.iloc[:,-1]
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)
"""
**NOTE:**Using train_test_split to overcome overfitting.
"""
X_train
X_test
LR=LinearRegression()
LR.fit(X_train,y_train)
y_pred=LR.predict(X_test)
y_pred
from sklearn.metrics import r2_score
score=r2_score(y_test,y_pred)
score
dff=pd.DataFrame({'y_test':y_test,'y_pred':y_pred})
dff['My_error']=dff['y_test']-dff['y_pred']
dff
"""
* **NOTE:** From the above dataset, you can cleary see that the error in my model is just near to some decimal points which shows that this model maybe good for predictions.
* **NOTE:** Also note that this model is not overfitted as we have already used train test split function to split the dataset so now lets see on testing dataset.
"""
plt.figure(figsize=(12,6))
sns.regplot(x=dff.y_pred,y=dff.y_test)
testing_data=pd.read_csv('../input/shared-bikes-demand-prediction/test.csv')
testing_data
testing_data.drop(['instant','dteday'],axis=1,inplace=True)
testing_data.head()
testing_data.drop('atemp',inplace=True,axis=1)
y_pred_testing=LR.predict(testing_data)
y_pred_testing
from sklearn.tree import DecisionTreeRegressor
DTR=DecisionTreeRegressor(criterion='mse')
DTR.fit(X_train,y_train)
y_pred2=DTR.predict(X_test)
score1=r2_score(y_test,y_pred2)
score1
dff1=pd.DataFrame({'y_test':y_test,'y_DTR_pred':y_pred2})
dff1['my_error']=dff1['y_test']-dff1['y_DTR_pred']
dff1
"""
**NOTE:**Here we can see that we have achieved around 98% but with Liner Regression we have a better score.
"""
plt.figure(figsize=(12,6))
sns.regplot(x=dff1.y_DTR_pred,y=dff1.y_test)
from sklearn.linear_model import Ridge
Rid=Ridge(alpha=1)
Rid.fit(X_train,y_train)
y_pred_ridge=Rid.predict(X_test)
dff2=pd.DataFrame({'y_test':y_test,'y_pred':y_pred_ridge})
dff2['my_error']=dff2['y_test']-dff2['y_pred']
(dff2.my_error.sum())**2
dff2
score2=r2_score(y_test,y_pred_ridge)
score2
"""
**NOTE:** Even with the Ridge Regression model, we are having a better score.
"""
plt.figure(figsize=(12,6))
sns.regplot(x=dff2.y_pred,y=dff2.y_test)
from sklearn import linear_model
LSO=linear_model.Lasso(alpha=0.2)
LSO.fit(X_train,y_train)
y_pred_lasso=LSO.predict(X_test)
y_pred_lasso
dff3=pd.DataFrame({'y_test':y_test,'y_pred_lasso':y_pred_lasso})
dff3['my_error']=dff3['y_test']-dff3['y_pred_lasso']
(dff3.my_error.sum())**2
dff3
score3=r2_score(y_test,y_pred_lasso)
score3
plt.figure(figsize=(12,6))
sns.regplot(x=dff3.y_pred_lasso,y=dff3.y_test)
LinearRegressionPredictions=score
DecisionTreeRegressorPredictions=score1
LassoRegressionPredictions=score2
RidgeRegressionPredictions=score3
Models=['Linear Regression','Decision Tree Regression','Lasso Regression','Ridge Regression']
Scores=[LinearRegressionPredictions,DecisionTreeRegressorPredictions,LassoRegressionPredictions,RidgeRegressionPredictions]
from sklearn.metrics import mean_squared_error
rms=round(mean_squared_error(y_test,y_pred,squared=False),12)
rms
rms1=round(mean_squared_error(y_test,y_pred2,squared=False),2)
rms1
rms2=round(mean_squared_error(y_test,y_pred_lasso,squared=False),5)
rms2
rms3=round(mean_squared_error(y_test,y_pred_ridge,squared=False),5)
rms3
LinearRegressionPredictions=score
DecisionTreeRegressorPredictions=score1
LassoRegressionPredictions=score2
RidgeRegressionPredictions=score3
Models=['Linear Regression','Decision Tree Regression','Lasso Regression','Ridge Regression']
Scores=[LinearRegressionPredictions,DecisionTreeRegressorPredictions,LassoRegressionPredictions,RidgeRegressionPredictions]
rmse=[rms,rms1,rms2,rms3]
scores_df=pd.DataFrame({'Models':Models,'R2 Scores':Scores,'Root_Mean_Squared_Error':rmse})
scores_df
plt.rcParams["figure.autolayout"] = True
plt.rcParams["figure.figsize"] = [12,20]
f, ax = plt.subplots(4,1 )
sns.regplot(x=dff.y_pred,y=dff.y_test,ax=ax[0])
ax[0].set_title('Predictions using Linear Regression')
sns.regplot(x=dff3.y_pred_lasso,y=dff3.y_test,ax=ax[1])
ax[1].set_title('Predictions using Lasso Regression')
sns.regplot(x=dff2.y_pred,y=dff2.y_test,ax=ax[2])
ax[2].set_title('Predictions using Ridge Regression')
sns.regplot(x=dff1.y_DTR_pred,y=dff1.y_test,ax=ax[3])
ax[3].set_title('Predictions using Decision Tree Regression')
f.tight_layout()