-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmlbaseline.py
More file actions
4946 lines (4121 loc) · 197 KB
/
mlbaseline.py
File metadata and controls
4946 lines (4121 loc) · 197 KB
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
# -*- coding: utf-8 -*-
"""mlbaseline.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1T7c2kh_IH8EJcQlEs3h9YBRnKUDEp9V2
# Crop Yield Prediction - ML Baseline
We use WOFOST crop growth indicators, weather variables, geographic information, soil data and remote sensing indicators to predict the yield.
## Google Colab Notes
**To run the script in Google Colab environment**
1. Download the data directory and save it somewhere convenient.
2. Open the notebook using Google Colaboratory.
3. Create a copy of the notebook for yourself.
4. Click connect on the right hand side of the bar below menu items. When you are connected to a machine, you will see a green tick mark and bars showing RAM and disk.
5. Click the folder icon on the left sidebar and click upload. Upload the data files you downloaded. Click *Ok* when you see a warning saying the files will be deleted after the session is disconnected.
6. Use *Runtime* -> *Run before* option to run all cells before **Set Configuration**.
7. Run the remaining cells except **Python Script Main**. The configuration subsection allows you to change configuration and rerun experiments.
## Global Variables and Spark Installation/Initialization
Initialize Spark session and global variables. Package installation is required only in Google Colab.
"""
#%%writefile globals.py
# test_env = 'notebook'
test_env = 'cluster'
# test_env = 'pkg'
# change to False to skip tests
run_tests = False
# NUTS levels
nuts_levels = ['NUTS' + str(i) for i in range(4)]
# country codes
countries = ['BG', 'DE', 'ES', 'FR', 'HU', 'IT', 'NL', 'PL', 'RO']
# debug levels
debug_levels = [i for i in range(5)]
# Keeping these two mappings inside CYPConfiguration leads to SPARK-5063 error
# when lambda functions use them. Therefore, they are defined as globals now.
# crop name to id mapping
crop_id_dict = {
'grain maize': 2,
'sugar beet' : 6,
'sugarbeet' : 6,
'sugarbeets' : 6,
'sugar beets' : 6,
'total potatoes' : 7,
'potatoes' : 7,
'potato' : 7,
'winter wheat' : 90,
'soft wheat' : 90,
'sunflower' : 93,
'spring barley' : 95,
}
# crop id to name mapping
crop_name_dict = {
2 : 'grain maize',
6 : 'sugarbeet',
7 : 'potatoes',
90 : 'soft wheat',
93 : 'sunflower',
95 : 'spring barley',
}
import pyspark
from pyspark.sql import functions as SparkF
from pyspark.sql import types as SparkT
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
SparkContext.setSystemProperty('spark.executor.memory', '12g')
SparkContext.setSystemProperty('spark.driver.memory', '6g')
spark = SparkSession.builder.master("local[*]").getOrCreate()
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)
"""## Utility Functions"""
#%%writefile util.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# crop name and id mappings
def cropNameToID(crop_id_dict, crop):
"""
Return id of given crop. Relies on crop_id_dict.
Return 0 if crop name is not in the dictionary.
"""
crop_lcase = crop.lower()
try:
crop_id = crop_id_dict[crop_lcase]
except KeyError as e:
crop_id = 0
return crop_id
def cropIDToName(crop_name_dict, crop_id):
"""
Return crop name for given crop ID. Relies on crop_name_dict.
Return 'NA' if crop id is not found in the dictionary.
"""
try:
crop_name = crop_name_dict[crop_id]
except KeyError as e:
crop_name = 'NA'
return crop_name
def getYear(date_str):
"""Extract year from date in yyyyMMdd or dd/MM/yyyy format."""
return SparkF.when(SparkF.length(date_str) == 8,
SparkF.year(SparkF.to_date(date_str, 'yyyyMMdd')))\
.otherwise(SparkF.year(SparkF.to_date(date_str, 'dd/MM/yyyy')))
def getMonth(date_str):
"""Extract month from date in yyyyMMdd or dd/MM/yyyy format."""
return SparkF.when(SparkF.length(date_str) == 8,
SparkF.month(SparkF.to_date(date_str, 'yyyyMMdd')))\
.otherwise(SparkF.month(SparkF.to_date(date_str, 'dd/MM/yyyy')))
def getDay(date_str):
"""Extract day from date in yyyyMMdd or dd/MM/yyyy format."""
return SparkF.when(SparkF.length(date_str) == 8,
SparkF.dayofmonth(SparkF.to_date(date_str, 'yyyyMMdd')))\
.otherwise(SparkF.dayofmonth(SparkF.to_date(date_str, 'dd/MM/yyyy')))
# 1-10: Dekad 1
# 11-20: Dekad 2
# > 20 : Dekad 3
def getDekad(date_str):
"""Extract dekad from date in YYYYMMDD format."""
month = getMonth(date_str)
day = getDay(date_str)
return SparkF.when(day < 30, (month - 1)* 3 +
SparkF.ceil(day/10)).otherwise((month - 1) * 3 + 3)
# Machine Learning Utility Functions
# This definition is from the suggested answer to:
# https://stats.stackexchange.com/questions/58391/mean-absolute-percentage-error-mape-in-scikit-learn/294069#294069
def mean_absolute_percentage_error(Y_true, Y_pred):
"""Mean Absolute Percentage Error"""
Y_true, Y_pred = np.array(Y_true), np.array(Y_pred)
return np.mean(np.abs((Y_true - Y_pred) / Y_true)) * 100
def printFeatures(features, indices, log_fh=None):
"""Print names of features in groups of 5"""
num_features = len(indices)
groups = int(num_features/5) + 1
feature_str = '\n'
for g in range(groups):
group_start = g * 5
group_end = (g + 1) * 5
if (group_end > num_features):
group_end = num_features
group_indices = indices[group_start:group_end]
for idx in group_indices:
if (idx == group_indices[-1]):
feature_str += str(idx+1) + ': ' + features[idx]
else:
feature_str += str(idx+1) + ': ' + features[idx] + ', '
feature_str += '\n'
print(feature_str)
if (log_fh is not None):
log_fh.write(feature_str)
def getPredictionScores(Y_true, Y_predicted, metrics):
"""Get values of metrics for given Y_predicted and Y_true"""
pred_scores = {}
for met in metrics:
score_function = metrics[met]
met_score = score_function(Y_true, Y_predicted)
# for RMSE, score_function is mean_squared_error, take square root
# normalize RMSE
if (met == 'RMSE'):
met_score = np.round(100*np.sqrt(met_score)/np.mean(Y_true), 2)
pred_scores['NRMSE'] = met_score
# normalize mean absolute errors except MAPE which is already a percentage
elif ((met == 'MAE') or (met == 'MdAE')):
met_score = np.round(100*met_score/np.mean(Y_true), 2)
pred_scores['N' + met] = met_score
# MAPE, R2, ... : no postprocessing
else:
met_score = np.round(met_score, 2)
pred_scores[met] = met_score
return pred_scores
def getFilename(crop, country, yield_trend,
early_season, early_season_end, nuts_level=None):
"""Get filename based on input arguments"""
suffix = crop.replace(' ', '_')
suffix += '_' + country
if (nuts_level is not None):
suffix += '_' + nuts_level
if (yield_trend):
suffix += '_trend'
else:
suffix += '_notrend'
if (early_season):
suffix += '_early' + str(early_season_end)
return suffix
def getLogFilename(crop, country, yield_trend,
early_season, early_season_end):
"""Get filename for experiment log"""
log_file = getFilename(crop, country, yield_trend,
early_season, early_season_end)
return log_file + '.log'
def getFeatureFilename(crop, country, yield_trend,
early_season, early_season_end):
"""Get unique filename for features"""
feature_file = 'ft_'
suffix = getFilename(crop, country, yield_trend, early_season, early_season_end)
feature_file += suffix
return feature_file
def getPredictionFilename(crop, country, nuts_level, yield_trend,
early_season, early_season_end):
"""Get unique filename for predictions"""
pred_file = 'pred_'
suffix = getFilename(crop, country, yield_trend,
early_season, early_season_end, nuts_level)
pred_file += suffix
return pred_file
def plotTrend(years, actual_values, trend_values, trend_label):
"""Plot a linear trend and scatter plot of actual values"""
plt.scatter(years, actual_values, color="blue", marker="o")
plt.plot(years, trend_values, '--')
plt.xticks(np.arange(years[0], years[-1] + 1, step=len(years)/5))
ax = plt.axes()
plt.xlabel("YEAR")
plt.ylabel(trend_label)
plt.title(trend_label + ' Trend by YEAR')
plt.show()
def plotTrueVSPredicted(actual, predicted):
"""Plot actual and predicted values"""
fig, ax = plt.subplots()
ax.scatter(np.asarray(actual), predicted)
ax.plot([actual.min(), actual.max()], [actual.min(), actual.max()], 'k--', lw=4)
ax.set_xlabel('Actual')
ax.set_ylabel('Predicted')
plt.show()
"""## Configuration"""
#%%writefile config.py
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.svm import SVR
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import mutual_info_regression
from sklearn.feature_selection import SelectFromModel
from sklearn.feature_selection import RFE
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import r2_score
from sklearn.metrics import explained_variance_score
from sklearn.metrics import median_absolute_error
class CYPConfiguration:
def __init__(self, crop_name='potatoes', country_code='NL', season_cross='N'):
self.config = {
'crop_name' : crop_name,
'crop_id' : cropNameToID(crop_id_dict, crop_name),
'season_crosses_calendar_year' : season_cross,
'country_code' : country_code,
'nuts_level' : 'NUTS2',
'data_sources' : [ 'WOFOST', 'METEO_DAILY', 'SOIL', 'YIELD' ],
'use_yield_trend' : 'N',
'predict_yield_residuals' : 'N',
'find_optimal_trend_window' : 'N',
# set it to a list with one entry for fixed window
'trend_windows' : [5, 7, 10],
'use_centroids' : 'N',
'use_remote_sensing' : 'Y',
'early_season_prediction' : 'N',
'early_season_end_dekad' : 0,
'data_path' : '.',
'output_path' : '.',
'save_features' : 'N',
'use_saved_features' : 'N',
'save_predictions' : 'Y',
'use_saved_predictions' : 'N',
'compare_with_mcyfs' : 'N',
'debug_level' : 0,
}
# Description of configuration parameters
# This should be in sync with config above
self.config_desc = {
'crop_name' : 'Crop name',
'crop_id' : 'Crop ID',
'season_crosses_calendar_year' : 'Crop growing season crosses calendar year boundary',
'country_code' : 'Country code (e.g. NL)',
'nuts_level' : 'NUTS level for yield prediction',
'data_sources' : 'Input data sources',
'use_yield_trend' : 'Estimate and use yield trend',
'predict_yield_residuals' : 'Predict yield residuals instead of full yield',
'find_optimal_trend_window' : 'Find optimal trend window',
'trend_windows' : 'List of trend window lengths (number of years)',
'use_centroids' : 'Use centroid coordinates and distance to coast',
'use_remote_sensing' : 'Use remote sensing data (FAPAR)',
'early_season_prediction' : 'Predict yield early in the season',
'early_season_end_dekad' : 'Early season end dekad relative to harvest',
'data_path' : 'Path to all input data. Default is current directory.',
'output_path' : 'Path to all output files. Default is current directory.',
'save_features' : 'Save features to a CSV file',
'use_saved_features' : 'Use features from a CSV file',
'save_predictions' : 'Save predictions to a CSV file',
'use_saved_predictions' : 'Use predictions from a CSV file',
'compare_with_mcyfs' : 'Compare predictions with MARS Crop Yield Forecasting System',
'debug_level' : 'Debug level to control amount of debug information',
}
########### Machine learning configuration ###########
# test fraction
self.test_fraction = 0.3
# scaler
self.scaler = StandardScaler()
# Feature selection algorithms. Initialized in getFeatureSelectors().
self.feature_selectors = {}
# prediction algorithms
self.estimators = {
# linear model
'Ridge' : {
'estimator' : Ridge(alpha=1, random_state=42, max_iter=1000,
copy_X=True, fit_intercept=True),
'fs_param_grid' : dict(estimator__alpha=[1e-1]),
'param_grid' : dict(estimator__alpha=[1e-5, 1e-2, 1e-1, 0.5, 1, 5, 10])
},
'KNN' : {
'estimator' : KNeighborsRegressor(weights='distance'),
'fs_param_grid' : dict(estimator__n_neighbors=[5]),
'param_grid' : dict(estimator__n_neighbors=[3, 5, 7, 9])
},
# SVM regression
'SVR' : {
'estimator' : SVR(kernel='rbf', gamma='scale', max_iter=-1,
shrinking=True, tol=0.001),
'fs_param_grid' : dict(estimator__C=[10.0],
estimator__epsilon=[0.5]),
'param_grid' : dict(estimator__C=[1e-1, 5e-1, 1.0, 5.0, 10.0, 50.0, 100.0, 200.0],
estimator__epsilon=[1e-2, 1e-1, 0.5, 1.0, 5.0]),
},
# random forest
#'RF' : {
# 'estimator' : RandomForestRegressor(bootstrap=True, random_state=42,
# oob_score=True, min_samples_leaf=5),
# 'fs_param_grid' : dict(estimator__max_depth=[7],
# estimator__n_estimators=[100]),
# 'param_grid' : dict(estimator__max_depth=[5, 7],
# estimator__n_estimators=[100, 500])
#},
# extra randomized trees
#'ERT' : {
# 'estimator' : ExtraTreesRegressor(bootstrap=True, random_state=42,
# oob_score=True, min_samples_leaf=5),
# 'fs_param_grid' : dict(estimator__max_depth=[7],
# estimator__n_estimators=[100]),
# 'param_grid' : dict(estimator__max_depth=[5, 7],
# estimator__n_estimators=[100, 500])
#},
# gradient boosted decision trees
'GBDT' : {
'estimator' : GradientBoostingRegressor(learning_rate=0.01,
subsample=0.8, loss='huber',
min_samples_leaf=5,
random_state=42),
'fs_param_grid' : dict(estimator__max_depth=[5],
estimator__n_estimators=[100]),
'param_grid' : dict(estimator__max_depth=[5, 10, 15],
estimator__n_estimators=[100, 500])
},
#'MLP' : {
# 'estimator' : MLPRegressor(batch_size='auto', learning_rate='adaptive',
# solver='sgd', activation='relu',
# learning_rate_init=0.01, power_t=0.5,
# max_iter=1000, shuffle=True,
# random_state=42, tol=0.001,
# verbose=False, warm_start=False,
# momentum=0.9, nesterovs_momentum=True,
# early_stopping=True,
# validation_fraction=0.4, beta_1=0.9,
# beta_2=0.999, epsilon=1e-08),
# 'fs_param_grid' : dict(estimator__hidden_layer_sizes=[(10, 10), (15,15)],
# estimator__alpha=[0.2, 0.3]),
# 'param_grid' : dict(estimator__hidden_layer_sizes=[(10, 10), (15, 15), (20, 20)],
# estimator__alpha=[0.1, 0.2, 0.3]),
#},
}
# k-fold validation metric for feature selection
self.fs_cv_metric = 'neg_mean_squared_error'
# k-fold validation metric for training
self.est_cv_metric = 'neg_mean_squared_error'
# Performance evaluation metrics:
# sklearn supports these metrics:
# 'explained_variance', 'max_error', 'neg_mean_absolute_error
# 'neg_mean_squared_error', 'neg_root_mean_squared_error'
# 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2'
self.eval_metrics = {
# EXP_VAR (y_true, y_obs) = 1 - ( var(y_true - y_obs) / var (y_true) )
#'EXP_VAR' : explained_variance_score,
# MAE (y_true, y_obs) = ( 1 / n ) * sum_i-n ( | y_true_i - y_obs_i | )
'MAE' : mean_absolute_error,
# MdAE (y_true, y_obs) = median ( | y_true_1 - y_obs_1 |, | y_true_2 - y_obs_2 |, ... )
#'MdAE' : median_absolute_error,
# MAPE (y_true, y_obs) = ( 1 / n ) * sum_i-n ( ( y_true_i - y_obs_i ) / y_true_i )
'MAPE' : mean_absolute_percentage_error,
# MSE (y_true, y_obs) = ( 1 / n ) * sum_i-n ( y_true_i - y_obs_i )^2
'RMSE' : mean_squared_error,
# R2 (y_true, y_obs) = 1 - ( ( sum_i-n ( y_true_i - y_obs_i )^2 )
# / sum_i-n ( y_true_i - mean(y_true) )^2)
'R2' : r2_score,
}
########### Setters and getters ###########
def setCropName(self, crop_name):
"""Set the crop name"""
crop = crop_name.lower()
assert crop in crop_id_dict
self.config['crop_name'] = crop
self.config['crop_id'] = cropNameToID(crop_id_dict, crop)
def getCropName(self):
"""Return the crop name"""
return self.config['crop_name']
def setCropID(self, crop_id):
"""Set the crop ID"""
assert crop_id in crop_name_dict
self.config['crop_id'] = crop_id
self.config['crop_name'] = cropIDToName(crop_name_dict, crop_id)
def getCropID(self):
"""Return the crop ID"""
return self.config['crop_id']
def setSeasonCrossesCalendarYear(self, season_crosses):
"""Set whether the season crosses calendar year boundary"""
scross = season_crosses.upper()
assert scross in ['Y', 'N']
self.config['season_crosses_calendar_year'] = scross
def seasonCrossesCalendarYear(self):
"""Return whether the season crosses calendar year boundary"""
return (self.config['season_crosses_calendar_year'] == 'Y')
def setCountryCode(self, country_code):
"""Set the country code"""
if (country_code is None):
self.config['country_code'] = None
else:
ccode = country_code.upper()
assert len(ccode) == 2
assert ccode in countries
self.config['country_code'] = ccode
def getCountryCode(self):
"""Return the country code"""
return self.config['country_code']
def setNUTSLevel(self, nuts_level):
"""Set the NUTS level"""
nuts = nuts_level.upper()
assert nuts in nuts_levels
self.config['nuts_level'] = nuts
def getNUTSLevel(self):
"""Return the NUTS level"""
return self.config['nuts_level']
def setDataSources(self, data_sources):
"""Get the data sources"""
# TODO: some validation
self.config['data_sources'] = data_sources
def updateDataSources(self, data_src, include_src, nuts_level=None):
"""add or remove data_src from data sources"""
src_nuts = self.getNUTSLevel()
if (nuts_level is not None):
src_nuts = nuts_level
data_sources = self.config['data_sources']
# no update required
if (((include_src == 'Y') and (data_src in data_sources)) or
((include_src == 'N') and (data_src not in data_sources))):
return
if (include_src == 'Y'):
if (isinstance(data_sources, dict)):
data_sources[data_src] = src_nuts
else:
data_sources.append(data_src)
else:
if (isinstance(data_sources, dict)):
del data_sources[data_src]
else:
data_sources.remove(data_src)
self.config['data_sources'] = data_sources
def getDataSources(self):
"""Return the data sources"""
return self.config['data_sources']
def setUseYieldTrend(self, use_trend):
"""Set whether to use yield trend"""
use_yt = use_trend.upper()
assert use_yt in ['Y', 'N']
self.config['use_yield_trend'] = use_yt
def useYieldTrend(self):
"""Return whether to use yield trend"""
return (self.config['use_yield_trend'] == 'Y')
def setPredictYieldResiduals(self, pred_res):
"""Set whether to use predict yield residuals"""
pred_yres = pred_res.upper()
assert pred_yres in ['Y', 'N']
self.config['predict_yield_residuals'] = pred_yres
def predictYieldResiduals(self):
"""Return whether to use predict yield residuals"""
return (self.config['predict_yield_residuals'] == 'Y')
def setFindOptimalTrendWindow(self, find_opt):
"""Set whether to find optimal trend window for each year"""
find_otw = find_opt.upper()
assert find_otw in ['Y', 'N']
self.config['find_optimal_trend_window'] = find_otw
def findOptimalTrendWindow(self):
"""Return whether to find optimal trend window for each year"""
return (self.config['find_optimal_trend_window'] == 'Y')
def setTrendWindows(self, trend_windows):
"""Set trend window lengths (years)"""
assert isinstance(trend_windows, list)
assert len(trend_windows) > 0
# trend windows less than 2 years do not make sense
for tw in trend_windows:
assert tw > 2
self.config['trend_windows'] = trend_windows
def getTrendWindows(self):
"""Return trend window lengths (years)"""
return self.config['trend_windows']
def setUseCentroids(self, use_centroids):
"""Set whether to use centroid coordinates and distance to coast"""
use_ct = use_centroids.upper()
assert use_ct in ['Y', 'N']
self.config['use_centroids'] = use_ct
self.updateDataSources('CENTROIDS', use_ct)
def useCentroids(self):
"""Return whether to use centroid coordinates and distance to coast"""
return (self.config['use_centroids'] == 'Y')
def setUseRemoteSensing(self, use_remote_sensing):
"""Set whether to use remote sensing data"""
use_rs = use_remote_sensing.upper()
assert use_rs in ['Y', 'N']
self.config['use_remote_sensing'] = use_rs
self.updateDataSources('REMOTE_SENSING', use_rs, 'NUTS2')
def useRemoteSensing(self):
"""Return whether to use remote sensing data"""
return (self.config['use_remote_sensing'] == 'Y')
def setEarlySeasonPrediction(self, early_season):
"""Set whether to do early season prediction"""
ep = early_season.upper()
assert ep in ['Y', 'N']
self.config['early_season_prediction'] = ep
def earlySeasonPrediction(self):
"""Return whether to do early season prediction"""
return (self.config['early_season_prediction'] == 'Y')
def setEarlySeasonEndDekad(self, end_dekad):
"""Set early season prediction dekad"""
dekads_range = [dek for dek in range(1, 37)]
assert end_dekad in dekads_range
self.config['early_season_end_dekad'] = end_dekad
def getEarlySeasonEndDekad(self):
"""Return early season prediction dekad"""
return self.config['early_season_end_dekad']
def setDataPath(self, data_path):
"""Set the data path"""
# TODO: some validation
self.config['data_path'] = data_path
def getDataPath(self):
"""Return the data path"""
return self.config['data_path']
def setOutputPath(self, out_path):
"""Set the path to output files. TODO: some validation."""
self.config['output_path'] = out_path
def getOutputPath(self):
"""Return the path to output files."""
return self.config['output_path']
def setSaveFeatures(self, save_ft):
"""Set whether to save features in a CSV file"""
sft = save_ft.upper()
assert sft in ['Y', 'N']
self.config['save_features'] = sft
def saveFeatures(self):
"""Return whether to save features in a CSV file"""
return (self.config['save_features'] == 'Y')
def setUseSavedFeatures(self, use_saved):
"""Set whether to use features from CSV file"""
saved = use_saved.upper()
assert saved in ['Y', 'N']
self.config['use_saved_features'] = saved
def useSavedFeatures(self):
"""Return whether to use to use features from CSV file"""
return (self.config['use_saved_features'] == 'Y')
def setSavePredictions(self, save_pred):
"""Set whether to save predictions in a CSV file"""
spd = save_pred.upper()
assert spd in ['Y', 'N']
self.config['save_predictions'] = spd
def savePredictions(self):
"""Return whether to save predictions in a CSV file"""
return (self.config['save_predictions'] == 'Y')
def setUseSavedPredictions(self, use_saved):
"""Set whether to use predictions from CSV file"""
saved = use_saved.upper()
assert saved in ['Y', 'N']
self.config['use_saved_predictions'] = saved
def useSavedPredictions(self):
"""Return whether to use to use predictions from CSV file"""
return (self.config['use_saved_predictions'] == 'Y')
def setCompareWithMCYFS(self, compare_mcyfs):
"""Set whether to compare predictions with MCYFS"""
comp_mcyfs = compare_mcyfs.upper()
assert comp_mcyfs in ['Y', 'N']
self.config['compare_with_mcyfs'] = comp_mcyfs
def compareWithMCYFS(self):
"""Return whether to compare predictions with MCYFS"""
return (self.config['compare_with_mcyfs'] == 'Y')
def setDebugLevel(self, debug_level):
"""Set the debug level"""
assert debug_level in debug_levels
self.config['debug_level'] = debug_level
def getDebugLevel(self):
"""Return the debug level"""
return self.config['debug_level']
def updateConfiguration(self, config_update):
"""Update configuration"""
assert isinstance(config_update, dict)
for k in config_update:
assert k in self.config
# keys that need special handling
special_cases = {
'crop_name' : self.setCropName,
'crop_id' : self.setCropID,
'use_centroids' : self.setUseCentroids,
'use_remote_sensing' : self.setUseRemoteSensing,
}
if (k not in special_cases):
self.config[k] = config_update[k]
continue
# special case
special_cases[k](config_update[k])
def printConfig(self, log_fh):
"""Print current configuration and write configuration to log file."""
config_str = '\nCurrent ML Baseline Configuration'
config_str += '\n--------------------------------'
for k in self.config:
if (isinstance(self.config[k], dict)):
conf_keys = list(self.config[k].keys())
if (not isinstance(conf_keys[0], str)):
conf_keys = [str(k) for k in conf_keys]
config_str += '\n' + self.config_desc[k] + ': ' + ', '.join(conf_keys)
elif (isinstance(self.config[k], list)):
conf_vals = self.config[k]
if (not isinstance(conf_vals[0], str)):
conf_vals = [str(k) for k in conf_vals]
config_str += '\n' + self.config_desc[k] + ': ' + ', '.join(conf_vals)
else:
conf_val = self.config[k]
if (not isinstance(conf_val, str)):
conf_val = str(conf_val)
config_str += '\n' + self.config_desc[k] + ': ' + conf_val
config_str += '\n'
log_fh.write(config_str + '\n')
print(config_str)
# Machine learning configuration
def getTestFraction(self):
"""Return test set fraction (of full dataset)"""
return self.test_fraction
def setTestFraction(self, test_fraction):
"""Set test set fraction (of full dataset)"""
assert (test_fraction > 0.0 and test_fraction < 1.0)
self.test_fraction = test_fraction
def getFeatureScaler(self):
"""Return feature scaling method"""
return self.scaler
def setFeatureScaler(self, scaler):
"""Set feature scaling method"""
assert (isinstance(scaler, MinMaxScaler) or isinstance(scaler, StandardScaler))
self.scaler = scaler
def getFeatureSelectionCVMetric(self):
"""Return metric for feature selection using K-fold validation"""
return self.fs_cv_metric
def setFeatureSelectionCVMetric(self, fs_metric):
"""Return metric for feature selection using K-fold validation"""
assert fs_metric in self.eval_metrics
self.fs_cv_metric = fs_metric
def getAlgorithmTrainingCVMetric(self):
"""Return metric for hyperparameter optimization using K-fold validation"""
return self.est_cv_metric
def setFeatureSelectionCVMetric(self, est_metric):
"""Return metric for hyperparameter optimization using K-fold validation"""
assert est_metric in self.eval_metrics
self.est_cv_metric = est_metric
def getFeatureSelectors(self, X_train, Y_train, num_features,
custom_cv):
"""Feature selection methods"""
# already defined?
if (len(self.feature_selectors) > 0):
return self.feature_selectors
# NOTE: X_train, Y_train, custom_cv
# are for optimizing hyperparamters of rf and lasso used
# to define feature selectors. At the moment, we don't
# optimize hyperparameters.
# Early season prediction can have less than 10 features
min_features = 10 if num_features > 10 else num_features
max_features = [min_features]
if (num_features > 15):
max_features.append(15)
if (num_features > 20):
max_features.append(20)
use_yield_trend = self.useYieldTrend()
if ((num_features > 25) and (use_yield_trend)):
max_features.append(25)
rf = RandomForestRegressor(n_estimators=100, max_depth=5,
bootstrap=True, random_state=42,
oob_score=True, min_samples_leaf=5)
lasso = Lasso(alpha=0.1, copy_X=True, fit_intercept=True,
random_state=42,selection='cyclic', tol=0.01)
self.feature_selectors = {
# random forest
'random_forest' : {
'selector' : SelectFromModel(rf, threshold='median'),
'param_grid' : dict(selector__max_features=max_features)
},
# recursive feature elimination using Lasso
'RFE_Lasso' : {
'selector' : RFE(lasso),
'param_grid' : dict(selector__n_features_to_select=max_features)
},
# NOTE: Mutual info raises an error when used with spark parallel backend.
# univariate feature selection
# 'mutual_info' : {
# 'selector' : SelectKBest(mutual_info_regression),
# 'param_grid' : dict(selector__k=max_features)
# },
}
return self.feature_selectors
def setFeatureSelectors(self, ft_sel):
"""Set feature selection algorithms"""
assert isinstance(ft_sel, dict)
assert len(ft_sel) > 0
for sel in ft_sel:
assert isinstance(sel, dict)
assert 'selector' in sel
assert 'param_grid' in sel
# add cases if other feature selection methods are used
assert (isinstance(sel['selector'], SelectKBest) or
isinstance(sel['selector'], SelectFromModel) or
isinstance(sel['selector'], RFE))
assert isinstance(sel['param_grid'], dict)
self.feature_selectors = ft_sel
def getEstimators(self):
"""Return machine learning algorithms for prediction"""
return self.estimators
def setEstimators(self, estimators):
"""Set machine learning algorithms for prediction"""
assert isinstance(estimators, dict)
assert len(estimators) > 0
for est in estimators:
assert isinstance(est, dict)
assert 'estimator' in est
assert 'param_grid' in est
assert 'fs_param_grid' in est
assert isinstance(est['param_grid'], dict)
assert isinstance(est['fs_param_grid'], dict)
self.estimators = estimators
def getEvaluationMetrics(self):
"""Return metrics to evaluate predictions of algorithms"""
return self.eval_metrics
def setEvaluationMetrics(self, metrics):
assert isinstance(metrics, dict)
self.eval_metrics = metrics
"""## Workflow
### Data Loading and Preprocessing
#### Data Loader Class
"""
#%%writefile data_loading.py
class CYPDataLoader:
def __init__(self, spark, cyp_config):
self.spark = spark
self.data_path = cyp_config.getDataPath()
self.country_code = cyp_config.getCountryCode()
self.nuts_level = cyp_config.getNUTSLevel()
self.data_sources = cyp_config.getDataSources()
self.verbose = cyp_config.getDebugLevel()
self.data_dfs = {}
def loadFromCSVFile(self, data_path, src, nuts, country_code):
"""
The implied filename for each source is:
<data_source>_<nuts_level>_<country_code>.csv
Examples: CENTROIDS_NUTS2_NL.csv, WOFOST_NUTS2_NL.csv.
Schema is inferred from the file. We might want to specify the schema at some point.
"""
if (country_code is not None):
datafile = data_path + '/' + src + '_' + nuts + '_' + country_code + '.csv'
else:
datafile = data_path + '/' + src + '_' + nuts + '.csv'
if (self.verbose > 1):
print('Data file name', '"' + datafile + '"')
df = self.spark.read.csv(datafile, header = True, inferSchema = True)
return df
def loadData(self, src, nuts_level):
"""
Load data for a specific data source.
nuts_level may one level or a list of levels.
"""
data_path = self.data_path
country_code = self.country_code
assert src in self.data_sources
if (isinstance(nuts_level, list)):
src_dfs = []
for nuts in nuts_level:
df = self.loadFromCSVFile(data_path, src, nuts, country_code)
src_dfs.append(df)
elif (isinstance(nuts_level, str)):
src_dfs = self.loadFromCSVFile(data_path, src, nuts_level, country_code)
else:
src_dfs = None
return src_dfs
def loadAllData(self):
"""
NOT SUPPORTED:
1. Schema is not defined.
2. Loading data for multiple countries.
3. Loading data from folders.
Ioannis: Spark has a nice way of loading several files from a folder,
and associating the file name on each record, using the function
input_file_name. This allows to extract medatada from the path
into the dataframe. In your case it could be the country name, etc.
"""
data_dfs = {}
for src in self.data_sources:
nuts_level = self.nuts_level
if (isinstance(self.data_sources, dict)):
nuts_level = self.data_sources[src]
# REMOTE_SENSING data is at NUTS2. If nuts_level is None, leave as is.
elif ((src == 'REMOTE_SENSING') and (nuts_level is not None)):
nuts_level = 'NUTS2'
if ('METEO' in src):
data_dfs['METEO'] = self.loadData(src, nuts_level)
else:
data_dfs[src] = self.loadData(src, nuts_level)
if (self.verbose > 1):
data_sources_str = ''
for src in data_dfs:
data_sources_str = data_sources_str + src + ', '
# remove the comma and space from the end
print('Loaded data:', data_sources_str[:-2])
print('\n')
return data_dfs
"""#### Data Preprocessor Class"""
#%%writefile data_preprocessing.py
from pyspark.sql import Window
class CYPDataPreprocessor:
def __init__(self, spark, cyp_config):
self.spark = spark
self.verbose = cyp_config.getDebugLevel()