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

# # Linear Regression in Python 

# Linear Regression Using Statsmodels.api 
import statsmodels.api as sm
import pandas as pd

# # Data Preprocessing

# Reading the Data
data = pd.read_csv("insurance.csv", delimiter = ",")

print(data.head(n=5))

# +
# Getting the data ready for the models
data = pd.DataFrame(data) 
predictors = data.iloc[:,:6] #all columns except charges 
y = data.iloc[:,-1] #charges, response variable
df = data.copy() #copying the data 

# Label encoding the data - from categorical to numerical 
object_df = data.select_dtypes(include=['object']).copy()
object_df["sex"] = object_df["sex"].astype('category')
object_df["smoker"] = object_df["smoker"].astype('category')
object_df["region"] = object_df["region"].astype('category') 

object_df["sex_binary"] = object_df["sex"].cat.codes
object_df["smoker_binary"] = object_df["smoker"].cat.codes
object_df["region_encoded"] = object_df["region"].cat.codes


#changing the columns in the data
df["sex"] = object_df["sex_binary"]
df["smoker"] = object_df["smoker_binary"]
df["region"] = object_df["region_encoded"] 


print(df.head(n=5))
# -

# # Modeling

# Models 
predictors = df.iloc[:,:6] #all columns except charges - using the new dataframe, 'df' 
for i in predictors: 
    X = predictors[i] 
    X = sm.add_constant(X) #adding a constant - adding an intercept otherwise we would get the wrong model
    model = sm.OLS(y,X) 
    results = model.fit() 
    print(f"{i} vs. charges: ", results.summary())

StarcoderdataJupyterScriptsDedupFiltered