"""
<img src="https://www.policybazaar.com/pblife/assets/images/pb_life_How_to_increase_Health_insurance_cover_1592063367.gif">
"""
"""
# About Dataset
"""
"""
This dataset contains person's information like age,sex,gender,bmi,region,smoke or not and we have to predict their medical insurance cost.In this notebook I will apply regression techniques of supervised learning to predict the medical insurance costs.
"""
"""
# This notebook will cover the following

1. Exploratory Data Analysis 
2. Data Modelling and Evaluation
"""
"""
<font size="+2" color=chocolate ><b>Please Upvote my kernel if you like my work.</b></font>
"""
"""
# Import Libraries
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
"""
# Import Dataset
"""
data=pd.read_csv('../input/insurance/insurance.csv')
data.head()
"""
<font size="+3" color='#1f0c75' ><b>Exploratory Data Analysis</b></font>
"""
"""
# Data Summary
"""
data.iloc[:,[0,2,6]].describe()
"""
* Age is ranging from 18 to 64 ,with mean of 38.2 and standard deviation of 14.04 
* bmi is ranging from 15.96 to 53.13 , with mean of 30.6 and standard deviation of 6.09
* charges is ranging from 1121 to 63770 , with mean of 13270 and standard deviation of 12110
"""
"""
# Age distribution
"""
sns.distplot(data['age'])
"""
* As you can see age is normally distrtibuted 
* Maximum number of patients are of 18-22 age 
"""
sns.boxplot(y='age',data=data,color='green')
"""
# Age Vs Bmi by age
"""
sns.scatterplot(x="age", y="bmi", hue='sex',data=data,color='red')
"""
* No relation between age and bmi
"""
"""
# Gender wise Age distribution
"""
sns.boxplot(x='sex',y='age',data=data)
f= plt.figure(figsize=(12,5))

ax=f.add_subplot(121)
sns.distplot(data[(data.sex == 'male')]["age"],color='b',ax=ax)
ax.set_title('Distribution of ages of male')

ax=f.add_subplot(122)
sns.distplot(data[(data.sex == 'female')]['age'],color='r',ax=ax)
ax.set_title('Distribution of ages of female')
"""
* As you can see age distribution of male and female are almost same .
"""
"""
# Age distribution of Smoker vs Non-Smoker
"""
sns.boxplot(x='smoker',y='age',data=data)
f= plt.figure(figsize=(12,5))

ax=f.add_subplot(121)
sns.distplot(data[(data.smoker == 'yes')]["age"],color='#b0b0b0',ax=ax)
ax.set_title('Distribution of ages of smoker')

ax=f.add_subplot(122)
sns.distplot(data[(data.smoker == 'no')]['age'],color='#333ed6',ax=ax)
ax.set_title('Distribution of ages of non smoker')
"""
* As you can see there is slight change in distribution of smoker and non smoker and also we can see there is some interesting spike in % of age group between 18-22.
"""
"""
# Smokers count by gender
"""
sns.catplot(x="smoker", kind="count",hue = 'sex',palette='GnBu',data=data)
"""
* There are more male smokers than female,but difference is not that big.
* More non smokers patients than smokers patients .
"""
"""
# Cost distribution of smokers Vs non smokers 
"""
sns.boxplot(x='smoker',y='charges',palette='viridis',data=data)
f= plt.figure(figsize=(12,5))

ax=f.add_subplot(121)
sns.distplot(data[(data.smoker == 'yes')]["charges"],color='#b0b0b0',ax=ax)
ax.set_title('Distribution of charges of smoker')

ax=f.add_subplot(122)
sns.distplot(data[(data.smoker == 'no')]['charges'],color='#333ed6',ax=ax)
ax.set_title('Distribution of charges of non smoker')
"""
* Smoking patients spend more 
"""
"""
# Charges of patients Age 18-22 of smokers Vs non-smokers
"""
sns.boxplot(x='smoker',y='charges',data=data[(data.age>=18)&(data.age<=22)])
"""
* As we can see, patients of age 18-22 smokers spend much more on treatment than non-smokers. Although we can see some outliers om non smokers this may be due to some serious disease.
"""
"""
# Age vs charges of smokers
"""
sns.scatterplot(x="age", y="charges", data=data[data.smoker=='yes'],color='purple')
g = sns.jointplot(x="age", y="charges", data=data[data.smoker=='yes'], kind="kde", color="b")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("age", "charges");
sns.jointplot(x="age", y="charges", data=data[data.smoker=='yes'], kind="kde");
"""
# Age vs Charges of Non-smokers
"""
sns.scatterplot(x="age", y="charges", data=data[data.smoker=='no'],color='#82113a')
g = sns.jointplot(x="age", y="charges", data=data[data.smoker=='no'], kind="kde", color="#82113a")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("age", "charges");
sns.jointplot(x="age", y="charges", data=data[data.smoker=='no'],color='#82113a', kind="kde");
"""
* In case of non smokers charges increase with age ,  but in case of smokers there is no such dependency.
"""
"""
# Bmi of Male Vs Female
"""
sns.boxplot(x='sex',y='bmi',palette='viridis',data=data)
f= plt.figure(figsize=(12,5))

ax=f.add_subplot(121)
sns.distplot(data[(data.sex == 'male')]["bmi"],color='b',ax=ax)
ax.set_title('Distribution of bmi of male')

ax=f.add_subplot(122)
sns.distplot(data[(data.sex == 'female')]['bmi'],color='r',ax=ax)
ax.set_title('Distribution of bmi of female')
"""
* Distribution of bmi of male and female are normally distributed
"""
f= plt.figure(figsize=(12,5))

ax=f.add_subplot(121)
sns.distplot(data[(data.smoker == 'yes')]["bmi"],color='#b0b0b0',ax=ax)
ax.set_title('Distribution of bmi of smoker')

ax=f.add_subplot(122)
sns.distplot(data[(data.smoker == 'no')]['bmi'],color='#333ed6',ax=ax)
ax.set_title('Distribution of bmi of non smoker')
"""
* distribution of bmi of  smoker and non smoker are normally distributed
"""
"""
# Patients Region wise
"""
sns.catplot(x="region", kind="count",palette='viridis',data=data)
sns.catplot(x="region", kind="count",hue = 'sex',palette='viridis',data=data)
"""
# Bmi vs Charges
"""
sns.lmplot(x="bmi", y="charges",data=data);
"""
# Bmi vs Charges of smoker Vs non smoker
"""
sns.lmplot(x="bmi", y="charges", hue="smoker", data=data, palette="Set1")
sns.lmplot(x="bmi", y="charges", hue="smoker", col="sex", data=data)
sns.lmplot(x="bmi", y="charges", col="children", data=data,aspect=.5)
g = sns.jointplot(x="bmi", y="charges", data=data, kind="kde", color="#4837cc")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("bmi", "charges")
"""
# Childrens Vs Charges
"""
sns.catplot(x="children", kind="count",palette='rainbow',data=data)
sns.lmplot(x="children", y="charges",data=data)
sns.lmplot(x="children", y="charges", hue='smoker',data=data)
"""
# Correlation matrix
"""
f, ax = plt.subplots(figsize=(10, 8))
corr = data.corr()
sns.heatmap(corr)
"""
<font size="+3" color='#1f0c75' ><b>Data Modelling and Evaluation </b></font>
"""
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score,mean_squared_error
"""
# Create dummy variables 
"""

#sex
le = LabelEncoder()
le.fit(data.sex.drop_duplicates()) 
data.sex = le.transform(data.sex)
# smoker or not
le.fit(data.smoker.drop_duplicates()) 
data.smoker = le.transform(data.smoker)
#region
le.fit(data.region.drop_duplicates()) 
data.region = le.transform(data.region)
data.head()
"""
# Train Test split
"""
x = data.drop(['charges','region'], axis = 1)
y = data.charges

x_train,x_test,y_train,y_test = train_test_split(x,y, random_state = 0)
"""
# Linear regression
"""
lreg = linear_model.LinearRegression()
lreg.fit(x_train,y_train)
y_train_pred = lreg.predict(x_train)
y_test_pred = lreg.predict(x_test)
lreg.score(x_test,y_test)
"""
# Polynomial Regression 
"""
degree=2
polyreg=make_pipeline(PolynomialFeatures(degree),LinearRegression())
polyreg.fit(x_train,y_train)
y_train_pred = polyreg.predict(x_train)
y_test_pred = polyreg.predict(x_test)
polyreg.score(x_test,y_test)
"""
# Decision Tree Regressor
"""
dt_regressor = DecisionTreeRegressor(random_state=0)
cross_val_score(dt_regressor,x_train, y_train, cv=10).mean()
"""
# Random Forest Regressor
"""
Rf = RandomForestRegressor(n_estimators = 100,
                              criterion = 'mse',
                              random_state = 1,
                              n_jobs = -1)
Rf.fit(x_train,y_train)
Rf_train_pred = Rf.predict(x_train)
Rf_test_pred = Rf.predict(x_test)


r2_score(y_test,Rf_test_pred)
"""
# Conclusion

* Got maximum score of 0.88 from polynomial regression
* Although random forest regressor performing good with an accuracy 0.86
"""
"""
<font size="+1" color=purple ><b> I hope you enjoyed this kernel ,also if you have any suggestions to improve my model ,then feel free to comment it down .</b></font>
"""
"""
<img src="https://i.pinimg.com/originals/71/c0/68/71c068478e7499d73ec005eacbe42c10.gif">
"""