Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

Crop_Pred_ Nigeria.py 42 KB

You have to be logged in to leave a comment. Sign In
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # # Crop Prediction for Nigeria Agriculture using Essmbel Machine learning
  4. #
  5. # Crop yield which is too uncertain to estimate is an esential factor for determining farmer's income level. The difficult to estimate yiled of agricultural crop is duetto its reliance on weather conditions (rain, temperature, etc), pesticides and information about history of crop yield even. These all makes possibel making decisions related to agricultural risk management and future predictions if obtained and articulate exactly. Dueto its yet not innovated sector and its natural behaviour obtaing concise and organized agricultural data even today is very challenging. One important source of information in this sector thta provide a panel data is Food and agricultural organization(FAO).From FAO Database data related to crop yiled, rainfall and pestcide extracted fot Nigeria. To make the climatic factor complet from abiotic factor perspectiv, we also considere nigeria's temperature to incorporate with crop yiled prediction.
  6. # # Table of contents
  7. #
  8. # 1. Data Importing and Prearation
  9. #
  10. # 2. Exploratory Analysis
  11. #
  12. # 3. Model Developmemnt and Selection
  13. #
  14. # 6. Hybriding algorithm with pipline
  15. #
  16. # 7. Drawing conclusion
  17. # # 1. Data Importing and preparation
  18. # As the outpuet indicates there are about 56717 rows and 12 columns for the crop yiled dataset. only column like Area, Itme and value columns are importnat to our analsysis. To extract yield data for nigeria we can use Area column where the country can be extracted wit its name Nigeria uing the function `(df_yield.loc[df_yield['Area'] == 'Nigeria'])`. It is also possible to exttract using Area Code column and `(df_yield.loc[df_yield['Area Code'] == '159'])` Thanks to William Green from the Omdena Zowasel chalenege for sharng Nigerian agriculture dataset from FAO (https://files.slack.com/files-pri/T03NM44BRB9-F03TAHA5FBM/download/crop_yield-20220811t144327z-001.zip?origin_team=T03NM44BRB9)
  19. # In[1]:
  20. Nig_yield = pd.read_csv('C:\\Users\\moga\\Desktop\\Files\\Crop_dataset\\crop_yield\\FAOSTAT_data_en_8-9-2022_yield.csv')
  21. Nig_yield.head()
  22. # In[2]:
  23. # Crop Nierogen dataset
  24. Nig_Nitro = pd.read_csv('C:\\Users\\moga\\Desktop\\Files\\Crop_dataset\\crop_yield\\FAOSTAT_data_en_8-9-2022_nitrogen.csv')
  25. Nig_Nitro.head()
  26. # In[3]:
  27. # import Rainfal dataset
  28. Nig_rain = pd.read_csv('C:\\Users\\moga\\Desktop\\Files\\Crop_dataset\\crop_yield\\1901-2021_NGA_rain.csv')
  29. Nig_rain .head()
  30. # In[4]:
  31. #import temprature dataset
  32. Nig_temp = pd.read_csv('C:\\Users\\moga\\Desktop\\Files\\Crop_dataset\\crop_yield\\observed-average-annual-mean-temperature-of-nigeria-for-1901-2021.csv')
  33. Nig_temp.head()
  34. # ## 1.2 Checking for Missing value
  35. # In[5]:
  36. #check for missikng value
  37. Nig_yield.info()
  38. # In[6]:
  39. Nig_yield.describe()
  40. # In[7]:
  41. #check missing data for nitrogen
  42. Nig_Nitro.info()
  43. # In[8]:
  44. # descriptive statistics for niterogen data
  45. Nig_Nitro.describe()
  46. # In[9]:
  47. Nig_rain.info()
  48. # In[10]:
  49. #Dropunwanted column for raainfall
  50. Nig_rain.describe()
  51. # In[11]:
  52. Nig_temp.info()
  53. # In[12]:
  54. Nig_temp.describe()
  55. # ## 1.2 Droping unwanted Columns
  56. # In[13]:
  57. Nig_yield.columns
  58. # In[14]:
  59. # drop unwanted columns for yiled data
  60. Nig_yield = Nig_yield.drop(['Domain Code','Area Code (FAO)','Area','Element Code',
  61. 'Item Code (FAO)','Year Code','Unit','Flag','Flag Description'], axis=1)
  62. Nig_yield.head()
  63. # In[15]:
  64. #Drop unwanted column for niterogen data
  65. Nig_Nitro=Nig_Nitro.drop(['Domain Code','Domain','Area Code (FAO)','Area','Element Code','Element',
  66. 'Item Code','Item','Year Code','Unit','Flag','Flag Description'],axis=1)
  67. Nig_Nitro.head()
  68. # Though the datasetsfor the four features are cleaned and checked for missing value, they are in separate dataframe and mereging into one datafrmae is done next.
  69. #
  70. # ## 1.3 Combining DataSets
  71. # Three possible ways or functions to combine data in panda includes
  72. # - **Merege functio,** `Mereg()`:for combining data on common columns or indices
  73. #
  74. # - **Join Functio**`.join()`:for combining data on common columns or indices
  75. #
  76. # - **concatnate function**, `Concat()`: for combining DataFrames across rows or columns
  77. # In[16]:
  78. yile_nitr = pd.merge(Nig_yield,Nig_Nitro, on=["Year"] )
  79. yile_nitr.head()
  80. # In[17]:
  81. yile_nitr_rain = pd.merge(yile_nitr,Nig_rain, on =["Year"] )
  82. yile_nitr_rain.head()
  83. # Since column name for temprature dataset is`Category` it must be renamed as `Year`
  84. # In[18]:
  85. Nig_temp=Nig_temp.rename(index=str, columns={"Category": 'Year'})
  86. Nig_temp.head()
  87. # In[19]:
  88. # defining the combibed dataframe
  89. df_com = pd.merge(yile_nitr_rain,Nig_temp, on =["Year"] )
  90. df_com
  91. # In[20]:
  92. df_com.columns
  93. # In[21]:
  94. # still droping of some column seems essential
  95. df_com = df_com.drop(['Domain','Element'], axis =1)
  96. df_com
  97. # - let's also rename some columns for convinece
  98. # In[22]:
  99. df_com = df_com.rename(index=str, columns={"Value_x": 'Yiled/ha',"Value_y":'Niro/ha',
  100. "Annual Mean":'Mean_Temp',"5-yr smooth":'smooth_Temp'})
  101. df_com.head()
  102. # In[23]:
  103. df_com.describe()
  104. # # 2. EXploratory Analysis
  105. # In[24]:
  106. from mpl_toolkits.mplot3d import Axes3D
  107. from sklearn.preprocessing import StandardScaler
  108. import matplotlib.pyplot as plt # plotting
  109. import seaborn as sns
  110. import numpy as np # linear algebra
  111. import os # accessing directory structure
  112. import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)from mpl_toolkits.mplot3d import Axes3D
  113. from sklearn.preprocessing import StandardScaler
  114. import matplotlib.pyplot as plt # plotting
  115. import numpy as np # linear algebra
  116. import os # accessing directory structure
  117. import pandas as pd # data processing, CSV file I/O (e.g. pd.read_c
  118. # # 2.1 Exploring Data Aggregation uing Seaborn Visualization
  119. # In[25]:
  120. #grouping dataset by column Item for production information
  121. df_com.groupby(['Item'],sort=True)['Yiled/ha'].sum().nlargest(20)
  122. # In[26]:
  123. #aggregation of the data is based on the various momnets and respective variance
  124. plt.figure(figsize=(50,30))
  125. sns.set_context('poster',font_scale=1.6)
  126. plt.subplot(3,1,1)
  127. sns.barplot(x='Item',y='Value', data=Nig_yield)
  128. plt.legend(['mean aggregate'],loc=1)
  129. plt.xticks(rotation=90)
  130. plt.subplot(3,1,2)
  131. sns.barplot(x='Item',y='Value', data=Nig_yield, estimator =np.median)
  132. plt.legend(['medain aggregate'],loc=1)
  133. plt.xticks(rotation=90)
  134. plt.subplot(3,1,3)
  135. sns.barplot(x='Item',y='Value', data=Nig_yield, estimator =np.std)
  136. plt.legend(['std aggregate'],loc=1)
  137. plt.xticks(rotation=90)
  138. # In[27]:
  139. plt.figure(figsize=(50,30))
  140. sns.set_context('paper',font_scale=4,)
  141. plt.subplot(3,1,1)
  142. sns.barplot(x='Item',y='Value', data=Nig_yield, estimator =np.var)
  143. plt.legend(['var aggregate'],loc=1)
  144. plt.xticks(rotation=90)
  145. plt.subplot(3,1,2)
  146. sns.barplot(x='Item',y='Value', data=Nig_yield, estimator =np.cov)
  147. plt.legend(['Cov aggregate'],loc=1)
  148. plt.xticks(rotation=90)
  149. # ## 2.2 Pivoting and Ternd Analsysi
  150. # In[28]:
  151. get_ipython().run_line_magic('matplotlib', 'inline')
  152. plt.figure(figsize=(30,25))
  153. sns.set()
  154. table = pd.pivot_table(Nig_yield, values = 'Value', index=['Year'],
  155. columns=['Item'], aggfunc=np.sum)
  156. table.plot()
  157. # In[29]:
  158. get_ipython().run_line_magic('matplotlib', 'inline')
  159. plt.figure(figsize=(30,25))
  160. sns.set()
  161. Nig_yield.pivot_table('Value', index=['Year'],
  162. columns=['Item'], aggfunc=np.sum).plot()
  163. plt.ylabel('yield per year')
  164. # In[30]:
  165. sns.pairplot(Nig_yield)
  166. # In[31]:
  167. # use hue to categorize base on categorical vriable sex for example
  168. sns.pairplot(Nig_yield,hue='Item', palette='Blues')
  169. # In[32]:
  170. plt.figure(figsize=(50,30))
  171. sns.set_theme(color_codes=True)
  172. #sns.set_context('paper',font_scale=1.4)
  173. sns.lmplot(x='Mean_Temp',y='Yiled/ha', hue='Item',data=df_com)
  174. # In[33]:
  175. plt.figure(figsize=(50,30))
  176. sns.set_theme(color_codes=True)
  177. #sns.set_context('paper',font_scale=1.4)
  178. sns.lmplot(x='smooth_Temp',y='Yiled/ha', hue='Item',data=df_com)
  179. # In[34]:
  180. plt.figure(figsize=(50,30))
  181. sns.set_theme(color_codes=True)
  182. sns.set_context('paper',font_scale=1.4)
  183. sns.lmplot(x='Niro/ha',y='Yiled/ha', hue='Item',data=df_com)
  184. # In[35]:
  185. plt.figure(figsize=(50,30))
  186. sns.set_theme(color_codes=True)
  187. sns.set_context('paper',font_scale=1.4)
  188. sns.lmplot(x='Year',y='Yiled/ha', hue='Item',data=df_com)
  189. # In[36]:
  190. #option 2: using heatmap
  191. plt.figure(figsize=(8,6))
  192. sns.set_context('paper',font_scale =1.4)
  193. yield_mx= df_com.corr()
  194. sns.heatmap(yield_mx,annot =True, cmap='Blues')
  195. # ## 2.4 curse of symetery
  196. #
  197. # In <font color ='magneta'>Cramer’s_V</font> it seems possible to guarantee what value of the feature for known value of the response variable but is difficult for the revers. This is known as <font color='magneta'>symetry property</font> and works for <font color ='magneta'>Cramer’s V</font>.
  198. #
  199. # For utilizing asymmetric measure of association between categorical features,<font color='magneta'>Theil’s U</font> is being recommnded and also referred to as the <font color='magneta'>Uncertainty Coefficient</font>.
  200. #
  201. # It is based on the <font color ='magneta'>conditional entropy</font> between x and y — or in human language, given the value of x, how many possible states does y have, and how often do they occur.
  202. # Just like<font color='magneta'>Cramer’s V</font>, the output value is on the range of [0,1], with the same interpretations as before — but unlike <font color='magneta'> Cramer’s V</font>, it is asymmetric, meaning U(x,y)$\ne$ U(y,x) (while V(x,y)=V(y,x), where V is <font color='magneta'>Cramer’s V</font>. Using<font color='magneta'>Theil’s U</font> in the simple case above will let us find out that knowing y means we know x, but not vice-versa. <font color='magneta'>Theil's U</font>, also known as the<font color ='magneta'>Uncertainty Coefficient</font>.
  203. #
  204. # Formaly marked as U(x|y), this coefficient provides a value in the range of [0,1], where 0 means that feature y provides no information about feature x, and 1 means that feature y provides full information abpout features x's value.
  205. #
  206. # Theil’s U statistic is a relative accuracy measure that compares the forecasted results with the results of forecasting with minimal historical data. It also squares the deviations to give more weight to large errors and to exaggerate errors, which can help eliminate methods with large errors
  207. #
  208. # The formula for calculating Theil’s U statistic:
  209. # ![image.png](attachment:image.png)
  210. #
  211. # where $Y_t$ is the actual value of a point for a given time period t, n is the number of data points, and $\hat{Y_t}$ is predicted valye.
  212. # In[37]:
  213. import math
  214. from collections import Counter
  215. import numpy as np
  216. import seaborn as sns
  217. import pandas as pd
  218. import scipy.stats as ss
  219. import matplotlib.pyplot as plt
  220. import sklearn.preprocessing as sp
  221. from sklearn.tree import DecisionTreeClassifier
  222. from sklearn.model_selection import train_test_split
  223. from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
  224. from subprocess import check_output
  225. # In[38]:
  226. def conditional_entropy(x,y):
  227. # entropy of x given y
  228. y_counter = Counter(y)
  229. xy_counter = Counter(list(zip(x,y)))
  230. total_occurrences = sum(y_counter.values())
  231. entropy = 0
  232. for xy in xy_counter.keys():
  233. p_xy = xy_counter[xy] / total_occurrences
  234. p_y = y_counter[xy[1]] / total_occurrences
  235. entropy += p_xy * math.log(p_y/p_xy)
  236. return entropy
  237. def theil_u(x,y):
  238. s_xy = conditional_entropy(x,y)
  239. x_counter = Counter(x)
  240. total_occurrences = sum(x_counter.values())
  241. p_x = list(map(lambda n: n/total_occurrences, x_counter.values()))
  242. s_x = ss.entropy(p_x)
  243. if s_x == 0:
  244. return 1
  245. else:
  246. return (s_x - s_xy) / s_x
  247. # In[39]:
  248. theilu = pd.DataFrame(index=['Item'],columns=df_com.columns)
  249. columns = df_com.columns
  250. for j in range(0,len(columns)):
  251. u = theil_u(df_com['Item'].tolist(),df_com[columns[j]].tolist())
  252. theilu.loc[:,columns[j]] = u
  253. theilu.fillna(value=np.nan,inplace=True)
  254. plt.figure(figsize=(20,1))
  255. sns.heatmap(theilu,annot=True,fmt='.2f')
  256. plt.show()
  257. # # 3.Prediction Model Development and Selection
  258. #
  259. # - Here,we will explore both classification and Regression algorithms of the supervised machine learning. For the classification model dvelopement those categorical columns (Item) used as target variables whereas the regration models development constructed using anaual yiled as target variable.
  260. # In[40]:
  261. # Column Varaible is categorical
  262. df_com.info()
  263. # #### 3.1 Baseline Setting
  264. #
  265. # While forecasting there are available accuracy measures with there own prons and cons but generally gropuded as (i) scale dependent errors, (ii) percentage errors and (iii) scaled errors[<font color='blue'>vorgelegt von,2019</font>] the first is for <font color ='Magneat'>mean absolute error</font> (<font color='pureple'>MAE</font>) and <font color ='Magneat'>root mean square error</font> (<font color='pureple'>RMSE</font>) which they typically used to compare dataset having same units and minimizaing them respectively leads to median and mean of the distribution.
  266. #
  267. # <font color ='Mgneat'>mean absolute percentage error </font> (<font color='pureple'> MAPE</font>) and <font color='Mgneat'>symmetric mean absolute percentage error</font> (<font color='pureple'>SMAP</font>) are the Percentage errors tyeps which aallows to measure time seriesat different scale while <font color='Magneat'>mean percentage error</font>(<font color='pureple'>MPE</font>) in this category help as a bias indicator as negative and positive errors offset each other.
  268. #
  269. # Scaled errors as an alternative to percentage-based errors for comparing forecasts on datasets having different scales or units. It incudes the <font color='Magneat'>mean absolute scaled error</font> (<font color='pureple'>MASE</font>).
  270. #
  271. # Let $X_u$ stands for uneconded features and the target varial y which is demand in our case has shown no change at all with regard to encoding as it is contineuous numeric.
  272. # In[41]:
  273. import numpy as np
  274. import pandas as pd
  275. import matplotlib.pyplot as plt
  276. from sklearn.metrics import mean_absolute_error, make_scorer
  277. from sklearn.metrics import mean_squared_error
  278. from sklearn.pipeline import Pipeline
  279. from sklearn.preprocessing import StandardScaler
  280. from sklearn.impute import SimpleImputer
  281. from sklearn.model_selection import KFold
  282. from sklearn.model_selection import train_test_split
  283. from sklearn.model_selection import cross_val_score
  284. from sklearn.base import BaseEstimator, TransformerMixin
  285. from sklearn.linear_model import BayesianRidge
  286. from scipy.special import comb
  287. from xgboost import XGBRegressor
  288. np.random.seed(12345)
  289. get_ipython().run_line_magic('matplotlib', 'inline')
  290. get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'")
  291. # In[42]:
  292. Xu = df_com.drop(columns=['Yiled/ha'],axis=1)
  293. yu = df_com['Yiled/ha']
  294. # In[43]:
  295. Xu_train, Xu_test, yu_train, yu_test = train_test_split(Xu, yu, test_size=0.2, random_state=42)
  296. mean_absolute_error(yu_train,
  297. np.full(yu_train.shape[0], yu_train.mean()))
  298. # In[44]:
  299. mean_squared_error(yu_train,
  300. np.full(yu_train.shape[0], yu_train.mean()))
  301. # Hence, the encoding method is expected to make ready the data for our algorthim that will give <font color ='pureple'>MAE</font> below 38021.27671310749. Since the prediction model will not be perfect a kind of nois which is random must be acknowledged but with normally distributed having a standard deviation of $\sigma^2$=1 and therefore whatever our model is perefect we have to expect <font color ='pureple'>MAE</font>=0.7868967904399754
  302. # In[45]:
  303. mean_absolute_error(np.random.randn(1000),
  304. np.zeros(1000))
  305. # ## 3.2 Crop Prediction Using KNN
  306. # In[46]:
  307. from mpl_toolkits.mplot3d import Axes3D
  308. from sklearn.preprocessing import StandardScaler
  309. import matplotlib.pyplot as plt # plotting
  310. import numpy as np # linear algebra
  311. import os # accessing directory structure
  312. import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)from mpl_toolkits.mplot3d import Axes3D
  313. from sklearn.preprocessing import StandardScaler
  314. import matplotlib.pyplot as plt # plotting
  315. import numpy as np # linear algebra
  316. import os # accessing directory structure
  317. import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
  318. # In[47]:
  319. #define functions for plotting data.
  320. # Distribution graphs (histogram/bar graph) of column data
  321. def plotPerColumnDistribution(df, nGraphShown, nGraphPerRow):
  322. nunique = df.nunique()
  323. df = df[[col for col in df if nunique[col] > 1 and nunique[col] < 50]] # For displaying purposes, pick columns that have between 1 and 50 unique values
  324. nRow, nCol = df.shape
  325. columnNames = list(df)
  326. nGraphRow = (nCol + nGraphPerRow - 1) / nGraphPerRow
  327. plt.figure(num = None, figsize = (6 * nGraphPerRow, 8 * nGraphRow), dpi = 80, facecolor = 'w', edgecolor = 'k')
  328. for i in range(min(nCol, nGraphShown)):
  329. plt.subplot(nGraphRow, nGraphPerRow, i + 1)
  330. columnDf = df.iloc[:, i]
  331. if (not np.issubdtype(type(columnDf.iloc[0]), np.number)):
  332. valueCounts = columnDf.value_counts()
  333. valueCounts.plot.bar()
  334. else:
  335. columnDf.hist()
  336. plt.ylabel('counts')
  337. plt.xticks(rotation = 90)
  338. plt.title(f'{columnNames[i]} (column {i})')
  339. plt.tight_layout(pad = 1.0, w_pad = 1.0, h_pad = 1.0)
  340. plt.show()
  341. # In[48]:
  342. # Correlation matrix
  343. def plotCorrelationMatrix(df, graphWidth):
  344. filename = df.dataframeName
  345. df = df.dropna('columns') # drop columns with NaN
  346. df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values
  347. if df.shape[1] < 2:
  348. print(f'No correlation plots shown: The number of non-NaN or constant columns ({df.shape[1]}) is less than 2')
  349. return
  350. corr = df.corr()
  351. plt.figure(num=None, figsize=(graphWidth, graphWidth), dpi=80, facecolor='w', edgecolor='k')
  352. corrMat = plt.matshow(corr, fignum = 1)
  353. plt.xticks(range(len(corr.columns)), corr.columns, rotation=90)
  354. plt.yticks(range(len(corr.columns)), corr.columns)
  355. plt.gca().xaxis.tick_bottom()
  356. plt.colorbar(corrMat)
  357. plt.title(f'Correlation Matrix for {filename}', fontsize=15)
  358. plt.show()
  359. # In[49]:
  360. # Scatter and density plots
  361. def plotScatterMatrix(df, plotSize, textSize):
  362. df = df.select_dtypes(include =[np.number]) # keep only numerical columns
  363. # Remove rows and columns that would lead to df being singular
  364. df = df.dropna('columns')
  365. df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values
  366. columnNames = list(df)
  367. if len(columnNames) > 10: # reduce the number of columns for matrix inversion of kernel density plots
  368. columnNames = columnNames[:10]
  369. df = df[columnNames]
  370. ax = pd.plotting.scatter_matrix(df, alpha=0.75, figsize=[plotSize, plotSize], diagonal='kde')
  371. corrs = df.corr().values
  372. for i, j in zip(*plt.np.triu_indices_from(ax, k = 1)):
  373. ax[i, j].annotate('Corr. coef = %.3f' % corrs[i, j], (0.8, 0.2), xycoords='axes fraction', ha='center', va='center', size=textSize)
  374. plt.suptitle('Scatter and Density Plot')
  375. plt.show()
  376. # In[50]:
  377. correlation_data=df_com.select_dtypes(include=[np.number]).corr()
  378. mask = np.zeros_like(correlation_data, dtype=np.bool)
  379. mask[np.triu_indices_from(mask)] = True
  380. f, ax = plt.subplots(figsize=(11, 9))
  381. # Generate a custom diverging colormap
  382. cmap = sns.palette="vlag"
  383. # Draw the heatmap with the mask and correct aspect ratio
  384. sns.heatmap(correlation_data, mask=mask, cmap=cmap, vmax=.3, center=0,
  385. square=True, linewidths=.5, cbar_kws={"shrink": .5});
  386. # In[51]:
  387. import numpy as np
  388. import pandas as pd
  389. from sklearn.neighbors import KNeighborsClassifier
  390. from matplotlib import pyplot as plt
  391. from scipy.interpolate import make_interp_spline
  392. #from pandas_profiling import ProfileReport
  393. from pylab import rcParams
  394. from sklearn.model_selection import train_test_split
  395. from sklearn.preprocessing import StandardScaler
  396. from sklearn.metrics import accuracy_score as acc
  397. from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
  398. import seaborn as sns
  399. import warnings
  400. warnings.filterwarnings('ignore')
  401. # For the classification model developemnet we prefer to drop yield column of the combined dataframe as it is a result than a factor to influnce itself. However, we run it for checking on classification purpose and it outperforms the KNN model that ignors yield column we are not sure why it is so if any one can to justify.
  402. # In[52]:
  403. df= df_com.drop(['Yiled/ha'],axis=1)
  404. df.head()
  405. # In[53]:
  406. column_names = ['Year','Rain','Mean_Temp','smooth_Temp','Item']
  407. df = df.reindex(columns=column_names)
  408. df
  409. # In[54]:
  410. col = list(df.columns)
  411. classes = df["Item"].unique()
  412. # In[55]:
  413. xdata = df.iloc[:, 0:4].values
  414. ydata = df.iloc[:, 4].values
  415. plt.figure(figsize = (16, 9))
  416. sns.countplot(classes, palette = 'rocket')
  417. plt.xticks(rotation=90)
  418. # **Plotting the various values of the input parameter for a particular output value**
  419. # In[56]:
  420. all_col = df.columns[:-1]
  421. for col in all_col:
  422. plt.figure(figsize = (16, 9))
  423. sns.barplot(x = 'Item', y = col, data = df, palette = 'rocket')
  424. plt.xlabel('Item', fontsize = 12)
  425. plt.ylabel(col, fontsize = 12)
  426. plt.xticks(rotation=90)
  427. plt.title(f'{col} vs Crop')
  428. plt.show()
  429. # In[57]:
  430. plt.figure(figsize = (10, 17))
  431. sns.pairplot(df, hue = 'Item', palette = 'rocket')
  432. plt.show()
  433. # **Split & scale the data into train and test dataset**
  434. #
  435. # The data set is splited into test and train dataset based on the 80 - 20 rule and it is scaled for better performance for training.
  436. # In[58]:
  437. from sklearn.linear_model import LinearRegression, SGDRegressor
  438. from sklearn.ensemble import RandomForestRegressor
  439. from xgboost import XGBClassifier, XGBRegressor
  440. from sklearn.model_selection import train_test_split
  441. from imblearn.datasets import make_imbalance
  442. from category_encoders.target_encoder import TargetEncoder
  443. import statsmodels.api as sm
  444. xtrain, xtest, ytrain, ytest = train_test_split(xdata, ydata, test_size=0.2, random_state=884)
  445. x_st = StandardScaler()
  446. xtrain = x_st.fit_transform(xtrain)
  447. xtest = x_st.fit_transform(xtest)
  448. # **Requied only for optimising the performance of the KNN algorithm**
  449. #
  450. # The training model is being optimised using trial and error method to determine the best random_state in test_train_split function and the nearest neighbor in the KNN algorithm.
  451. # In[59]:
  452. acc_list = []
  453. err_rate = []
  454. neighbors = np.linspace(1, 50, 50)
  455. neighbors = neighbors.astype(int)
  456. for K in neighbors:
  457. classifier = KNeighborsClassifier(n_neighbors = K)
  458. classifier.fit(xtrain, ytrain)
  459. y_pred = classifier.predict(xtest)
  460. accuracy = round(acc(ytest, y_pred)*100, 3)
  461. acc_list.append(accuracy)
  462. err_rate.append(np.mean(y_pred != ytest))
  463. xy = make_interp_spline(neighbors, acc_list)
  464. xz = make_interp_spline(neighbors, err_rate)
  465. x = np.linspace(1, 50, 1000)
  466. y = xy(x)
  467. z = xz(x)
  468. plt.figure(figsize = (13, 7))
  469. plt.subplot(2, 1, 1)
  470. sns.lineplot(x, y, linewidth = 2, color = '#5C284F')
  471. plt.xlabel('K value')
  472. plt.ylabel('Accuracy (%)')
  473. plt.title('Accuracy vs K', fontweight = 'bold')
  474. plt.xlim(min(neighbors), max(neighbors))
  475. plt.subplot(2, 1, 2)
  476. sns.lineplot(x, z, linewidth = 2, color = '#D96856')
  477. plt.xlabel('K value')
  478. plt.ylabel('Loss')
  479. plt.title('Loss vs K', fontweight = 'bold')
  480. plt.xlim(min(neighbors), max(neighbors))
  481. plt.tight_layout()
  482. plt.show()
  483. K_opt = acc_list.index(max(acc_list))
  484. print('\nOptimal value of K = ', K_opt)
  485. # **K Nearest Neighbor Algorithm**
  486. #
  487. # The classification is done based on the k nearest neighbour algorithm where the euclidian distance is calculated for each input output combination and the classification is done depending on the minimum euclidian distance.
  488. # In[60]:
  489. classifier = KNeighborsClassifier(n_neighbors=K_opt+1)
  490. classifier.fit(xtrain, ytrain)
  491. y_pred = classifier.predict(xtest)
  492. accuracy = acc(ytest, y_pred)*100
  493. print('Accuracy of the training Model : ', round(accuracy, 3), '%')
  494. # **Thi is Too poor accuracy and needs further explortion, i don't know where to start actually.**
  495. # **Display the Performance of the trained model**
  496. #
  497. # A confusion matrix is used to determine the performance of a trained model by mapping the training accuracy for each input and output combination. Ideally it should be a diagonal matrix but due to training uncertainity , the matrix obtained is not a diagonal matrix.
  498. # In[61]:
  499. cm = confusion_matrix(ytest, y_pred, normalize = 'pred')
  500. fig, ax = plt.subplots(figsize=(25,15))
  501. sns.heatmap(cm, annot = True)
  502. plt.xlabel('Predicted Crop', fontsize = 12)
  503. plt.ylabel('Actual Crop', fontsize = 12)
  504. plt.title('Confusion Matrix', fontweight = 'bold', fontsize = 15)
  505. plt.xticks(rotation=90)
  506. plt.yticks(rotation=0)
  507. ax.xaxis.set_ticklabels(classes)
  508. ax.yaxis.set_ticklabels(classes)
  509. plt.show()
  510. # # 3.3 Crop Prediction model Regresion approach
  511. #
  512. # Another important supervised learing alogorithm is the Regression approach by using anaual yield as target variable which is numerical than Items that are categorical.
  513. # In our classification based prediction to the dataset,perfomance obtained is too poor even after incorporating the yield column of orginal dataframe into the analysis (**accuracy become 3.4%**).
  514. #
  515. # let's turn into another supervised alogorithm,regression,now since peritty of having with numerical target variable that is yield. We lend oursveles here to further data processing since we do have a categorical variable, Item column.
  516. #
  517. # Unlike label encoding and One-Hot encoding that respectively experinced value implication and dimenionality problems.
  518. # In[62]:
  519. import warnings
  520. warnings.filterwarnings('ignore')
  521. import pandas as pd
  522. import numpy as np
  523. import matplotlib.pyplot as plt
  524. get_ipython().run_line_magic('matplotlib', 'inline')
  525. import seaborn as sns
  526. from scipy import stats
  527. from sklearn.preprocessing import *
  528. from sklearn. metrics import *
  529. from sklearn.linear_model import LinearRegression, SGDRegressor
  530. from sklearn.ensemble import RandomForestRegressor
  531. from xgboost import XGBClassifier, XGBRegressor
  532. from sklearn.model_selection import train_test_split
  533. from imblearn.datasets import make_imbalance
  534. from category_encoders.target_encoder import TargetEncoder
  535. import statsmodels.api as sm
  536. # In[63]:
  537. df.info()
  538. # For a detail to Label and One Hot encoding read https://www.analyticsvidhya.com/blog/2020/03/one-hot-encoding-vs-label-encoding-using-scikit-learn/
  539. #
  540. # One-Hot encoding is the process of creating dummy variables.
  541. # - One-Hot Encoding results in a Dummy Variable Trap as the outcome of one variable can easily be predicted with the help of the remaining variables.
  542. #
  543. # - Dummy Variable Trap is a scenario in which variables are highly correlated to each other.
  544. #
  545. # - The Dummy Variable Trap leads to the problem known as **multicollinearity**.
  546. #
  547. # - Multicollinearity occurs where there is a dependency between the independent features.
  548. #
  549. # - It is a serious issue in machine learning models like `Linear Regression` and `Logistic Regression`.
  550. #
  551. # So, in order to overcome the problem of multicollinearity, one of the dummy variables has to be dropped. One of the common ways to check for multicollinearity is the Variance Inflation Factor (VIF):
  552. #
  553. # - VIF=1, Very Less Multicollinearity
  554. #
  555. # - VIF<5, Moderate Multicollinearity
  556. #
  557. # - VIF>5, Extreme Multicollinearity (This is what we have to avoid)
  558. # Compute the VIF scores:
  559. # In order not traped by target leakage due to the underlings probablity based target encoding we deploye Target encoder with prior smoothing by Vinícius Trevisan (https://towardsdatascience.com/dealing-with-categorical-variables-by-using-target-encoder-a0f1733a4c69) and https://towardsdatascience.com/categorical-feature-encoding-547707acf4e5
  560. # ### 3.3.1 One Hot Encoding
  561. #
  562. # one-Hot encoding some times refered as dummies
  563. # In[64]:
  564. from pandas import DataFrame,get_dummies
  565. df_com.columns = df_com.columns.to_series().apply(lambda x: x.strip())
  566. data_to_encode = df_com[['Item']]
  567. df_com_dumy = get_dummies(df_com, prefix={k:"dmy_%s"%k for k in data_to_encode},
  568. columns = list(data_to_encode))
  569. df_com_dumy.head (5)
  570. # In[65]:
  571. # Compare sizes
  572. print('Original size:', df_com.shape)
  573. print('One-hot encoded size:', df_com_dumy.shape)
  574. # It is observed that the dataset now changed to a shape of 2790x54 which was 2790x7 in the orginal dataset.
  575. # # 3.3.2 Evaluate Onehot encoding
  576. # Now lets evaluate one-hot encoding using
  577. # - <font color='magneta'>Linear regression</font>(<font color='pureple'>lr</font>)
  578. #
  579. # - <font color='Magneta'>Suport vector Regression</font>,
  580. #
  581. # - (<font color='pureple'>SVR</font>) and
  582. #
  583. # - <font color='Magnea'>Random Forest</font>(<font color='pureple'>RF</font>) algorithm
  584. # Let $X_{oh}$ stands for feature variable affter one-hot encding and $X_t$ for target encoding and the response variable remains constant as it is free from encoding.
  585. # In[66]:
  586. Xoh = df_com_dumy.drop(columns=['Yiled/ha'],axis=1)
  587. y = df_com_dumy['Yiled/ha']
  588. # In[67]:
  589. # convvert dataframe to array to make the ML ease
  590. #array = df_com_dumy.values
  591. #Xoh = array[:,1:54]
  592. #y = array[:,1]
  593. #Xoh.shape
  594. # In[68]:
  595. Xoh_train, Xoh_test, y_train, y_test = train_test_split(Xoh, y, test_size=0.3, random_state=42)
  596. print ("training dataset", Xoh_train,y_train)
  597. print("testing datasdet", Xoh_test,y_test)
  598. # In[69]:
  599. #import libraries
  600. from pandas import Series,DataFrame
  601. from sklearn.preprocessing import OneHotEncoder
  602. from sklearn.linear_model import LinearRegression
  603. #train the model
  604. lr_oh = LinearRegression()
  605. lr_oh.fit(Xoh_train,y_train)
  606. #predict ton the test data
  607. pred_oh =lr_oh.predict(Xoh_test)
  608. # error determination
  609. errors_lr_oh =abs(pred_oh -y_test)
  610. mse =np.mean((pred_oh -y_test)**2)
  611. #print out mean absolute error(mae)
  612. print('Mean Absolute Error(MAE):',round(np.mean(errors_lr_oh),2),'yield/ha')
  613. print('Mean Square Error (MSE):',round(np.mean(mse),2),'yiled/ha')
  614. # An improvement about 25% on MAE (9845.51/38021.27671310749) and 1.8% (57039460.81/3162915966.08407)on MSE obtained
  615. # lets try another meterics for prediction model, i.e., coefficient of determination <font color='Magneat'> $R^2$</font> and <font color='Magneat'>adjusted-$R^2$</font>
  616. # In[70]:
  617. #model score
  618. lr_oh.score(Xoh_test,y_test)
  619. # Determining the performance metrics for a model is ofcourse to perform accuracy evaluation using <font color='blue'> mean average percentage errore</font> (<font color='purple'>MAPE</font> subtracted from 100%
  620. # In[71]:
  621. # calculate MAPE
  622. mape_lr_oh=100*(errors_lr_oh/y_test)
  623. #calculate and display accuracy
  624. accuracy =100-np.mean(mape_lr_oh)
  625. print('Accuracy:',round(accuracy,2),'%')
  626. # In[72]:
  627. _plot=plt.scatter(pred_oh,(pred_oh-y_test),c='b')
  628. plt.hlines(y=0,xmin=-0.4,xmax=3)
  629. plt.title('Residual plot')
  630. # In[73]:
  631. # get importance
  632. from matplotlib import pyplot
  633. importance = lr_oh.coef_
  634. # summarize model importance
  635. for i, v in enumerate(importance):
  636. print('Feature:%0d, score:%.5f'%(i,v))
  637. #plot feature importance
  638. pyplot.bar([x for x in range(len(importance))],importance )
  639. plt.xlabel('Features')
  640. plt.ylabel('features importance')
  641. pyplot.show()
  642. # In[80]:
  643. predictors = df_com_dumy.drop(['Yiled/ha'],axis=1).columns
  644. coef = Series(lr_oh.coef_,predictors).sort_values()
  645. coef.plot(kind='bar',title='Model Coefficients')
  646. # In[ ]:
  647. def one_hot_encoder_one(data,Item,keep_first=True):
  648. oh = OneHotEncoder()
  649. oh_df = pd.DataFrame(oh.fit_transform(df_com[[Item]]).toarray())
  650. oh_df.columns = oh.get_feature_names()
  651. for col in oh_df.columns:
  652. oh_df.rename({col:f'{Item}_'+col.split('_')[1]},axis=1,inplace=True)
  653. new_data = pd.concat([df_com,oh_df],axis=1)
  654. new_data.drop(Item,axis=1,inplace=True)
  655. if keep_first == False:
  656. new_data=new_data.iloc[:,1:]
  657. return new_data
  658. # combine the data and potentially remove one column for auto correlation
  659. # In[ ]:
  660. def one_hot_encoder_two(data,Fetaure,keep_first=True):
  661. one_hot_cols = pd.get_dummies(data[feature])
  662. for col in one_hot_cols.columns:
  663. one_hot_cols.rename({col:f'{Item}_'+col},axis=1,inplace=True)
  664. new_data = pd.concat([df_com,one_hot_cols],axis=1)
  665. new_data.drop(Item,axis=1,inplace=True)
  666. if keep_first == False:
  667. new_data=new_data.iloc[:,1:]
  668. return new_data
  669. # In[ ]:
  670. df_com.head()
  671. # In[ ]:
  672. one_hot_encoder_one(df_com,'Item')
  673. # In[ ]:
  674. stats = df_com['Yiled/ha'].groupby(df_com['Item']).agg(['count', 'mean'])
  675. # In[ ]:
  676. smoothing_factor = 1.0 # The f of the smoothing factor equation
  677. min_samples_leaf = 1 # The k of the smoothing factor equation
  678. prior = df_com['Yiled/ha'].mean()
  679. smoove = 1 / (1 + np.exp(-(stats['count'] - min_samples_leaf) / smoothing_factor))
  680. smoothing = prior * (1 - smoove) + stats['mean'] * smoove
  681. encoded = pd.Series(smoothing, name = 'genre_encoded_complete')
  682. # In[ ]:
  683. from category_encoders import TargetEncoder
  684. encoder = TargetEncoder()
  685. df_com['Item_encoded'] = encoder.fit_transform(df_com['Item'], df_com['Yiled/ha'])
  686. # In[ ]:
  687. df_com['Item_encoded']
  688. # The above target encoding is based on binary classification whiel the dataframe used here is a multiclass problem and must be encodedd using `category_encoders.TargetEncoder` object in this scenario:
  689. # In[ ]:
  690. from category_encoders import TargetEncoder
  691. targets = df_com['Yiled/ha'].unique()
  692. for t in targets:
  693. target_aux = df_com['Yiled/ha'].apply(lambda x: 1 if x == t else 0)
  694. encoder = TargetEncoder()
  695. df_com['Item_encoded_sklearn_target_' + str(t)] = encoder.fit_transform(df_com['Item'], target_aux)
  696. # In[ ]:
  697. te_df=df_com.copy()
  698. for col in te_df.select_dtypes(include='O').columns:
  699. te=TargetEncoder()
  700. te_df[col]=te.fit_transform(te_df[col],te_df['Yiled/ha'])
  701. # In[ ]:
  702. te_df.head()
  703. # Just like label and ordinal encoding, we lose the name of the actual values for each particular feature
  704. # **Building** `target_encoding function`
  705. #
  706. # - Inputs are data, a feature, and the target feature
  707. #
  708. # - A new data frame is created containing each unique value of a feature from the data which is then grouped by it’s mean target value
  709. #
  710. # - An empty dictionary is then created, filled with this data, and mapped to each unique value of the particular feature
  711. #
  712. # - The return value is the data frame with new target encodings in place
  713. # In[ ]:
  714. def target_encoding(data, column, target):
  715. grouped = data[[column,target]].groupby(column,as_index=False).mean()
  716. empty_dict = {}
  717. for i in range(len(grouped)):
  718. empty_dict[grouped.iloc[i,0]]=grouped.iloc[i,1]
  719. data[column]=data[column].map(lambda x: empty_dict[x])
  720. return data
  721. # - Let’s see the same result with the new function
  722. # In[ ]:
  723. te_df=df_com.copy()
  724. for col in te_df.select_dtypes(include='O').columns:
  725. target_encoding(te_df,col,'Yiled/ha')
  726. # - ordinal data
  727. # In[ ]:
  728. df_com.head()
  729. # - New data
  730. # In[ ]:
  731. te_df.head()
  732. # In[ ]:
  733. def reg_model(data):
  734. X = df_com.drop('Yiled/ha',axis=1)
  735. y = df_com['Yiled/ha']
  736. X_tr,X_te,y_tr,y_te = train_test_split(X,y,random_state=14,test_size=0.25)
  737. linreg = LinearRegression()
  738. linreg.fit(X_tr,y_tr)
  739. p = linreg.predict(X_te)
  740. print(f'R-squared: {r2_score(y_te,p)}')
  741. print('-'*20)
  742. print(f'Error: {mean_absolute_error(y_te,p)}')
  743. coefs = pd.DataFrame(linreg.coef_).T
  744. coefs.columns=X.columns
  745. print('-'*20)
  746. return coefs
  747. # In[ ]:
  748. reg_model(te_df)
  749. # ![image-2.png](attachment:image-2.png)
  750. # **2. Crop recomendation Essenble learning**
  751. # credti to `Prakash Kumar.K`
  752. # In[ ]:
  753. import pandas as pd
  754. import pandas_profiling as pp
  755. import numpy as np
  756. import seaborn as sns
  757. import matplotlib.pyplot as plt
  758. from jinja2.utils import escape
  759. import warnings
  760. import os
  761. import plotly.graph_objects as go
  762. import plotly.io as pio
  763. import pickle
  764. from sklearn.utils import resample
  765. # Metrics
  766. from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, auc, roc_curve
  767. # Validation
  768. from sklearn.model_selection import train_test_split, cross_val_score, KFold
  769. from sklearn.pipeline import Pipeline, make_pipeline
  770. # Tuning
  771. from sklearn.model_selection import GridSearchCV
  772. # Feature Extraction
  773. from sklearn.feature_selection import RFE
  774. # Preprocessing
  775. from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer, Binarizer, LabelEncoder
  776. # Models
  777. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
  778. from sklearn.linear_model import LogisticRegression
  779. from sklearn.naive_bayes import GaussianNB
  780. from sklearn.svm import SVC
  781. from sklearn.neighbors import KNeighborsClassifier
  782. from sklearn.tree import DecisionTreeClassifier
  783. # Ensembles
  784. from sklearn.ensemble import RandomForestClassifier
  785. from sklearn.ensemble import BaggingClassifier
  786. from sklearn.ensemble import AdaBoostClassifier
  787. from sklearn.ensemble import GradientBoostingClassifier
  788. from sklearn.ensemble import ExtraTreesClassifier
  789. warnings.filterwarnings('ignore')
  790. # In[ ]:
  791. sns.set_style("whitegrid", {'axes.grid' : False})
  792. pio.templates.default = "plotly_white"
  793. # Analyze Data
  794. def explore_data(df):
  795. print("Number of Instances and Attributes:", df.shape)
  796. print('\n')
  797. print('Dataset columns:',df.columns)
  798. print('\n')
  799. print('Data types of each columns: ', df.info())
  800. # In[ ]:
  801. # Checking for duplicates
  802. def checking_removing_duplicates(df):
  803. count_dups = df.duplicated().sum()
  804. print("Number of Duplicates: ", count_dups)
  805. if count_dups >= 1:
  806. df.drop_duplicates(inplace=True)
  807. print('Duplicate values removed!')
  808. else:
  809. print('No Duplicate values')
  810. # In[ ]:
  811. # Split training and validation set
  812. def read_in_and_split_data(data, target):
  813. X = data.drop(target, axis=1)
  814. y = data[target]
  815. X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, random_state=0)
  816. return X_train, X_test, y_train, y_test
  817. # In[ ]:
  818. # appending Algorithms
  819. def GetModel():
  820. Models = []
  821. Models.append(('LR' , LogisticRegression()))
  822. Models.append(('LDA' , LinearDiscriminantAnalysis()))
  823. Models.append(('KNN' , KNeighborsClassifier()))
  824. Models.append(('CART' , DecisionTreeClassifier()))
  825. Models.append(('NB' , GaussianNB()))
  826. Models.append(('SVM' , SVC(probability=True)))
  827. return Models
  828. # In[ ]:
  829. #appending Algorithms
  830. def ensemblemodels():
  831. ensembles = []
  832. ensembles.append(('AB' , AdaBoostClassifier()))
  833. ensembles.append(('GBM' , GradientBoostingClassifier()))
  834. ensembles.append(('RF' , RandomForestClassifier()))
  835. ensembles.append(( 'Bagging' , BaggingClassifier()))
  836. ensembles.append(('ET', ExtraTreesClassifier()))
  837. return ensembles
  838. # In[ ]:
  839. # Normalized Models
  840. def NormalizedModel(nameOfScaler):
  841. if nameOfScaler == 'standard':
  842. scaler = StandardScaler()
  843. elif nameOfScaler =='minmax':
  844. scaler = MinMaxScaler()
  845. elif nameOfScaler == 'normalizer':
  846. scaler = Normalizer()
  847. elif nameOfScaler == 'binarizer':
  848. scaler = Binarizer()
  849. pipelines = []
  850. pipelines.append((nameOfScaler+'LR' , Pipeline([('Scaler', scaler),('LR' , LogisticRegression())])))
  851. pipelines.append((nameOfScaler+'LDA' , Pipeline([('Scaler', scaler),('LDA' , LinearDiscriminantAnalysis())])))
  852. pipelines.append((nameOfScaler+'KNN' , Pipeline([('Scaler', scaler),('KNN' , KNeighborsClassifier())])))
  853. pipelines.append((nameOfScaler+'CART', Pipeline([('Scaler', scaler),('CART', DecisionTreeClassifier())])))
  854. pipelines.append((nameOfScaler+'NB' , Pipeline([('Scaler', scaler),('NB' , GaussianNB())])))
  855. pipelines.append((nameOfScaler+'SVM' , Pipeline([('Scaler', scaler),('SVM' , SVC())])))
  856. pipelines.append((nameOfScaler+'AB' , Pipeline([('Scaler', scaler),('AB' , AdaBoostClassifier())]) ))
  857. pipelines.append((nameOfScaler+'GBM' , Pipeline([('Scaler', scaler),('GMB' , GradientBoostingClassifier())]) ))
  858. pipelines.append((nameOfScaler+'RF' , Pipeline([('Scaler', scaler),('RF' , RandomForestClassifier())]) ))
  859. pipelines.append((nameOfScaler+'ET' , Pipeline([('Scaler', scaler),('ET' , ExtraTreesClassifier())]) ))
  860. return pipelines
  861. # In[ ]:
  862. # Train model
  863. def fit_model(X_train, y_train,models):
  864. # Test options and evaluation metric
  865. num_folds = 10
  866. scoring = 'accuracy'
  867. results = []
  868. names = []
  869. for name, model in models:
  870. kfold = KFold(n_splits=num_folds, shuffle=True, random_state=0)
  871. cv_results = cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring)
  872. results.append(cv_results)
  873. names.append(name)
  874. msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
  875. print(msg)
  876. return names, results
  877. # In[ ]:
  878. # Save trained model
  879. def save_model(model,filename):
  880. pickle.dump(model, open(filename, 'wb'))
  881. # In[ ]:
  882. # Performance Measure
  883. def classification_metrics(model, conf_matrix):
  884. print(f"Training Accuracy Score: {model.score(X_train, y_train) * 100:.1f}%")
  885. print(f"Validation Accuracy Score: {model.score(X_test, y_test) * 100:.1f}%")
  886. fig,ax = plt.subplots(figsize=(8,6))
  887. sns.heatmap(pd.DataFrame(conf_matrix), annot = True, cmap = 'YlGnBu',fmt = 'g')
  888. ax.xaxis.set_label_position('top')
  889. plt.tight_layout()
  890. plt.title('Confusion Matrix', fontsize=20, y=1.1)
  891. plt.ylabel('Actual label', fontsize=15)
  892. plt.xlabel('Predicted label', fontsize=15)
  893. plt.show()
  894. print(classification_report(y_test, y_pred))
  895. # In[ ]:
  896. # ROC_AUC
  897. def roc_auc(y_test, y_pred):
  898. fpr, tpr, thresholds = roc_curve(y_test, y_pred)
  899. plt.figure(figsize=(8,6))
  900. print(f"roc_auc score: {auc(fpr, tpr)*100:.1f}%")
  901. plt.plot(fpr, tpr, color='orange', label='ROC')
  902. plt.plot([0, 1], [0, 1], color='darkblue', linestyle='--')
  903. plt.xlabel('False Positive Rate',fontsize=12)
  904. plt.ylabel('True Positive Rate', fontsize=12)
  905. plt.title('Receiver Operating Characteristic (ROC) Curve', fontsize=20)
  906. plt.legend()
  907. plt.show()
  908. # In[ ]:
  909. #DataAnalysis
  910. explore_data(df)
  911. # In[ ]:
  912. #Removing_Duplicates
  913. checking_removing_duplicates(df)
  914. # In[ ]:
  915. df.isna().sum()
  916. # In[ ]:
  917. #Removing Outliers outliers
  918. Q1 = df.quantile(0.25)
  919. Q3 = df.quantile(0.75)
  920. IQR = Q3 - Q1
  921. df_out = df[~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]
  922. # In[ ]:
  923. #Training the model
  924. target ='Item'
  925. X_train, X_test, y_train, y_test = read_in_and_split_data(df, target)
  926. models = GetModel()
  927. names,results = fit_model(X_train, y_train,models)
  928. # In[ ]:
  929. #Preprocessing Technique
  930. ScaledModel = NormalizedModel('minmax')
  931. name,results = fit_model(X_train, y_train, ScaledModel)
  932. # In[ ]:
  933. #Saving the model
  934. pipeline = make_pipeline(MinMaxScaler(), GaussianNB())
  935. model = pipeline.fit(X_train, y_train)
  936. y_pred = model.predict(X_test)
  937. conf_matrix = confusion_matrix(y_test,y_pred)
  938. classification_metrics(pipeline, conf_matrix)
  939. # save model
  940. save_model(model, 'model.pkl')
  941. # In[ ]:
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...