-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdvertising_KNN.py
335 lines (147 loc) · 4.73 KB
/
Advertising_KNN.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python
# coding: utf-8
# # Advertising Dataset
# ### This Dataset contain the Information about the users either they clicked on Advertisement or not. Depending on the features like Daily Time spent on a site, Age, Area Income,etc.
# ## Importing Libraries
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='ignore')
# ## Importing the Dataset
# In[2]:
df=pd.read_csv('advertising.csv')
# In[29]:
df.head(3)
# ## Exploratory Data analysis (EDA)
# > Area Income vs Age (hue=Sex)
# In[79]:
sns.set_style('whitegrid')
sns.jointplot(df['Age'],df['Area Income'],hue=df['Male'],palette='Set1');
# > Area Income (histogram)
# In[75]:
plt.figure(figsize=(15,4),dpi=300)
plt.hist(df['Area Income'],color='green')
plt.xlabel('Area Income');
# > Pairplot (Dataset)
# In[78]:
sns.pairplot(df,hue='Male');
# > Correlation of all Features (Heatmap)
# In[90]:
plt.figure(figsize=(17,8),dpi=300)
sns.heatmap(df.corr(),fmt='g',annot=True);
# ## Checking for the null values
# > Heatmap to check null values
# In[83]:
plt.figure(figsize=(17,4),dpi=300)
sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis');
# ## Adjusting the data
# In[5]:
df.head()
# In[6]:
df.drop((['Ad Topic Line','Country','Timestamp','City']),axis=1,inplace=True)
# In[7]:
df
# ## Scaling the Data
# In[8]:
from sklearn.preprocessing import StandardScaler
# In[9]:
scaler=StandardScaler()
# In[10]:
scaler.fit(df.drop('Clicked on Ad',axis=1))
# In[11]:
scaler_features=scaler.transform(df.drop('Clicked on Ad',axis=1))
# In[12]:
df_fit=pd.DataFrame(scaler_features,columns=df.columns[:-1])
# In[13]:
df_fit
# ### 0 null values : ready to deal with the model
# ## Train Test Split
# In[14]:
df
# In[15]:
X=df_fit
y=df['Clicked on Ad']
# In[16]:
from sklearn.model_selection import train_test_split
# In[17]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# ## Creating the model
# In[18]:
from sklearn.neighbors import KNeighborsClassifier
# In[19]:
knn=KNeighborsClassifier(n_neighbors=1)
# In[20]:
knn.fit(X_train,y_train)
# ## Predictions & Evaluations
# In[21]:
predictions= knn.predict(X_test)
# In[22]:
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
# In[23]:
print(classification_report(y_test,predictions))
print('\n')
print(confusion_matrix(y_test,predictions))
print('\n')
print("Acccuracy : ",accuracy_score(y_test,predictions)*100,'%')
# ## Finding the best k value for model
# In[24]:
error_rate=[]
for i in range(1,40):
knn=KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train,y_train)
pred_i=knn.predict(X_test)
error_rate.append(np.mean(pred_i!=y_test))
# In[27]:
sns.set_style('whitegrid')
plt.figure(figsize=(20,6),dpi=300)
plt.plot(range(1,40),error_rate,color='blue',marker='o',ls='dashed',markerfacecolor='red',markersize=15)
plt .title('Error rate VS K value')
plt.xlabel('K')
plt.ylabel('Error rate');
# #### According to the plot k>20 gives maximum accuracy
# > for k==24,31,etc. we can get the maximum accuracy.
# ## Training the model for k==31
# In[28]:
knn=KNeighborsClassifier(n_neighbors=31)
knn.fit(X_train,y_train)
pred=knn.predict(X_test)
print('Classfication report: \n\n',classification_report(y_test,pred))
print('\n')
print('Confusion matrix : \n\n',confusion_matrix(y_test,pred))
print('\n')
print('Accuracy :',accuracy_score(y_test,pred)*100,'%')
# ## Testing the model
# ### To test the model have to pass all the list of values require to train the X of model, but due to KNN we have to get values from user & have to scale them with dataset to get maximum accuracy through KNN model
# > Taking values from user
# In[ ]:
y_test
# In[ ]:
df.head()
# In[ ]:
Daily_Time_Spent_on_Site=float(input('Daily Time Spent on site :'))
Daily_Time_Spent_on_Site=float(input('Income :'))
Daily_Internet_Usage=float(input('Daily internet Usage :'))
Male=float(input('0=Female / 1=Male ?'))
# In[ ]:
arr=[[Daily_Time_Spent_on_Site,Daily_Time_Spent_on_Site,Daily_Internet_Usage,Male]]
# In[ ]:
scaler.fit(arr)
# In[ ]:
scaler_features=scaler.transform(arr)
# In[ ]:
scaler_features
# In[ ]:
X_test
# In[ ]:
df_user=pd.DataFrame(arr,columns=['Daily_Time_Spent_on_Site','Daily_Time_Spent_on_Site','Daily_Internet_Usage','Male'])
# In[ ]:
df_user
# In[ ]:
predictions=knn.predict(df_user)
if predictions[0]==0:
print(em.emojize(':green_circle:'),"Employee is not going to leave the company.",em.emojize(':green_circle:'))
else:
print(em.emojize(':prohibited:'),'Employee is going to leave the comapany',em.emojize(':prohibited:'))