
# coding: utf-8

# # Importing Libraries

# In[2]:


import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score,mean_absolute_error,mean_squared_error


# In[3]:


data = pd.read_csv("mobiledata.csv",encoding='unicode_escape')
data.rename(columns={' PRICE ':'PRICE'},inplace=True)
data


# # BRAND

# In[4]:


data['BRAND']=data.BRAND.map({'APPLE':57000,'ASUS':20000,'COOLPAD':12000,'HONOR':17000,'HTC':19500,'INTEX':6500,'KARBONN':6200,'LAVA':7000,'LENOVO':13000,'LG':22500,'MICROSOFT':12000,'MOTO':17500,'NOKIA':11200,'ONEPLUS':32000,'OPPO':17000,'PANASONIC':9500,'REDMI':8300,'SAMSUNG':26000,'SONY':26500,'VIVO':17000,'MICROMAX':13500})


# In[5]:


V=data[['BRAND','PRICE','OS','COLOR']]
V2=V.groupby(['BRAND'], as_index=False).mean()
V2.sort_values('PRICE',inplace=True)
V2.set_index('BRAND',inplace=True)
V2


# In[6]:


'''''V2.plot(kind='bar', figsize=(10, 6), rot=90) # rotate the bars by 90 degrees

plt.xlabel('brands')
plt.ylabel('price')
plt.title('Average Price')

plt.show()'''''


# # OS

# In[7]:


data['OS']=data.OS.map({'ANDROID':16903,'iOS':57590,'WINDOWS':10707})


# In[8]:


V=data[['PRICE','OS']]
V3=V.groupby(['OS'], as_index=False).mean()
V3.sort_values('PRICE',inplace=True)
V3.set_index('OS',inplace=True)
V3


# In[9]:


colors_list = ['gold', 'yellowgreen', 'lightcoral']
explode_list = [0.1, 0, 0.1] # ratio for each continent with which to offset each wedge.

V3.plot(kind='pie',
                            figsize=(15, 6),
                            autopct='%1.1f%%', 
                            startangle=90,    
                            shadow=True,       
                            labels=None,
                            subplots=True,
                            pctdistance=1.12,    # the ratio between the center of each pie slice and the start of the text generated by autopct 
                            colors=colors_list,  # add custom colors
                            explode=explode_list # 'explode' lowest 3 continents
                            )

# scale the title up by 12% to match pctdistance
plt.title('OS') 

plt.axis('equal') 

# add legend
plt.legend(labels=V3.index, loc='upper left') 

plt.show()


# # VERSION

# In[10]:


version = data["VERSION"].apply(lambda x : str(x).strip(" "))
version = version.replace(['','nan'],[7,7])
v = version.replace(['7.1.1','6.0.1','7.1.2','4.4.4','5.1.1','4.4.2','4.2.1','4.2.2','5.0.2','11.1.1','10.0.1'],
                             [7,6,7,4,5,4,4,4,5,11,10])
v = v.replace(['7.1','5.1','4.2','4.3','4.4','8.1','6.01'],
             [7,5,4,4,4,8,6])
v = pd.to_numeric(v)
data["VERSION"] = v


# In[11]:


data["VERSION"].value_counts()


# In[12]:


V=data[['PRICE','VERSION']]
V3=V.groupby(['VERSION'], as_index=False).mean()
V3.sort_values('PRICE',inplace=True)
V3.set_index('VERSION',inplace=True)
V3


# In[13]:


colors_list = ['gold', 'yellowgreen', 'lightcoral','red','pink','green','blue']
explode_list = [0, 0, 0,0
                ,0,0.1,0.1] # ratio for each continent with which to offset each wedge.

V3.plot(kind='pie',
                            figsize=(15, 6),
                            autopct='%1.1f%%', 
                            startangle=90,    
                            shadow=True,       
                            labels=None,
                            subplots=True,
                            pctdistance=1.12,    # the ratio between the center of each pie slice and the start of the text generated by autopct 
                            colors=colors_list,  # add custom colors
                             # 'explode' lowest 3 continents
                            )

# scale the title up by 12% to match pctdistance
plt.title('OS') 

plt.axis('equal') 

# add legend
plt.legend(labels=V3.index, loc='upper left') 

plt.show()


# 
# # RAM

# In[14]:


data["RAM"] = data["RAM"].replace(['512MB'],'0.5GB')
data["RAM"] = data["RAM"].apply(lambda x : str(x).strip(" "))
R = []

for r in data["RAM"]:
    R.append(str(r)[:-2])
    
data["RAM"]=R



# # MEMORY

# In[15]:


data["MEMORY"] = data["MEMORY"].apply(lambda x : str(x).strip(" "))
M= []

for m in data["MEMORY"]:
    M.append(str(m)[:-2])
    
data["MEMORY"] = M


# In[16]:


V=data[['PRICE',"MEMORY"]]
V3=V.groupby(["MEMORY"], as_index=False).count()

V3.set_index("MEMORY",inplace=True)
V3


# # DISPLAY

# In[17]:


data["DISPLAY"] = data["DISPLAY"].apply(lambda x : str(x).strip(" "))
D = []

for d in data["DISPLAY"]:
    D.append(str(d)[:-4])
    
D = pd.Series(D).apply(lambda x : str(x).strip(" "))
D = D.replace([''],['5.5'])
D= pd.to_numeric(D)
data["DISPLAY"] = D


# In[18]:


import seaborn as sns
sns.regplot(x='DISPLAY', y='PRICE', data=data)


# # PRIMARY CAMERA 

# In[19]:


data["PRIMARYCAMERA"] = data["PRIMARYCAMERA"].apply(lambda x : str(x).strip(" "))

P = []

for p in data["PRIMARYCAMERA"]:
     P.append(str(p)[:-2])
        
P = pd.Series(P).replace(['v','n'],['0.3','13'])
     
data["PRIMARYCAMERA"] = P


# # Secondary camera

# In[20]:


data["SECONDARYCAMERA"] = data["SECONDARYCAMERA"].apply(lambda x : str(x).strip(" "))

S = []

for s in data["SECONDARYCAMERA"]:
     S.append(str(s)[:-2])

S = pd.Series(S).replace(['n'],['5'])

data["SECONDARYCAMERA"] = S


# # BATTERY

# In[21]:


B = data["BATTERY"].apply(lambda x : str(x).strip("  "))


b = []
for a in B:
    z = a[0:4]
    b.append(z)
    
    
battery = pd.Series(b)

battery.replace(to_replace = ['nan','300m'],value = [0,'3000'],inplace=True)

Battery = []
for r in battery:
    if (int(r) <= 1500):
        r = 1500
        Battery.append(r)
    elif(int(r)>1500 and int(r)<=2000):
        r = 2000
        Battery.append(r)
    elif(int(r)>2000 and int(r)<=2500):
        r = 2500
        Battery.append(r)
    elif(int(r)>2500 and int(r)<=3000):
        r = 3000
        Battery.append(r)
    elif(int(r)>3000 and int(r)<=3500):
        r = 3500
        Battery.append(r)
    elif(int(r)>3500 and int(r)<=4000):
        r = 4000
        Battery.append(r)
    elif(int(r)>4000 and int(r)<=4500):
        r = 4500
        Battery.append(r)
    elif(int(r)>4500 and int(r)<=5000):
        r = 5000
        Battery.append(r)

data["BATTERY"] = Battery


# # COLOR

# In[22]:


data["COLOR"]  = data["COLOR"].apply(lambda x : str(x).strip(" "))
data["COLOR"]  = data["COLOR"].apply(lambda x : x.lower())


# # PROCESSOR

# In[23]:


Processor = []
for a in data["PROCESSOR"]:
    b = str(a).lower()
    Processor.append(b)
    
P = pd.Series(Processor).apply(lambda x: str(x).strip(" "))

p = []
for a in P:
    if(a == "dual"):
        a = 2
        p.append(a)
    elif(a == "quad"):
        a = 4
        p.append(a)
    elif(a == "hexa"):
        a = 6
        p.append(a)
    elif(a == "octa"):
        a = 8
        p.append(a)
    elif(a == "deca"):
        a = 10
        p.append(a)
    else:
        a = 0
        p.append(a)
        
data["PROCESSOR"] = p


# # DIMENSION
# 

# In[24]:


Display = data['DIMENSION'].apply(lambda x : str(x).split(".")[0])
Display = Display.replace(['101970','nan'],['1019','0'])
data["DIMENSION"] = Display


# # WEIGHT

# In[25]:


W = data["WEIGHT"].apply(lambda x : str(x).strip(" "))


# In[26]:


weight = []
for c in W:
    if( c == 'nan'):
        b = 0
        weight.append(b)
    elif(c == '2.43Kg'):
        b = '243'
        weight.append(b)
    else:
        b = c[:3]
        weight.append(b)

    
data["WEIGHT"] = weight


# # TECHNOLOGY

# In[27]:


technology = data["TECHNOLOGY"].apply(lambda x : str(x).strip(" "))
t = technology.replace(['4G','3G','2G','nan'],[4,3,2,4])
data["TECHNOLOGY"] = t


# In[28]:


data[['RAM','PRIMARYCAMERA','SECONDARYCAMERA','DIMENSION','WEIGHT','MEMORY']]=data[['RAM','PRIMARYCAMERA','SECONDARYCAMERA','DIMENSION','WEIGHT','MEMORY']].applymap(float)



# In[29]:


data.corr()["PRICE"]



# In[30]:


data = data.drop(["MODEL NO","COLOR"],axis = 1)


# In[31]:


def acc(y_test,y_pred):
    
    import math 
    from sklearn.metrics import r2_score,mean_absolute_error,mean_squared_error
    
    
    
    
    mse = int(mean_squared_error(y_test,y_pred))
    print("r2_score :" , r2_score(y_test,y_pred))
    print("mean_absolute_error :" ,mean_absolute_error(y_test,y_pred))
    print("mean_squared_error : " ,mse)
    print("rmse : ",math.sqrt(mse))
    
    
    
    plt.figure(figsize=(16,6))
    plt.plot(np.arange(53),pd.DataFrame(y_test),marker = '.')
    plt.scatter(np.arange(53),pd.DataFrame(y_pred),color = 'r',marker="*")
    plt.legend(["original results","predicted results"])
    plt.xlabel("Observation",fontsize = 16,color = 'c')
    plt.ylabel("Price",fontsize = 20,color = 'm')
    plt.title('Graphical representation between original results and predicted results',color = 'green',fontsize = 16)
    
    
    y_pred = pd.DataFrame(y_pred)
    y_pred.columns = ["Predicted"]
    
    
    print(pd.concat([pd.DataFrame(y_test).set_index(np.arange(y_test.shape[0])),y_pred],axis = 1))
    
    
    


# In[32]:


def cv(estimator,x,y):
    
    from sklearn.cross_validation import cross_val_score
    min = []
    mean = []
    max = []
  
    
    i = 3
    while(i <=15):
        val = cross_val_score(estimator,x,y,cv = i,scoring='r2')
        min.append(val.min())
        max.append(val.max())
        mean.append(val.mean())
        i = i+1
    
    
    d = { 'min' : min , 'max' : max , "mean" : mean }
    c = pd.DataFrame(d,index = np.arange(3,16,1))
    return c
    
        
    


# In[33]:


x = data.drop(["PRICE"],axis = 1)
y = data["PRICE"]


# In[34]:


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,random_state = 2)


# In[ ]:


from sklearn.ensemble import GradientBoostingRegressor
gbr = GradientBoostingRegressor(min_samples_split=3,random_state=2)
gbr.fit(x_train,y_train)


# In[ ]:


y_pred_gbr = gbr.predict(x_test)


# In[ ]:


acc(y_test,y_pred_gbr)


# In[38]:


from sklearn.neighbors import KNeighborsRegressor
knr = KNeighborsRegressor()


# In[39]:


knr.fit(x_train,y_train)


# In[40]:


y_pred_knr = knr.predict(x_test)


# In[41]:


acc(y_test,y_pred_knr)


# In[42]:


from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()


# In[43]:


lr.fit(x_train,y_train)


# In[44]:


y_pred_lr = lr.predict(x_test)


# In[45]:


acc(y_test,y_pred_lr)


# In[46]:


from sklearn.svm import SVR


# In[ ]:


svr = SVR(kernel = 'poly')


# In[ ]:


svr.fit(x_train,y_train)


# In[ ]:


y_pred_svr = svr.predict(x_test)  


# In[ ]:


y_pred_svr


# In[ ]:


acc(y_test,y_pred_svr)

