-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunetgee.py
More file actions
2236 lines (2044 loc) · 112 KB
/
unetgee.py
File metadata and controls
2236 lines (2044 loc) · 112 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
import selfee as se
import json
import tensorflow as tf
import geemap
import ee
import re
import time
import gzip
import numpy as np
import os
import random
import shutil
import datetime
import urllib3
import socket
import functools
from tqdm.keras import TqdmCallback
from dateutil.relativedelta import relativedelta
from tensorflow.keras import layers
from tensorflow.keras import losses
from tensorflow.keras import models
from tensorflow.keras import metrics
from tensorflow.keras import optimizers
from tensorflow.keras.layers import BatchNormalization
import matplotlib.pyplot as plt
import my_unet_definition.model as my_unet
import my_unet_definition.evaluation_metrics as my_metrics
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
def read_samples(training_pattern, eval_pattern, local_sample_folder, input_bands, input_band_scaling_factors:list, response, kernel_size, batch_size, only_sizes=False, compression_type=None):
kernel_shape = [kernel_size, kernel_size]
features = input_bands + response
columns = [
tf.io.FixedLenFeature(shape=kernel_shape, dtype=tf.float32) for k in features
]
features_dict = dict(zip(features, columns))
def parse_tfrecord(example_proto):
return tf.io.parse_single_example(example_proto, features_dict)
def to_tuple(inputs):
inputs_list = [inputs.get(key) for key in features]
stacked = tf.stack(inputs_list, axis=0)
# Convert from CHW to HWC
stacked = tf.transpose(stacked, [1, 2, 0])
# Scale the input bands
scaling_factors = tf.constant(input_band_scaling_factors, dtype=tf.float32)
scaled = tf.cast(stacked[:,:,:len(input_bands)], tf.float32) * scaling_factors
return scaled, stacked[:,:,len(input_bands):]
def predicate(inputs):
inputs_list = [inputs.get(key) for key in features]
stacked = tf.stack(inputs_list, axis = 0)
stacked = tf.transpose(stacked, [1, 2, 0])
output = stacked[:,:,len(input_bands):]
return tf.math.reduce_sum(output) < 99999
def get_dataset_size():
file_list = [s for s in os.popen(f'ls {local_sample_folder}').read().split('\n') if s]
training_files = [local_sample_folder + s for s in file_list if (training_pattern in s) and ('tfrecord' in s)]
dataset = tf.data.TFRecordDataset(training_files, compression_type=compression_type)
dataset = dataset.map(parse_tfrecord, num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.filter(predicate)
c = 0
for element in dataset.as_numpy_iterator():
c += 1
training_size = c
file_list = [s for s in os.popen(f'ls {local_sample_folder}').read().split('\n') if s]
eval_files = [local_sample_folder + s for s in file_list if (eval_pattern in s) and ('tfrecord' in s)]
dataset = tf.data.TFRecordDataset(eval_files, compression_type=compression_type)
dataset = dataset.map(parse_tfrecord, num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.filter(predicate)
c = 0
for element in dataset.as_numpy_iterator():
c += 1
eval_size = c
print(f'training size: {training_size}, eval_size: {eval_size}')
return training_size, eval_size
def get_dataset(pattern):
file_list = [s for s in os.popen(f'ls {local_sample_folder}').read().split('\n') if s]
files = [local_sample_folder + s for s in file_list if (pattern in s) and ('tfrecord' in s)]
dataset = tf.data.TFRecordDataset(files, compression_type=compression_type).prefetch(tf.data.AUTOTUNE)
dataset = dataset.map(parse_tfrecord, num_parallel_calls=tf.data.AUTOTUNE)
if 'filtered' in local_sample_folder:
pass
else:
dataset = dataset.filter(predicate)
dataset = dataset.map(to_tuple, num_parallel_calls=tf.data.AUTOTUNE)
return dataset
def get_training_dataset(shuffle_buffer_size):
dataset = get_dataset(training_pattern)
dataset = dataset.shuffle(shuffle_buffer_size).batch(batch_size).repeat()
return dataset
def get_eval_dataset():
dataset = get_dataset(eval_pattern)
dataset = dataset.batch(1).repeat()
return dataset
training_size, eval_size = get_dataset_size()
print(f'training size: {training_size}, eval_size: {eval_size}')
shuffle_buffer_size = int(training_size/30)
if only_sizes:
return training_size, eval_size
else:
return get_training_dataset(shuffle_buffer_size), get_eval_dataset(), training_size, eval_size
def read_test_samples(test_pattern, local_sample_folder, input_bands, input_band_scaling_factors, response, kernel_size, compression_type=None):
kernel_shape = [kernel_size, kernel_size]
features = input_bands + response
columns = [
tf.io.FixedLenFeature(shape=kernel_shape, dtype=tf.float32) for k in features
]
features_dict = dict(zip(features, columns))
def parse_tfrecord(example_proto):
return tf.io.parse_single_example(example_proto, features_dict)
def to_tuple(inputs):
inputs_list = [inputs.get(key) for key in features]
stacked = tf.stack(inputs_list, axis=0)
# Convert from CHW to HWC
stacked = tf.transpose(stacked, [1, 2, 0])
# Scale the input bands
scaling_factors = tf.constant(input_band_scaling_factors, dtype=tf.float32)
scaled = tf.cast(stacked[:,:,:len(input_bands)], tf.float32) * scaling_factors
return scaled, stacked[:,:,len(input_bands):]
def predicate(inputs):
inputs_list = [inputs.get(key) for key in features]
stacked = tf.stack(inputs_list, axis = 0)
stacked = tf.transpose(stacked, [1, 2, 0])
output = stacked[:,:,len(input_bands):]
return tf.math.reduce_sum(output) < 99999
def get_dataset(pattern):
file_list = [s for s in os.popen(f'ls {local_sample_folder}').read().split('\n') if s]
files = [local_sample_folder + s for s in file_list if (pattern in s) and ('tfrecord' in s)]
dataset = tf.data.TFRecordDataset(files, compression_type=compression_type).prefetch(tf.data.AUTOTUNE)
dataset = dataset.map(parse_tfrecord, num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.filter(predicate)
dataset = dataset.map(to_tuple, num_parallel_calls=tf.data.AUTOTUNE)
return dataset
def get_test_dataset():
dataset = get_dataset(test_pattern)
dataset = dataset.batch(1)
return dataset
return get_test_dataset()
def draw_unet_train_figure(history, save_path):
def moving_average(points, window_size=0):
smoothed_points = []
for point in points:
if len(smoothed_points) < window_size:
smoothed_points.append(point)
else:
smoothed_points.append(1/(window_size+1)*(point + np.sum([smoothed_points[-(i+1)] for i in range(window_size)])))
return smoothed_points
acc = moving_average(history['binary_accuracy'])
val_acc = moving_average(history['val_binary_accuracy'])
loss = moving_average(history['loss'])
val_loss = moving_average(history['val_loss'])
iou_coef = moving_average(history['IoU_coef'])
val_iou_coef = moving_average(history['val_IoU_coef'])
epochs = range(1, len(acc) + 1)
plt.figure(figsize=(20, 10))
plt.subplot(3,1,1)
plt.plot(epochs, acc, 'r', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.grid(True, which='both', axis='both', linestyle='--', linewidth=0.5)
plt.xticks(np.arange(0, len(epochs)+1, 25)) # Change here
plt.yticks(np.arange(0, 1.05, 0.05))
plt.gca().xaxis.grid(True, which='major', linestyle='--', linewidth=0.5)
plt.gca().yaxis.grid(True, which='major', linestyle='--', linewidth=0.5)
plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(5)) # Change here
plt.subplot(3,1,2)
plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.grid(True, which='both', axis='both', linestyle='--', linewidth=0.5)
plt.xticks(np.arange(0, len(epochs)+1, 25)) # Change here
plt.yticks(np.arange(0, max(max(loss), max(val_loss))+0.05, 0.05))
plt.gca().xaxis.grid(True, which='major', linestyle='--', linewidth=0.5)
plt.gca().yaxis.grid(True, which='major', linestyle='--', linewidth=0.5)
plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(5)) # Change here
plt.subplot(3,1,3)
plt.plot(epochs, iou_coef, 'r', label='Training IoU')
plt.plot(epochs, val_iou_coef, 'b', label='Validation IoU')
plt.title('Training and validation IoU')
plt.legend()
plt.grid(True, which='both', axis='both', linestyle='--', linewidth=0.5)
plt.xticks(np.arange(0, len(epochs)+1, 25)) # Change here
plt.yticks(np.arange(0, 1.05, 0.05))
plt.gca().xaxis.grid(True, which='major', linestyle='--', linewidth=0.5)
plt.gca().yaxis.grid(True, which='major', linestyle='--', linewidth=0.5)
plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(5)) # Change here
plt.savefig(save_path, format="pdf", bbox_inches="tight", dpi=300)
plt.close()
return None
def unet_train(training_pattern, eval_pattern, local_sample_folder, input_bands, input_band_scaling_factors:list, response,
kernel_size, epochs, batch_size, save_models_and_figures_folder, keep_ratio=1):
def deserialize_example(serialized_example, features_dict):
"""
Parse the serialized data so we get a dict with our data.
"""
return tf.io.parse_single_example(serialized_example, features_dict)
def adapted_predicate(serialized_example, features_dict, input_bands):
"""
Deserialize and apply the filtering logic to each example.
"""
example = deserialize_example(serialized_example, features_dict)
inputs_list = [example[key] for key in features_dict.keys()]
stacked = tf.stack(inputs_list, axis=0)
stacked = tf.transpose(stacked, [1, 2, 0])
output = stacked[:, :, len(input_bands):]
return tf.math.reduce_sum(output) < 99999
def filter_and_save_dataset(original_pattern, compressed_sample_folder, destination_folder, features_dict, input_bands, keep_ratio=1):
"""
Filters out samples based on the predicate and saves the result as uncompressed TFRecord files.
"""
file_list = [s for s in os.popen(f'ls {compressed_sample_folder}').read().split('\n') if s]
file_list = [compressed_sample_folder + s for s in file_list if (original_pattern in s) and ('tfrecord' in s)]
for file_path in file_list:
raw_dataset = tf.data.TFRecordDataset(file_path, compression_type='GZIP')
filtered_dataset = raw_dataset.filter(
lambda x: adapted_predicate(x, features_dict, input_bands) and random.random() < keep_ratio
)
# Construct the output file path
file_name = os.path.basename(file_path)
output_path = os.path.join(destination_folder, file_name.replace(".gz", ""))
# Serialize and save the filtered dataset
with tf.io.TFRecordWriter(output_path) as writer:
for raw_record in filtered_dataset:
writer.write(raw_record.numpy())
kernel_shape = [kernel_size, kernel_size]
features = input_bands + response
columns = [
tf.io.FixedLenFeature(shape=kernel_shape, dtype=tf.float32) for k in features
]
features_dict = dict(zip(features, columns))
local_uncompressed_sample_folder = local_sample_folder + 'uncompressed_filtered/'
if not os.path.exists(local_uncompressed_sample_folder):
os.makedirs(local_uncompressed_sample_folder, exist_ok=True)
print(f'Filtering and saving training dataset to {local_uncompressed_sample_folder}')
filter_and_save_dataset(training_pattern, local_sample_folder, local_uncompressed_sample_folder, features_dict, input_bands, keep_ratio)
print(f'Filtering and saving evaluation dataset to {local_uncompressed_sample_folder}')
filter_and_save_dataset(eval_pattern, local_sample_folder, local_uncompressed_sample_folder, features_dict, input_bands, keep_ratio)
training, evaluation, training_size, eval_size = read_samples(
training_pattern=training_pattern, eval_pattern=eval_pattern, local_sample_folder=local_uncompressed_sample_folder,
input_bands=input_bands, input_band_scaling_factors=input_band_scaling_factors, response=response, kernel_size=kernel_size, batch_size=batch_size,
compression_type=None
)
if not os.path.exists(save_models_and_figures_folder):
os.makedirs(save_models_and_figures_folder)
m = my_unet.attentionunet(input_shape=(kernel_size, kernel_size, len(input_bands)))
m.compile(
optimizer=optimizers.Adam(),
loss=my_metrics.IoU_loss,
metrics=[metrics.binary_accuracy, my_metrics.IoU_coef]
)
checkpoint_path = save_models_and_figures_folder + "cp-{epoch:04d}.ckpt"
cp_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_path,
period=5
)
tqdm_callback = TqdmCallback()
history = m.fit(
x=training,
epochs=epochs,
steps_per_epoch=int(training_size / batch_size),
validation_data=evaluation,
validation_steps=eval_size,
callbacks=[cp_callback, tqdm_callback],
verbose = 0,
workers = 8,
use_multiprocessing=True,
max_queue_size = 25,
)
history = history.history
with open(save_models_and_figures_folder + 'history.txt', 'w+') as file:
file.write(json.dumps(history))
if os.path.exists(local_uncompressed_sample_folder):
print('Removing uncompressed samples')
shutil.rmtree(local_uncompressed_sample_folder)
def moving_average(points, window_size=0):
smoothed_points = []
for point in points:
if len(smoothed_points) < window_size:
smoothed_points.append(point)
else:
smoothed_points.append(1/(window_size+1)*(point + np.sum([smoothed_points[-(i+1)] for i in range(window_size)])))
return smoothed_points
acc = moving_average(history['binary_accuracy'])
val_acc = moving_average(history['val_binary_accuracy'])
loss = moving_average(history['loss'])
val_loss = moving_average(history['val_loss'])
iou_coef = moving_average(history['IoU_coef'])
val_iou_coef = moving_average(history['val_IoU_coef'])
epochs = range(1, len(acc) + 1)
plt.figure(figsize=(20, 10))
plt.subplot(3,1,1)
plt.plot(epochs, acc, 'r', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.subplot(3,1,2)
plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.subplot(3,1,3)
plt.plot(epochs, iou_coef, 'r', label='Training IoU')
plt.plot(epochs, val_iou_coef, 'b', label='Validation IoU')
plt.title('Training and validation IoU')
plt.legend()
plt.savefig(save_models_and_figures_folder + 'loss_and_accuracy.pdf', format="pdf", bbox_inches="tight")
return m
def unet_train_per_feature(collection_size, local_sample_folder, save_models_and_figures_folder,
training_pattern='training', eval_pattern='eval', input_bands=['AWEI_MODIS'], response=['Water_GSW'],
kernel_size=128, epochs=150, batch_size=32, start_feature_index=0, end_feature_index=int(1e10)):
local_sample_folders = [local_sample_folder + str(i) + '/' for i in range(collection_size)]
save_models_and_figures_folders = [save_models_and_figures_folder + str(i) + '/' for i in range(collection_size)]
while start_feature_index < end_feature_index and start_feature_index < collection_size:
print(f'Training UNet in Feature {start_feature_index}')
lsf = local_sample_folders[start_feature_index]
smaff = save_models_and_figures_folders[start_feature_index]
unet_train(training_pattern=training_pattern, eval_pattern=eval_pattern,
local_sample_folder=lsf, input_bands=input_bands, response=response, kernel_size=kernel_size,
epochs=epochs, batch_size=batch_size, save_models_and_figures_folder=smaff)
start_feature_index += 1
return None
def unet_evaluate_on_test(model_path, test_pattern, test_sample_folder, input_bands=['AWEI_MODIS'], response=['Water_GSW'], kernel_size=128):
test = read_test_samples(test_pattern, test_sample_folder, input_bands=input_bands, response=response, kernel_size=kernel_size)
m = tf.keras.models.load_model(model_path)
loss, accuracy = m.evaluate(test)
return loss, accuracy
#new version
def do_prediction(m, input_bands:list, output_band:str, input_image_base, output_image_name, local_input_folder, local_output_folder, bucket, gcs_folder, gee_folder, kernel_size, sa_index,
compress=True, download=False, upload=False):
"""Perform inference on exported imagery, upload to Earth Engine.
"""
sa_json = se.KEYPATHS[sa_index]
if not os.path.exists(local_input_folder):
os.mkdir(local_input_folder)
if not os.path.exists(local_output_folder):
os.mkdir(local_output_folder)
kernel_shape = [kernel_size, kernel_size]
kernel_buffer = [int(x*0.5) for x in kernel_shape]
os.system(f'gcloud auth activate-service-account --key-file {sa_json}')
if(download == True):
print('Looking for TFRecord files...')
# Get a list of all the files in the output bucket.
filesList = os.popen(f'gsutil ls gs://{bucket}/{gcs_folder}').read()
filesList = [f for f in filesList.split('\n') if f]
# Get only the files generated by the image export.
exportFilesList = [s for s in filesList if (input_image_base in s and ('tfrecord' in s or 'json' in s))]
for file in exportFilesList:
os.system(f'gsutil cp {file} {local_input_folder}')
if(file.endswith('json')):
cloud_json_file = file
exportFilesList = os.popen(f'ls {local_input_folder}').read()
exportFilesList = [local_input_folder + s for s in exportFilesList.split('\n') if(s and input_image_base in s and ('tfrecord' in s or 'json' in s))]
# Get the list of image files and the JSON mixer file.
imageFilesList = []
jsonFile = None
for f in exportFilesList:
if f.endswith('.tfrecord.gz'):
imageFilesList.append(f)
elif f.endswith('.json'):
jsonFile = f
# Make sure the files are in the right order.
imageFilesList.sort()
from pprint import pprint
#pprint(imageFilesList)
#print(jsonFile)
import json
# Load the contents of the mixer file to a JSON object.
with open(jsonFile) as f:
mixer = json.load(f)
#pprint(mixer)
patches = mixer['totalPatches']
# Get set up for prediction.
x_buffer = int(kernel_buffer[0] / 2)
y_buffer = int(kernel_buffer[1] / 2)
buffered_shape = [
kernel_shape[0] + kernel_buffer[0],
kernel_shape[1] + kernel_buffer[1]]
imageColumns = [
tf.io.FixedLenFeature(shape=buffered_shape, dtype=tf.float32)
for k in input_bands
]
imageFeaturesDict = dict(zip(input_bands, imageColumns))
def parse_image(example_proto):
return tf.io.parse_single_example(example_proto, imageFeaturesDict)
def toTupleImage(inputs):
inputsList = [inputs.get(key) for key in input_bands]
stacked = tf.stack(inputsList, axis=0)
stacked = tf.transpose(stacked, [1, 2, 0])
return stacked
# Create a dataset from the TFRecord file(s) in Cloud Storage.
imageDataset = tf.data.TFRecordDataset(imageFilesList, compression_type='GZIP')
imageDataset = imageDataset.map(parse_image, num_parallel_calls=12)
imageDataset = imageDataset.map(toTupleImage)
imageDataset = imageDataset.batch(1)
# Perform inference.
print('Running predictions...')
predictions = m.predict(imageDataset, steps=patches, verbose=1)
for i in range(len(predictions)):
predictions[i][predictions[i] >= 0.5] = 1
predictions[i][predictions[i] < 0.5] = 0
print('Writing predictions...')
out_image_file = local_output_folder + output_image_name + '.tfrecord'
writer = tf.io.TFRecordWriter(out_image_file)
patches = 0
print(f'Writing {out_image_file}')
for predictionPatch in predictions:
predictionPatch = predictionPatch.astype(np.uint8)
predictionPatch = predictionPatch[
x_buffer:x_buffer+kernel_size, y_buffer:y_buffer+kernel_size]
# Create an example.
example = tf.train.Example(
features=tf.train.Features(
feature={
output_band: tf.train.Feature(
float_list=tf.train.FloatList(
value=predictionPatch.flatten()))
}
)
)
# Write the example.
writer.write(example.SerializeToString())
patches += 1
writer.close()
if compress == True:
print(f'compressing {out_image_file}')
compressed_out_image_file = f'{out_image_file}.gz'
with open(out_image_file, 'rb') as f_in:
with gzip.open(compressed_out_image_file, 'wb') as f_out:
f_out.writelines(f_in)
os.remove(out_image_file)
predicted_json_file = local_output_folder + output_image_name + 'mixer.json'
os.system(f'cp {jsonFile} {predicted_json_file}')
upload_task_id = None
if upload == True:
# Start the upload.
gee_image_asset = gee_folder + output_image_name
cloud_out_image_file = 'gs://' + bucket + gcs_folder + output_image_name + '.TFRecord'
os.system(f'gsutil cp {out_image_file} {cloud_out_image_file}')
os.system(f'earthengine --service_account_file {sa_json} upload image --asset_id={gee_image_asset} {cloud_out_image_file} {cloud_json_file}')
se.auth_gee_service_account(sa_index)
upload_task_id = ee.data.getTaskList()[0]['id']
return upload_task_id
def do_prediction_modis_awei(model, input_image_base, output_image_name, local_input_folder, local_output_folder, bucket, gcs_folder, gee_folder, sa_index = None,
compress=True, download=False, upload=False):
input_bands = ['AWEI_MODIS']
output_band = 'Predicted_Water'
kernel_size = 128
upload_task_id = do_prediction(
m=model,
input_bands=input_bands, output_band=output_band,
input_image_base=input_image_base, output_image_name=output_image_name,
local_input_folder=local_input_folder, local_output_folder=local_output_folder,
bucket=bucket, gcs_folder=gcs_folder, gee_folder=gee_folder,
kernel_size=kernel_size,
sa_index=sa_index,
compress=compress,
download=download,
upload=upload
)
return upload_task_id
def do_prediction_modis_awei_monthly(model_path, start_date:str, end_date:str, input_image_base, output_image_base, local_input_folder, local_output_folder, bucket, gcs_folder, gee_folder, sa_index=None, compress=True, download=False, upload=False):
date_format = '%Y-%m-%d'
start_date = datetime.datetime.strptime(start_date, date_format).date()
end_date = datetime.datetime.strptime(end_date, date_format).date()
current_date = start_date
upload_task_ids = []
model = tf.keras.models.load_model(model_path)
#model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
while current_date < end_date:
current_input_image_base = input_image_base + f'{current_date.strftime(date_format)}_{(current_date + relativedelta(months=1)).strftime(date_format)}'
current_output_image_base = output_image_base + f'{current_date.strftime(date_format)}_{(current_date + relativedelta(months=1)).strftime(date_format)}'
current_upload_task_id = do_prediction_modis_awei(
model=model,
input_image_base=current_input_image_base,
output_image_name=current_output_image_base,
local_input_folder=local_input_folder,
local_output_folder=local_output_folder,
bucket=bucket, gcs_folder=gcs_folder, gee_folder=gee_folder,
sa_index=sa_index, compress=True, download=download, upload=upload
)
upload_task_ids.append(current_upload_task_id)
current_date = current_date + relativedelta(months=1)
def upload_tfrecord_gz_to_gee(file_name_base, local_folder, local_task_info_folder, bucket, gcs_folder, gee_asset, gee_file_name, sa_index:int, auth=False, test=False):
if(auth):
se.auth_gcs_service_account(sa_index)
if not os.path.exists(local_task_info_folder):
os.makedirs(local_task_info_folder)
compressed_image_file_name = f'{file_name_base}.tfrecord.gz'
decompressed_image_file_name = f'{file_name_base}.tfrecord'
json_file_name = f'{file_name_base}mixer.json'
local_compressed_image_path = f'{local_folder}{compressed_image_file_name}'
local_decompressed_image_path = f'{local_folder}{decompressed_image_file_name}'
local_json_path = f'{local_folder}{json_file_name}'
gcs_decompressed_image_path = f'gs://{bucket}/{gcs_folder}{decompressed_image_file_name}'
gcs_json_path = f'gs://{bucket}/{gcs_folder}{json_file_name}'
print(f'decompressing {compressed_image_file_name} locally')
with gzip.open(local_compressed_image_path, 'rb') as gzip_file:
local_compressed_image_content = gzip_file.read()
with open(local_decompressed_image_path, 'wb') as decompressed_file:
decompressed_file.write(local_compressed_image_content)
success_flag = False
while not success_flag:
try:
print(f'uploading {compressed_image_file_name} and {json_file_name} from local to gcs')
os.system(f'gsutil cp -J {local_decompressed_image_path} {gcs_decompressed_image_path}')
os.system(f'gsutil cp {local_json_path} {gcs_json_path}')
print(f'removing {local_decompressed_image_path}')
os.system(f'rm {local_decompressed_image_path}')
gee_image_path = f'{gee_asset}{gee_file_name}'
sa_json = se.KEYPATHS[sa_index]
print(f'uploading {decompressed_image_file_name} and {json_file_name} from gcs to gee')
if not test:
task_id = os.popen(f'earthengine --service_account_file {sa_json} upload image --pyramiding_policy MODE --asset_id {gee_image_path} {gcs_decompressed_image_path} {gcs_json_path}').read()
task_id = task_id.split(' ')[-1].replace('\n', '')
else:
task_id = 'test-no-task-id'
success_flag = True
except socket.gaierror:
print('socket error, retrying')
time.sleep(random.randint(60, 180))
except urllib3.exceptions.NewConnectionError:
print('connection error, retrying')
time.sleep(random.randint(60, 180))
except urllib3.exceptions.MaxRetryError:
print('max retry error, retrying')
time.sleep(random.randint(60, 180))
local_task_info_path = f'{local_task_info_folder}{file_name_base}info.json'
task_info_json = {
'local_compressed_image_path': local_compressed_image_path,
'local_json_path': local_json_path,
'gcs_decompressed_image_path': gcs_decompressed_image_path,
'gcs_json_path': gcs_json_path,
'gee_image_path': gee_image_path,
'upload_task_id': task_id,
'sa_index': sa_index
}
with open(local_task_info_path, 'w') as f:
json.dump(task_info_json, f)
return local_task_info_path
def upload_monthly_tfrecord_gz_to_gee(start_date, end_date, file_name_base, local_folder, local_task_info_folder, bucket, gcs_folder, gee_asset, gee_file_name_base, sa_index:int, auth=False, test=False):
date_format = '%Y-%m-%d'
start_date = datetime.datetime.strptime(start_date, date_format).date()
end_date = datetime.datetime.strptime(end_date, date_format).date()
current_date = start_date
task_count = 0
completed_task = 0
local_task_info_paths = []
while current_date < end_date:
current_file_name_base = file_name_base + current_date.strftime(date_format) + '_' + (current_date + relativedelta(months=1)).strftime(date_format)
current_gee_file_name = gee_file_name_base + current_date.strftime(date_format) + '_' + (current_date + relativedelta(months=1)).strftime(date_format)
print(f'uploading {current_file_name_base} to gee')
current_local_task_info_path = upload_tfrecord_gz_to_gee(
file_name_base=current_file_name_base,
local_folder=local_folder,
local_task_info_folder=local_task_info_folder,
bucket=bucket,
gcs_folder=gcs_folder,
gee_asset=gee_asset,
gee_file_name=current_gee_file_name,
sa_index=sa_index,
auth=auth, test=test
)
local_task_info_paths.append(current_local_task_info_path)
task_count += 1
current_date = current_date + relativedelta(months=1)
if(task_count % 5 == 0):
with open(local_task_info_paths[task_count - 4], 'r') as f:
ahead_5th_task_info = json.load(f)
ahead_5th_task_id = ahead_5th_task_info['upload_task_id']
# possible states: READY, RUNNING, FAILED, COMPLETED
ahead_5th_task_state = ee.data.getTaskStatus(ahead_5th_task_id)[0]['state']
while(ahead_5th_task_state == 'READY'):
print(f'Waiting: {ahead_5th_task_id}({task_count - 4}) now is still {ahead_5th_task_state}')
time.sleep(60)
ahead_5th_task_state = ee.data.getTaskStatus(ahead_5th_task_id)[0]['state']
if(completed_task < task_count):
with open(local_task_info_paths[completed_task], 'r') as f:
completed_task_info = json.load(f)
completed_task_id = completed_task_info['upload_task_id']
completed_task_state = ee.data.getTaskStatus(completed_task_id)[0]['state']
while((completed_task_state == 'FAILED' or completed_task_state == 'COMPLETED')):
completed_gcs_decompressed_image_path = completed_task_info['gcs_decompressed_image_path']
completed_gcs_json_path = completed_task_info['gcs_json_path']
print(f'{completed_task_id}({completed_task}) is {completed_task_state}, try removing related files in gcs')
print(f'removing {completed_gcs_decompressed_image_path} {completed_gcs_json_path}')
os.system(f'gsutil rm {completed_gcs_decompressed_image_path}')
os.system(f'gsutil rm {completed_gcs_json_path}')
completed_task += 1
print(f'***********************{task_count} {len(local_task_info_paths)}')
if not completed_task < task_count:
break
with open(local_task_info_paths[completed_task], 'r') as f:
completed_task_info = json.load(f)
completed_task_id = completed_task_info['upload_task_id']
completed_task_state = ee.data.getTaskStatus(completed_task_id)[0]['state']
while completed_task < task_count:
with open(local_task_info_paths[completed_task], 'r') as f:
completed_task_info = json.load(f)
completed_task_id = completed_task_info['upload_task_id']
completed_task_state = ee.data.getTaskStatus(completed_task_id)[0]['state']
if(completed_task_state == 'FAILED' or completed_task_state == 'COMPLETED'):
completed_gcs_decompressed_image_path = completed_task_info['gcs_decompressed_image_path']
completed_gcs_json_path = completed_task_info['gcs_json_path']
print(f'{completed_task_id}({completed_task}) is {completed_task_state}, try removing related files in gcs')
print(f'removing {completed_gcs_decompressed_image_path} {completed_gcs_json_path}')
os.system(f'gsutil rm {completed_gcs_decompressed_image_path}')
os.system(f'gsutil rm {completed_gcs_json_path}')
completed_task += 1
else:
print(f'Waiting: {completed_task_id} is still {completed_task_state}')
time.sleep(60)
return None
def upload_single_local_to_gcs(local_folder, file_name, bucket, gcs_folder, sa_index=None):
local_path = local_folder + file_name
gcs_path = "gs://" + bucket + '/' + gcs_folder + file_name
if(sa_index):
se.auth_gcs_service_account(sa_index)
print(f"Uploading {local_path} to {gcs_path}")
os.system(f'gsutil cp {local_path} {gcs_path}')
return None
def upload_multiple_local_to_gcs(local_foler, file_base, file_format, bucket, gcs_folder, sa_index=None):
if(sa_index):
se.auth_gcs_service_account(sa_index)
filenames = [s for s in os.popen(f'ls {local_foler}').read().split('\n') if (file_base in s and s and s.endswith(file_format))]
for file_name in filenames:
upload_single_local_to_gcs(local_folder=local_foler, file_name=file_name, bucket=bucket, gcs_folder=gcs_folder)
return None
def upload_single_tif_gcs_to_gee(bucket, gcs_folder, gcs_file_name, gee_asset, gee_file_name, sa_index=0):
gcs_path = "gs://" + bucket + "/" + gcs_folder + gcs_file_name
gee_asset_id = gee_asset + gee_file_name
sa_json = se.KEYPATHS[sa_index]
print(f'earthengine --service_account_file {sa_json} upload image --asset_id={gee_asset_id} {gcs_path}')
os.system(f'earthengine --service_account_file {sa_json} upload image --asset_id={gee_asset_id} {gcs_path}')
def upload_multiple_gcs_to_gee(bucket, gcs_folder, file_base, gee_asset, file_format, sa_index=0):
se.auth_gcs_service_account(sa_index)
if file_format == 'tif':
files_list = [s for s in os.popen(f'gsutil ls gs://{bucket}/{gcs_folder}').read().split('\n') if (s and file_base in s and s.endswith(file_format))]
filename_list = [s.split('/')[-1] for s in files_list]
filename_underscore_list = [re.sub('\.', '_', s) for s in filename_list]
filename_underscore_list = [re.sub('_tif', '', s) for s in filename_underscore_list]
for file_name, file_name_underscore in zip(filename_list, filename_underscore_list):
upload_single_tif_gcs_to_gee(
bucket=bucket,
gcs_folder=gcs_folder,
gcs_file_name=file_name,
gee_asset=gee_asset,
gee_file_name=file_name_underscore
)
return None
def image_generation(start_time, end_time, kernel_size, mode, input_bands:list, input_bands_type='int16', response=['Water_GSW'], custom_projection_wkt=None, custom_scale=500, return_mask=False, test_display=False, gsw_max_start_date='2021-12-01', gsw_max_end_date='2022-01-01'):
if mode not in ['modis_500m_gsw_projection', 'modis_500m_original_projection', 'modis_custom_projection', 'modis_30m_gsw_projection', 'joint_neighborhood', 'joint_neighborhood_custom_projection', 'gsw', 'gsw_custom_projection']:
raise ValueError('mode must be one of the following: modis_500m_gsw_projection, modis_500m_original_projection, modis_custom_projection, modis_30m_gsw_projection, joint_neighborhood, joint_neighborhood_custom_projection, gsw, gsw_custom_projection')
if mode in ['modis_custom_projection', 'joint_neighborhood_custom_projection'] and (custom_projection_wkt == None or custom_scale == None):
raise ValueError('custom_projection_wkt and custom_scale must be set for joint_neighborhood and joint_neighborhood_custom_projection')
if not set(input_bands).issubset(["B", "G", "R", "NIR", "SWIR1", "SWIR2", "AWEI", "SensorZenith", "SolarZenith", 'GSW_Occurrence', 'GSW_Recurrence']):
raise ValueError('input_bands must be a subset of ["B", "G", "R", "NIR", "SWIR1", "SWIR2", "AWEI", "SensorZenith", "SolarZenith", "GSW_Occurrence", "GSW_Recurrence"]')
if input_bands_type not in ['int16']:
raise ValueError('input_bands_type must be one of the following: int16')
modis_bands = ["sur_refl_b03", "sur_refl_b04", "sur_refl_b01", "sur_refl_b02", "sur_refl_b06", "sur_refl_b07", "SensorZenith", "SolarZenith"]
modis_bands_new = ["B_MODIS", "G_MODIS", "R_MODIS", "NIR_MODIS", "SWIR1_MODIS", "SWIR2_MODIS", "SensorZenith", "SolarZenith"]
common_bands = ["B", "G", "R", "NIR", "SWIR1", "SWIR2", "SensorZenith", "SolarZenith"]
list = ee.List.repeat(1, kernel_size)
lists = ee.List.repeat(list, kernel_size)
kernel = ee.Kernel.fixed(kernel_size, kernel_size, lists)
custom_projection = ee.Projection(custom_projection_wkt)
def bitwiseExtract(value, fromBit, toBit = None):
if (toBit == None): toBit = fromBit
maskSize = ee.Number(1).add(toBit).subtract(fromBit)
mask = ee.Number(1).leftShift(maskSize).subtract(1)
return value.rightShift(fromBit).bitwiseAnd(mask)
img_filter = ee.Filter([ee.Filter.date(start_time, end_time)])
if start_time <= gsw_max_start_date:
gsw_img_filter = img_filter
print('using regular filter for gsw, start date:', start_time)
else:
gsw_img_filter = ee.Filter([ee.Filter.date(gsw_max_start_date, gsw_max_end_date)])
print('using max filter for gsw, start date:', gsw_max_start_date)
gsw = ee.ImageCollection('JRC/GSW1_4/MonthlyHistory').filter(gsw_img_filter).first()
if mode in ['joint_neighborhood_custom_projection', 'gsw_custom_projection']:
gsw = gsw.reproject(custom_projection, scale=custom_scale)
if mode == 'gsw_custom_projection':
return gsw.rename(response), None
gsw = gsw.updateMask(gsw).subtract(1).unmask(999999).rename(response)
if mode == 'gsw':
return gsw, None
#These two bands in GEE is signed-int8 type - Attention
if 'GSW_Occurrence' in input_bands:
gsw_occurrence = ee.Image("JRC/GSW1_4/GlobalSurfaceWater").select('occurrence')
if mode in ['joint_neighborhood_custom_projection', 'modis_custom_projection']:
gsw_occurrence = gsw_occurrence.reproject(custom_projection, scale=custom_scale)
gsw_occurrence = gsw_occurrence.unmask(0).rename('GSW_Occurrence')
if 'GSW_Recurrence' in input_bands:
gsw_recurrence = ee.Image("JRC/GSW1_4/GlobalSurfaceWater").select('recurrence')
if mode in ['joint_neighborhood_custom_projection', 'modis_custom_projection']:
gsw_recurrence = gsw_recurrence.reproject(custom_projection, scale=custom_scale)
gsw_recurrence = gsw_recurrence.unmask(0).rename('GSW_Recurrence')
def modisPreprocess(img):
qa = img.select("state_1km")
cloud_state = bitwiseExtract(qa, 0, 1)
cloudshadow_state = bitwiseExtract(qa, 2)
cirrus_state = bitwiseExtract(qa, 8, 9)
mask = cloud_state.eq(0)\
.And(cloudshadow_state.eq(0))\
.And(cirrus_state.eq(0))
if mode == 'modis_500m_gsw_projection':
img = img.select(modis_bands, modis_bands_new).updateMask(mask).reproject(gsw.projection(), scale=500)
elif mode == 'modis_500m_original_projection':
img = img.select(modis_bands, modis_bands_new).updateMask(mask)
elif mode == 'modis_custom_projection':
img = img.select(modis_bands, modis_bands_new).updateMask(mask).reproject(custom_projection, scale=custom_scale)
elif mode == 'modis_30m_gsw_projection':
img = img.select(modis_bands, modis_bands_new).updateMask(mask).reproject(gsw.projection(), scale=30)
elif mode == 'joint_neighborhood':
img = img.select(modis_bands, modis_bands_new).updateMask(mask).reproject(gsw.projection(), scale=30)
elif mode == 'joint_neighborhood_custom_projection':
img = img.select(modis_bands, modis_bands_new).updateMask(mask).reproject(custom_projection, scale=custom_scale)
return img
modis = ee.ImageCollection("MODIS/061/MOD09GA")\
.filter(img_filter)\
.map(modisPreprocess)
modis_median_30m = modis.median().select(modis_bands_new, common_bands)
if mode in ['modis_custom_projection', 'joint_neighborhood_custom_projection']:
modis_median_30m = modis_median_30m.reproject(custom_projection, scale=custom_scale)
if return_mask:
#currently assume that the mask is the same for all bands
return modis_median_30m.select('B').mask()
modis_median_30m = modis_median_30m.unmask(0)
if 'AWEI' in input_bands:
def AWEI(img):
band2 = img.select("G")
band4 = img.select("NIR")
band5 = img.select("SWIR1")
band7 = img.select("SWIR2")
return band2.subtract(band5).multiply(4).subtract( band4.multiply(0.25).add( band7.multiply(2.75) ) )
modis_median_awei_30m = AWEI(modis_median_30m).rename('AWEI') #unmask(0) to avoid situations when MODIS has too much missing values
modis_median_30m = modis_median_30m.addBands(modis_median_awei_30m)
if 'GSW_Occurrence' in input_bands:
modis_median_30m = modis_median_30m.addBands(gsw_occurrence)
if 'GSW_Recurrence' in input_bands:
modis_median_30m = modis_median_30m.addBands(gsw_recurrence)
modis_median_30m = modis_median_30m.select(input_bands)
if input_bands_type == 'int16':
modis_median_30m = modis_median_30m.int16()
if mode != 'joint_neighborhood' and mode != 'joint_neighborhood_custom_projection':
return modis_median_30m, None
joined_median_30m = gsw.addBands(modis_median_30m)
neighborhood_joined_30m = joined_median_30m.neighborhoodToArray(kernel)
Map = geemap.Map()
if(test_display):
modis_visualization = {
'min': -0.0100,
'max': 0.5000,
'bands': ['NIR_MODIS', 'R_MODIS', 'G_MODIS']
}
awei_visualization = {
'min': -0.5,
'max': 0.0
}
gsw_raw_visualization = {
'bands': ['water'],
'min': 0.0,
'max': 2.0,
'palette': ['ffffff', 'fffcb8', '0905ff']
}
Map.addLayer(ee.ImageCollection('JRC/GSW1_4/MonthlyHistory').filter(gsw_img_filter).first(), gsw_raw_visualization, 'gsw_raw')
Map.addLayer(gsw, {'palette': ['black', 'red']}, 'gsw')
Map.addLayer(modis_median_30m, modis_visualization, 'modis_30m')
Map.addLayer(modis_median_awei_30m, awei_visualization, 'modis_awei_30m')
if mode == 'joint_neighborhood' or mode == 'joint_neighborhood_custom_projection':
return neighborhood_joined_30m, Map
def export_modis_mask_to_asset(start_date, end_date, gee_asset, gee_file_name, region, kernel_size=128):
modis_median_awei_30m_mask, Map = image_generation(start_time=start_date, end_time=end_date, kernel_size=kernel_size, mode='modis_awei_mask')
task = ee.batch.Export.image.toAsset(
image = modis_median_awei_30m_mask,
description = gee_file_name,
assetId = gee_asset+gee_file_name,
region = region,
scale = 30,
maxPixels = 1e13
)
print(f"Exporting {gee_file_name} to {gee_asset}")
task.start()
return None
def unet_sample_generation_time_period(region, start_time, end_time, generate_samples, train_size, eval_size, test_size, shard_size,
training_base, eval_base, test_base, starting_seed, export_to, input_bands:list, response=['Water_GSW'],
train_shard_num=20, eval_shard_num=20, test_shard_num=20,
custom_projection_wkt=None, custom_scale=None, mode='joint_neighborhood',
local_task_id_folder=None, local_task_id_base=None, drive_folder=None, bucket=None, gcs_folder=None, kernel_size=128, scale=30):
valid_export_to = ['drive', 'gcs']
if export_to not in valid_export_to:
raise ValueError(f'export_to must be one of {valid_export_to}')
if export_to == 'drive' and not drive_folder:
raise ValueError('drive_folder must be specified if export_to is drive')
if export_to == 'gcs' and not (bucket and gcs_folder):
raise ValueError('bucket and gcs_folder must be specified if export_to is gcs')
test_display = not generate_samples
neighborhood_joined_awei_30m, Map = image_generation(
start_time=start_time,
end_time=end_time,
kernel_size=kernel_size,
mode=mode,
input_bands=input_bands,
response=response,
custom_projection_wkt=custom_projection_wkt,
custom_scale=custom_scale,
test_display=test_display
)
train_shards = int(train_size/shard_size)
eval_shards = int(eval_size/shard_size)
test_shards = int(test_size/shard_size)
training_tasks = {}
eval_tasks = {}
test_tasks = {}
samples = ee.FeatureCollection([])
for i in range(int(train_shards)):
sample = neighborhood_joined_awei_30m.sample(**{
'numPixels': shard_size,
'scale': scale,
'region': region,
'seed': i+starting_seed,
'tileScale': 16
})
samples = samples.merge(sample)
if((i+1) % train_shard_num == 0):
g = int((i+1)/train_shard_num)
desc = training_base + "_" + str(g)
if export_to == 'drive':
task = ee.batch.Export.table.toDrive(**{
'collection': samples,
'description': desc,
'folder': drive_folder,
'fileNamePrefix': desc,
'fileFormat': 'TFRecord',
})
elif export_to == 'gcs':
task = ee.batch.Export.table.toCloudStorage(**{
'collection': samples,
'description': desc,
'bucket': bucket,
'fileNamePrefix': gcs_folder + desc,
'fileFormat': 'TFRecord',
})
if(generate_samples):
task.start()
training_tasks[desc] = task.id
samples = ee.FeatureCollection([])
samples = ee.FeatureCollection([])
for i in range(int(eval_shards)):
sample = neighborhood_joined_awei_30m.sample(**{
'numPixels': shard_size,
'scale': scale,
'region': region,
'seed': i+int(train_shards)+starting_seed,
'tileScale': 16
})
samples = samples.merge(sample)
if((i+1) % eval_shard_num == 0):
g = int((i+1)/eval_shard_num)
desc = eval_base + "_" + str(g)
if export_to == 'drive':
task = ee.batch.Export.table.toDrive(**{
'collection': samples,
'description': desc,
'folder': drive_folder,
'fileNamePrefix': desc,
'fileFormat': 'TFRecord',
})
elif export_to == 'gcs':
task = ee.batch.Export.table.toCloudStorage(**{
'collection': samples,
'description': desc,
'bucket': bucket,
'fileNamePrefix': gcs_folder + desc,
'fileFormat': 'TFRecord',
})
if(generate_samples):
task.start()
eval_tasks[desc] = task.id
samples = ee.FeatureCollection([])
samples = ee.FeatureCollection([])
for i in range(int(test_shards)):
sample = neighborhood_joined_awei_30m.sample(**{
'numPixels': shard_size,
'scale': scale,
'region': region,
'seed': i+int(train_shards)+int(eval_shards)+starting_seed,
'tileScale': 16