-
Notifications
You must be signed in to change notification settings - Fork 6
/
master.py
executable file
·267 lines (222 loc) · 11 KB
/
master.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
"""
- loads the survey data (already preprocessed)
- donwloads the relevant satellite images
- extracts the features with a pre-trained net
- trains a regression model to predict food insecurity
"""
import os
import sys
import pandas as pd
import numpy as np
try:
os.chdir('scripts')
except FileNotFoundError:
pass
sys.path.append(os.path.join("..", "Src"))
from base_layer import BaseLayer
from osm import OSM_extractor
from utils import boundaries, points_to_polygon, get_config_db, get_config_file, write_scores_to_file, write_scores_to_db
def run(file, id=None):
# ----------------- #
# SETUP #############
# ----------------- #
if id is None:
config = get_config_file(file)
else:
config, engine = get_config_db(id)
for d in ['../Data/Features', '../Data/Geofiles/OSM', '../Data/Geofiles/nightlights', '../Data/Results']:
if not os.path.exists(d):
os.makedirs(d)
# --------------------- #
# Setting up playground #
# --------------------- #
assert (os.path.exists(config['dataset_filename'])
), "ups, dataset specified not found: "+config['dataset_filename']
data = pd.read_csv(config['dataset_filename'])
print(str(np.datetime64('now')), 'INFO: original dataset lenght: ', data.shape[0])
data['gpsLongitude'] = np.round(data['gpsLongitude'], 5)
data['gpsLatitude'] = np.round(data['gpsLatitude'], 5)
# avoid duplicates
data = data[['gpsLongitude', 'gpsLatitude', config['indicator']]].groupby(['gpsLongitude', 'gpsLatitude']).mean()
# base layer
assert (os.path.exists(config['base_raster'])
), "ups, raster specified not found: " + config['base_raster']
GRID = BaseLayer(config['base_raster'], data.index.get_level_values('gpsLongitude'), data.index.get_level_values('gpsLatitude'))
# TODO: we should enforce the most accurate i and j when training, i.e. aggregate = 1?
# Get Polygon Geojson of the boundaries
# TODO: maybe go into BaseLayer class?
minlat, maxlat, minlon, maxlon = boundaries(GRID.lat, GRID.lon, buffer=0.05)
area = points_to_polygon(minlon, minlat, maxlon, maxlat)
print(str(np.datetime64('now')), "INFO: Number of clusters: {} ".format(len(data)))
pipeline = 'evaluation'
# ------------------------------- #
# get features from Google images #
# ------------------------------- #
if config['satellite_config']['satellite_images'] in ['Y', 'G']:
features_path = "../Data/Features/features_Google_id_{}_{}.csv".format(id, pipeline)
data_path = "../Data/Satellite/"
from google_images import GoogleImages
if os.path.exists(features_path):
print('INFO: already scored.')
features = pd.read_csv(
features_path.format(id, pipeline),
index_col=['gpsLongitude', 'gpsLatitude'],
float_precision='round_trip')
else:
gimages = GoogleImages(data_path)
# download the images from the relevant API
gimages.download(GRID.lon, GRID.lat, step=config['satellite_config']['satellite_step'])
# extract the features
features = pd.DataFrame(gimages.featurize(GRID.lon, GRID.lat, step=config['satellite_config']['satellite_step']), index=data.index)
features.columns = [str(col) + '_Google' for col in features.columns]
features.to_csv(features_path)
data = data.join(features)
print('INFO: features extracted from Google satellite images')
# --------------------------------- #
# get features from Sentinel images #
# --------------------------------- #
if config['satellite_config']['satellite_images'] in ['Y','S']:
features_path = "../Data/Features/features_Sentinel_id_{}_{}.csv".format(id, pipeline)
data_path = "../Data/Satellite/"
start_date = config["satellite_config"]["start_date"]
end_date = config["satellite_config"]["end_date"]
from sentinel_images import SentinelImages
if os.path.exists(features_path):
print('INFO: already scored.')
features = pd.read_csv(
features_path.format(id, pipeline),
index_col=['gpsLongitude', 'gpsLatitude'],
float_precision='round_trip')
else:
simages = SentinelImages(data_path)
# download the images from the relevant API
simages.download(GRID.lon, GRID.lat, start_date, end_date)
print('INFO: scoring ...')
# extract the features
print('INFO: extractor instantiated.')
features = pd.DataFrame(simages.featurize(GRID.lon, GRID.lat, start_date, end_date), index=data.index)
features.columns = [str(col) + '_Sentinel' for col in features.columns]
features.to_csv(features_path)
data = data.join(features)
print('INFO: features extracted from Sentinel images')
# --------------- #
# add nightlights #
# --------------- #
from nightlights import Nightlights
nlights = Nightlights('../Data/Geofiles/')
nlights.download(area, config['nightlights_date']['start'], config['nightlights_date']['end'])
features = pd.DataFrame(nlights.featurize(GRID.lon, GRID.lat), columns=['nightlights'], index=data.index)
# quantize nightlights
features['nightlights'] = pd.qcut(features['nightlights'], 5, labels=False, duplicates='drop')
data = data.join(features)
# ---------------- #
# add OSM features #
# ---------------- #
OSM = OSM_extractor(minlon, minlat, maxlon, maxlat)
tags = {"amenity": ["school", "hospital"], "natural": ["tree"]}
osm_gdf = {}
for key, values in tags.items():
for value in values:
osm_gdf["value"] = OSM.download(key, value)
dist = OSM.distance_to_nearest(GRID.lat, GRID.lon, osm_gdf["value"])
data['distance_{}'.format(value)] = [np.log(0.0001 + x) for x in dist]
# ---------------- #
# NDBI, NDVI, NDWI #
# ---------------- #
print('INFO: getting NDBI, NDVI, NDWI ...')
from rms_indexes import S2indexes
S2 = S2indexes(area, '../Data/Geofiles/NDs/', config['NDs_date']['start'], config['NDs_date']['end'], config['scope'])
S2.download()
data['max_NDVI'], data['max_NDBI'], data['max_NDWI'] = S2.rms_values(GRID.lon, GRID.lat)
# --------------- #
# add ACLED #
# --------------- #
from acled import ACLED
acled = ACLED("../Data/Geofiles/ACLED/")
acled.download(config['iso3'], config['nightlights_date']['start'], config['nightlights_date']['end'])
d = {}
for property in ["fatalities", "n_events", "violence_civ"]:
for k in [10000, 100000]:
d[property + "_" + str(k)] = acled.featurize(GRID.lon, GRID.lat, property=property, function='density', buffer=k)
d["weighted_sum_fatalities_by_dist"] = acled.featurize(GRID.lon, GRID.lat, property="fatalities", function='weighted_kNN')
d["distance_to_acled_event"] = acled.featurize(GRID.lon, GRID.lat, function='distance')
# quantize ACLED
for c in d.keys():
d[c] = np.nan_to_num(pd.qcut(d[c], 5, labels=False, duplicates='drop'))
features = pd.DataFrame(d, index=data.index)
data = data.join(features)
# --------------- #
# save features #
# --------------- #
# drop columns with only 1 value
print('INFO: {} columns. Dropping features with unique values (if any) ...'.format(len(data.columns)))
data = data[[col for col in data if not data[col].nunique() == 1]]
print('INFO: {} columns.'.format(len(data.columns)))
# features to be use in the linear model
features_list = list(sorted(set(data.columns) - set(['i', 'j', config['indicator']])))
#Save non-scaled features
data.to_csv("../Data/Features/features_all_id_{}_evaluation_nonscaled.csv".format(config['id']))
# Scale Features
print("Normalizing : max")
data[features_list] = (data[features_list] - data[features_list].mean()) / (data[features_list].max()+0.001)
data.to_csv("../Data/Features/features_all_id_{}_evaluation.csv".format(config['id']))
# --------------- #
# model indicator #
# --------------- #
# shuffle dataset
data = data.sample(frac=1, random_state=1783) # shuffle data
scores_dict = {} # placeholder to save the scores
from modeller import Modeller
X, y = data[features_list].reset_index(), data[config['indicator']]
modeller = Modeller(X, rs_features=features_list, spatial_features=["gpsLatitude", "gpsLongitude"], scoring='r2', cv_loops=20)
kNN_pipeline = modeller.make_model_pipeline('kNN')
kNN_scores = modeller.compute_scores(kNN_pipeline, y)
scores_dict['kNN_R2_mean'] = round(kNN_scores.mean(), 2)
scores_dict['kNN_R2_std'] = round(kNN_scores.std(), 2)
print("kNN_R2_mean: ", scores_dict['kNN_R2_mean'], "kNN_R2_std: ", scores_dict['kNN_R2_std'])
Ridge_pipeline = modeller.make_model_pipeline('Ridge')
Ridge_scores = modeller.compute_scores(Ridge_pipeline, y)
scores_dict['ridge_R2_mean'] = round(Ridge_scores.mean(), 2)
scores_dict['ridge_R2_std'] = round(Ridge_scores.std(), 2)
print("Ridge_R2_mean: ", scores_dict['ridge_R2_mean'], "Ridge_R2_std: ", scores_dict['ridge_R2_std'])
Ensemble_pipeline = modeller.make_ensemble_pipeline([kNN_pipeline, Ridge_pipeline])
Ensemble_scores = modeller.compute_scores(Ensemble_pipeline, y)
scores_dict['ensemble_R2_mean'] = round(Ensemble_scores.mean(), 2)
scores_dict['ensemble_R2_std'] = round(Ensemble_scores.std(), 2)
print("Ensemble_R2_mean: ", scores_dict['ensemble_R2_mean'], "Ensemble_R2_std: ", scores_dict['ensemble_R2_std'])
# save results
if id is None:
write_scores_to_file(scores_dict, config['id'])
else:
write_scores_to_db(scores_dict, config['id'], engine)
# ------------------------- #
# write predictions to file #
# ------------------------- #
print('INFO: writing predictions to disk ...')
from sklearn.model_selection import cross_val_predict
results = pd.DataFrame({
'yhat': cross_val_predict(Ensemble_pipeline, X.values, y),
'y': data[config['indicator']].values},
index=data.index)
results.to_csv('../Data/Results/config_{}.csv'.format(config['id']))
# save model for production
Ensemble_pipeline.fit(X.values, y)
# Best n_neighbors (kNN)
print('INFO: number of neighbours chosen: ', Ensemble_pipeline.regr_[0].named_steps['gridsearchcv'].best_params_)
# Best alpha (Ridge)
print('INFO: regularization param chosen: ', Ensemble_pipeline.regr_[1].named_steps['gridsearchcv'].best_params_)
from sklearn.externals import joblib
joblib.dump(Ensemble_pipeline, '../Models/Ensemble_model_config_id_{}.pkl'.format(id))
print(str(np.datetime64('now')), 'INFO: model saved.')
if __name__ == "__main__":
import tensorflow as tf
for id in sys.argv[1:]:
if id.isdigit():
# use database for configs
run(file=False, id=id)
else:
# use yml for configs
print(os.getcwd())
run(file=id)
# rubbish collection
tf.keras.backend.clear_session()