-
Notifications
You must be signed in to change notification settings - Fork 0
/
v13_3.py
2186 lines (1973 loc) · 77.6 KB
/
v13_3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
# i*- coding: utf-8 -*-
"""
v13 model
* Input: v12_im
Author: Kohei <i@ho.lc>
"""
from logging import getLogger, Formatter, StreamHandler, INFO, FileHandler
from pathlib import Path
import subprocess
import glob
import math
import sys
import json
import re
import warnings
import os
import scipy
import tqdm
import click
import tables as tb
import pandas as pd
import numpy as np
from keras.models import Model
from keras.engine.topology import merge as merge_l
from keras.layers import (
Input, Convolution2D, MaxPooling2D, UpSampling2D,
Reshape, core, Dropout,
Activation, BatchNormalization)
from keras.optimizers import Adam, SGD
from keras.callbacks import ModelCheckpoint, EarlyStopping, History
from keras import backend as K
import skimage.draw
import rasterio
import rasterio.features
import shapely.wkt
import shapely.ops
import shapely.geometry
import skimage.transform as ski_transform
#Added: Jan 30th: mask2linestrings.
import argparse
import cv2
import queue
from shapely.geometry import LineString, Point
import sys
from skimage import morphology
# Constants
width = 1300
height = 1300
white = 255
black = 0
spacing = 21
# Generates the lists of coordinate alterations needed to search around a
# candidate pixel up to a certain spacing away from the candidate pixel
def grid(spacing):
search = []
for r in range(-spacing, spacing+1, 1):
for c in range(-spacing, spacing+1, 1):
if r == -spacing or r == spacing or c == -spacing or c == spacing:
search.append((r, c))
return search
searches = []
for i in range(spacing):
searches.append(grid(i+1))
MODEL_NAME = 'v13'
ORIGINAL_SIZE = 1300
INPUT_SIZE = 256
STRIDE_SZ = 197
BASE_DIR = "/data/train"
BASE_TEST_DIR = "/data/test"
WORKING_DIR = "/data/working"
IMAGE_DIR = "/data/working/images/{}".format('v5')
V5_IMAGE_DIR = "/data/working/images/{}".format('v5')
# ---------------------------------------------------------
# Parameters
MIN_POLYGON_AREA = 30 # 30
# ---------------------------------------------------------
# Input files
FMT_TRAIN_SUMMARY_PATH = str(
Path(BASE_DIR) /
Path("{prefix:s}_Train/") /
Path("summaryData/{prefix:s}_Train_Building_Solutions.csv"))
FMT_TRAIN_RGB_IMAGE_PATH = str(
Path(BASE_DIR) /
Path("{prefix:s}_Train/") /
Path("RGB-PanSharpen/RGB-PanSharpen_{image_id:s}.tif"))
FMT_TEST_RGB_IMAGE_PATH = str(
Path(BASE_TEST_DIR) /
Path("{prefix:s}_Test/") /
Path("RGB-PanSharpen/RGB-PanSharpen_{image_id:s}.tif"))
FMT_TRAIN_MSPEC_IMAGE_PATH = str(
Path(BASE_DIR) /
Path("{prefix:s}_Train/") /
Path("MUL-PanSharpen/MUL-PanSharpen_{image_id:s}.tif"))
FMT_TEST_MSPEC_IMAGE_PATH = str(
Path(BASE_TEST_DIR) /
Path("{prefix:s}_Test/") /
Path("MUL-PanSharpen/MUL-PanSharpen_{image_id:s}.tif"))
# ---------------------------------------------------------
# Preprocessing result
FMT_RGB_BANDCUT_TH_PATH = IMAGE_DIR + "/rgb_bandcut.csv"
FMT_MUL_BANDCUT_TH_PATH = IMAGE_DIR + "/mul_bandcut.csv"
# ---------------------------------------------------------
# Image list, Image container and mask container
FMT_VALTRAIN_IMAGELIST_PATH = V5_IMAGE_DIR + "/{prefix:s}_valtrain_ImageId.csv"
FMT_VALTEST_IMAGELIST_PATH = V5_IMAGE_DIR + "/{prefix:s}_valtest_ImageId.csv"
FMT_VALTRAIN_IM_STORE = IMAGE_DIR + "/valtrain_{}_im.h5"
FMT_VALTEST_IM_STORE = IMAGE_DIR + "/valtest_{}_im.h5"
FMT_VALTRAIN_MASK_STORE = IMAGE_DIR + "/valtrain_{}_mask.h5"
FMT_VALTEST_MASK_STORE = IMAGE_DIR + "/valtest_{}_mask.h5"
FMT_VALTRAIN_MUL_STORE = IMAGE_DIR + "/valtrain_{}_mul.h5"
FMT_VALTEST_MUL_STORE = IMAGE_DIR + "/valtest_{}_mul.h5"
FMT_TRAIN_IMAGELIST_PATH = V5_IMAGE_DIR + "/{prefix:s}_train_ImageId.csv"
FMT_TEST_IMAGELIST_PATH = V5_IMAGE_DIR + "/{prefix:s}_test_ImageId.csv"
FMT_TRAIN_IM_STORE = IMAGE_DIR + "/train_{}_im.h5"
FMT_TEST_IM_STORE = IMAGE_DIR + "/test_{}_im.h5"
FMT_TRAIN_MASK_STORE = IMAGE_DIR + "/train_{}_mask.h5"
FMT_TRAIN_MUL_STORE = IMAGE_DIR + "/train_{}_mul.h5"
FMT_TEST_MUL_STORE = IMAGE_DIR + "/test_{}_mul.h5"
FMT_MULMEAN = IMAGE_DIR + "/{}_mulmean.h5"
# ---------------------------------------------------------
# Model files
MODEL_DIR = "/data/working/models/{}".format(MODEL_NAME)
FMT_VALMODEL_PATH = MODEL_DIR + "/{}_val_weights.h5"
FMT_FULLMODEL_PATH = MODEL_DIR + "/{}_full_weights.h5"
FMT_VALMODEL_HIST = MODEL_DIR + "/{}_val_hist.csv"
FMT_VALMODEL_EVALHIST = MODEL_DIR + "/{}_val_evalhist.csv"
FMT_VALMODEL_EVALTHHIST = MODEL_DIR + "/{}_val_evalhist_th.csv"
# ---------------------------------------------------------
# Prediction & polygon result
FMT_TESTPRED_PATH = MODEL_DIR + "/{}_pred.h5"
FMT_VALTESTPRED_PATH = MODEL_DIR + "/{}_eval_pred.h5"
FMT_VALTESTPOLY_PATH = MODEL_DIR + "/{}_eval_poly.csv"
FMT_VALTESTLINE_PATH = MODEL_DIR + "/{}_eval_line.csv"
FMT_VALTESTTRUTH_PATH = MODEL_DIR + "/{}_eval_poly_truth.csv"
FMT_VALTESTTRUTHLINE_PATH = MODEL_DIR + "/{}_eval_line_truth.csv"
FMT_VALTESTPOLY_OVALL_PATH = MODEL_DIR + "/eval_poly.csv"
FMT_VALTESTLINE_OVALL_PATH = MODEL_DIR + "/eval_line.csv"
FMT_VALTESTTRUTH_OVALL_PATH = MODEL_DIR + "/eval_poly_truth.csv"
FMT_TESTPOLY_PATH = MODEL_DIR + "/{}_poly.csv"
FMT_TESTLINE_PATH = MODEL_DIR + "/{}_line.csv"
FN_SOLUTION_CSV = "data/output/{}.csv".format(MODEL_NAME)
# ---------------------------------------------------------
# Model related files (others)
FMT_VALMODEL_LAST_PATH = MODEL_DIR + "/{}_val_weights_last.h5"
FMT_FULLMODEL_LAST_PATH = MODEL_DIR + "/{}_full_weights_last.h5"
# ---------------------------------------------------------
# warnins and logging
warnings.simplefilter("ignore", UserWarning)
handler = StreamHandler()
handler.setLevel(INFO)
handler.setFormatter(Formatter('%(asctime)s %(levelname)s %(message)s'))
fh_handler = FileHandler(".{}.log".format(MODEL_NAME))
fh_handler.setFormatter(Formatter('%(asctime)s %(levelname)s %(message)s'))
logger = getLogger(__name__)
logger.setLevel(INFO)
if __name__ == '__main__':
logger.addHandler(handler)
logger.addHandler(fh_handler)
# Fix seed for reproducibility
np.random.seed(1145141919)
def directory_name_to_area_id(datapath):
"""
Directory name to AOI number
Usage:
>>> directory_name_to_area_id("/data/test/AOI_2_Vegas")
2
"""
dir_name = Path(datapath).name
if dir_name.startswith('AOI_2_Vegas'):
return 2
elif dir_name.startswith('AOI_3_Paris'):
return 3
elif dir_name.startswith('AOI_4_Shanghai'):
return 4
elif dir_name.startswith('AOI_5_Khartoum'):
return 5
else:
raise RuntimeError("Unsupported city id is given.")
# def _remove_interiors(line):
# if "), (" in line:
# line_prefix = line.split('), (')[0]
# line_terminate = line.split('))",')[-1]
# line = (
# line_prefix +
# '))",' +
# line_terminate
# )
# return line
# def _calc_fscore_per_aoi(area_id):
# prefix = area_id_to_prefix(area_id)
# truth_file = FMT_VALTESTTRUTH_PATH.format(prefix)
# poly_file = FMT_VALTESTPOLY_PATH.format(prefix)
#
# cmd = [
# 'java',
# '-jar',
# '/root/visualizer-2.0/visualizer.jar',
# '-truth',
# truth_file,
# '-solution',
# poly_file,
# '-no-gui',
# '-band-triplets',
# '/root/visualizer-2.0/data/band-triplets.txt',
# '-image-dir',
# 'pass',
# ]
# proc = subprocess.Popen(
# cmd,
# stdout=subprocess.PIPE,
# stderr=subprocess.PIPE,
# )
# stdout_data, stderr_data = proc.communicate()
# lines = [line for line in stdout_data.decode('utf8').split('\n')[-10:]]
#
# """
# Overall F-score : 0.85029
#
# AOI_2_Vegas:
# TP : 27827
# FP : 4999
# FN : 4800
# Precision: 0.847712
# Recall : 0.852883
# F-score : 0.85029
# """
#
# if stdout_data.decode('utf8').strip().endswith("Overall F-score : 0"):
# overall_fscore = 0
# tp = 0
# fp = 0
# fn = 0
# precision = 0
# recall = 0
# fscore = 0
#
# elif len(lines) > 0 and lines[0].startswith("Overall F-score : "):
# assert lines[0].startswith("Overall F-score : ")
# assert lines[2].startswith("AOI_")
# assert lines[3].strip().startswith("TP")
# assert lines[4].strip().startswith("FP")
# assert lines[5].strip().startswith("FN")
# assert lines[6].strip().startswith("Precision")
# assert lines[7].strip().startswith("Recall")
# assert lines[8].strip().startswith("F-score")
#
# overall_fscore = float(re.findall("([\d\.]+)", lines[0])[0])
# tp = int(re.findall("(\d+)", lines[3])[0])
# fp = int(re.findall("(\d+)", lines[4])[0])
# fn = int(re.findall("(\d+)", lines[5])[0])
# precision = float(re.findall("([\d\.]+)", lines[6])[0])
# recall = float(re.findall("([\d\.]+)", lines[7])[0])
# fscore = float(re.findall("([\d\.]+)", lines[8])[0])
# else:
# logger.warn("Unexpected data >>> " + stdout_data.decode('utf8'))
# raise RuntimeError("Unsupported format")
#
# return {
# 'overall_fscore': overall_fscore,
# 'tp': tp,
# 'fp': fp,
# 'fn': fn,
# 'precision': precision,
# 'recall': recall,
# 'fscore': fscore,
# }
def prefix_to_area_id(prefix):
area_dict = {
'AOI_1_Rio': 1,
'AOI_2_Vegas': 2,
'AOI_3_Paris': 3,
'AOI_4_Shanghai': 4,
'AOI_5_Khartoum': 5,
}
return area_dict[area_id]
def area_id_to_prefix(area_id):
"""
area_id から prefix を返す
"""
area_dict = {
1: 'AOI_1_Rio',
2: 'AOI_2_Vegas',
3: 'AOI_3_Paris',
4: 'AOI_4_Shanghai',
5: 'AOI_5_Khartoum',
}
return area_dict[area_id]
# ---------------------------------------------------------
# mask2linestring functions:
# Generates the lists of coordinate alterations needed to search around a candidate pixel
# up to a certain spacing away from the candidate pixel
def grid(spacing):
search = []
for r in range(-spacing, spacing+1, 1):
for c in range(-spacing, spacing+1, 1):
if r == -spacing or r == spacing or c == -spacing or c == spacing:
search.append((r, c))
return search
# From the current pixel, follow along the white pixels and add those pixels to a line
# If multiple paths appear, create a new job
def follow(jobs, image, old_location):
# Create "linestring"
linestring = []
old_direction = -1
# Follow the line while there are still pixels
done = False
while not done:
found = 0
row = old_location[0]
column = old_location[1]
# Add the current pixel to the linestring
linestring.append(old_location)
# Search 1, 2, etc. pixels away until a pixel is found or the limit is reached
for reach, search in enumerate(searches):
# Look at the 8 pixels around the center
for direction, pixel in enumerate(search):
r1 = pixel[0]
c1 = pixel[1]
# If the search goes outside the bounds
if row+r1 < 0 or row+r1 > len(image)-1 or column+c1 < 0 or column+c1 > len(image[0])-1:
continue
# If the pixel looked at is white
if image[row+r1][column+c1] == white:
found += 1
# If the search is looking 1 pixel away, check direction
if reach == 0:
new_direction = direction
# Otherwise, assume a direction change
else:
new_direction = -1
# If this is the first pixel found
if found == 1:
# If the direction of travel has not changed
if old_direction == new_direction:
# Replace the last pixel in the linestring
linestring.pop()
old_direction = new_direction
# Select new pixel to investigate
new_location = (row+r1, column+c1)
# Black out the current pixel
row = old_location[0]
column = old_location[1]
image[row][column] = black
# If another pixel is found
else:
# Add another job to search for that linestring
job = (image, old_location)
jobs.put(job)
# If a pixel is found at this search level, stop searching
if found > 0:
break
# If no surrounding pixels were white
if found == 0:
done = True
# Black out the current pixel
row = old_location[0]
column = old_location[1]
image[row][column] = black
# Update the pixel to investigate if there is one
if not done:
old_location = new_location
return linestring
# Given a skeletonized image, finds the linestrings that define it
# If the linestrings have gaps in them less than or equal to spacing, they still count
def skeleton2linestrings(image, spacing):
linestrings = []
# Iterate over all pixels
for row in range(len(image)):
for column in range(len(image[0])):
# If the pixel is white
if image[row][column] == white:
# Create empty queue of jobs
jobs = queue.Queue()
# Add this pixel to the jobs queue
old_location = (row, column)
job = (image, old_location)
jobs.put(job)
while not jobs.empty():
job = jobs.get()
linestring = follow(jobs, job[0], job[1])
# Remove all the linestrings that are just a single point
if len(linestring) > 1:
linestrings.append(linestring)
return linestrings
from skimage.morphology import dilation, closing, erosion
from skimage.morphology import disk
def mask2linestrings(image, spacing, image_id):
disk_size = 20
select = disk(disk_size)
# Dilation
image = dilation(image, select)
# Skeletonize the image
skeletonized = morphology.medial_axis(image)
skeletonized = skeletonized.astype(np.uint8)
skeletonized *= 255
# Find the linestrings from the image
linestrings = skeleton2linestrings(skeletonized, spacing)
return linestrings
def write_csv_predict(images, image_ids, spacing, csv_filename):
with open(csv_filename, 'w') as csv_predict:
csv_predict.write("ImageId,WKT_Pix\n")
for image, image_id in zip(images, image_ids):
binary_image = image
binary_image = np.swapaxes(binary_image, 0, 2)
binary_image = np.swapaxes(binary_image, 0, 1)
binary_image = ski_transform.resize(binary_image, (1300,1300))
binary_image = (binary_image > 0.5).astype(np.uint8)
binary_image = np.swapaxes(binary_image, 0, 2)
binary_image = np.swapaxes(binary_image, 1, 2)
binary_image = np.squeeze(binary_image)
cv2.imwrite("/data/output/outputImages/withDilation/{}.tif".format(image_id),binary_image)
linestrings = mask2linestrings(binary_image, spacing, image_id)
if len(linestrings) == 0:
lines = ["{},LINESTRING EMPTY".format(image_id)]
else:
lines = []
for linestring in linestrings:
line = "{},\"LINESTRING (".format(image_id)
for i, coordinate in enumerate(linestring):
#line += "{} {}".format((coordinate[1]/256.0)*1300, (coordinate[0]/256.0)*1300)
line += "{} {}".format(coordinate[1], coordinate[0])
if i != (len(linestring)-1):
line += ", "
else:
line += ")\""
lines.append(line)
for line in lines:
csv_predict.write(line+"\n")
# ---------------------------------------------------------
# main
# def _get_model_parameter(area_id):
# prefix = area_id_to_prefix(area_id)
# fn_hist = FMT_VALMODEL_EVALTHHIST.format(prefix)
# best_row = pd.read_csv(fn_hist).sort_values(
# by='fscore',
# ascending=False,
# ).iloc[0]
#
# param = dict(
# fn_epoch=int(best_row['zero_base_epoch']),
# min_poly_area=int(best_row['min_area_th']),
# )
# return param
# def _internal_test_predict_best_param(area_id,
# save_pred=True):
# prefix = area_id_to_prefix(area_id)
# param = _get_model_parameter(area_id)
# epoch = param['fn_epoch']
# min_th = param['min_poly_area']
#
# # Prediction phase
# logger.info("Prediction phase: {}".format(prefix))
#
# X_mean = get_mul_mean_image(area_id)
#
# # Load model weights
# # Predict and Save prediction result
# fn = FMT_TESTPRED_PATH.format(prefix)
# fn_model = FMT_VALMODEL_PATH.format(prefix + '_{epoch:02d}')
# fn_model = fn_model.format(epoch=epoch)
# model = get_unet()
# model.load_weights(fn_model)
#
# fn_test = FMT_TEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
#
# y_pred = model.predict_generator(
# generate_test_batch(
# area_id,
# batch_size=64,
# immean=X_mean,
# enable_tqdm=True,
# ),
# val_samples=len(df_test) * 9,
# )
# del model
#
# # Save prediction result
# if save_pred:
# with tb.open_file(fn, 'w') as f:
# atom = tb.Atom.from_dtype(y_pred.dtype)
# filters = tb.Filters(complib='blosc', complevel=9)
# ds = f.create_carray(f.root, 'pred', atom, y_pred.shape,
# filters=filters)
# ds[:] = y_pred
#
# return y_pred
def _internal_test_2(area_id):
prefix = area_id_to_prefix(area_id)
save_pred=True
epoch = 9
# Prediction phase
logger.info("Prediction phase: {}".format(prefix))
X_mean = get_mul_mean_image(area_id)
# Predict and Save prediction result
fn = FMT_TESTPRED_PATH.format(prefix)
#fn_model = FMT_VALMODEL_PATH.format(prefix + '_{epoch:02d}')
#fn_model = fn_model.format(epoch=epoch)
if os.path.isfile(FMT_VALMODEL_LAST_PATH.format(prefix)):
fn_model = FMT_VALMODEL_LAST_PATH.format(prefix)
elif os.path.isfile(FMT_VALMODEL_PATH.format(prefix + '_{epoch:02d}')):
fn_model = FMT_VALMODEL_PATH.format(prefix + '_{epoch:02d}')
fn_model = fn_model.format(epoch=epoch)
else:
print("ERROR: Trained model not found.")
exit(1)
model = get_unet()
model.load_weights(fn_model)
fn_test = FMT_TEST_IMAGELIST_PATH.format(prefix=prefix)
df_test = pd.read_csv(fn_test, index_col='ImageId')
y_pred = model.predict_generator(
generate_test_batch(
area_id,
batch_size=64,
immean=X_mean,
enable_tqdm=True,
),
val_samples=len(df_test)
)
del model
# Save prediction result in a dataframe
if save_pred:
with tb.open_file(fn, 'w') as f:
atom = tb.Atom.from_dtype(y_pred.dtype)
filters = tb.Filters(complib='blosc', complevel=9)
ds = f.create_carray(f.root, 'pred', atom, y_pred.shape,
filters=filters)
ds[:] = y_pred
image_ids = df_test.index.tolist()
spacing = 1
#time_now = time.strftime("%Y%m%d-%H%M%S")
#fn_out = FMT_TESTLINE_PATH.format(prefix +'_'+ time_now +'_')
fn_out = FMT_TESTLINE_PATH.format(prefix)
write_csv_predict(y_pred, image_ids, spacing, fn_out)
# def _internal_test(area_id):
# prefix = area_id_to_prefix(area_id)
# y_pred = _internal_test_predict_best_param(area_id, save_pred=False)
#
# fn_test = FMT_TEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
# image_ids = df_test.index.tolist()
# spacing = 1
#
# fn_out = FMT_TESTPOLY_PATH.format(prefix)
#
# write_csv_predict(y_pred, image_ids, spacing, fn_out)
#
# """
# # Postprocessing phase
# logger.info("Postprocessing phase")
# # if not Path(FMT_VALTESTPOLY_PATH.format(prefix)).exists():
# fn_test = FMT_TEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
# fn = FMT_TESTPRED_PATH.format(prefix)
# with tb.open_file(fn, 'r') as f:
# y_pred = np.array(f.get_node('/pred'))
#
# fn_out = FMT_TESTPOLY_PATH.format(prefix)
# with open(fn_out, 'w') as f:
# f.write("ImageId,WKT_Pix\n")
# for idx, image_id in enumerate(df_test.index.tolist()):
# pred_values = np.zeros((1300, 1300))
# pred_count = np.zeros((1300, 1300))
# for slice_pos in range(9):
# slice_idx = idx * 9 + slice_pos
#
# pos_j = int(math.floor(slice_pos / 3.0))
# pos_i = int(slice_pos % 3)
# x0 = STRIDE_SZ * pos_i
# y0 = STRIDE_SZ * pos_j
# pred_values[x0:x0+INPUT_SIZE, y0:y0+INPUT_SIZE] += (
# y_pred[slice_idx][0]
# )
# pred_count[x0:x0+INPUT_SIZE, y0:y0+INPUT_SIZE] += 1
# pred_values = pred_values / pred_count
#
# linstrings = mask2linestrings(pred_values, spacing)
# if len(linstrings) > 0:
# for i, row in linstrings.iterrows():
# line = "{},{}\n".format(
# image_id,
# row.wkt)
# f.write(line)
# else:
# f.write("{},{},{},0\n".format(
# image_id,
# -1,
# "EMPTY"))
# """
# def _internal_validate_predict_best_param(area_id,
# enable_tqdm=False):
# """
# best param で valtest の prediction proba を return する
# y_pred は保存しない
#
# (used from ensemble model)
# """
# param = _get_model_parameter(area_id)
# epoch = param['fn_epoch']
# y_pred = _internal_validate_predict(
# area_id,
# epoch=epoch,
# save_pred=False,
# enable_tqdm=enable_tqdm)
#
# return y_pred
# def _internal_validate_predict(area_id,
# epoch=3,
# save_pred=True,
# enable_tqdm=False):
# prefix = area_id_to_prefix(area_id)
# X_mean = get_mul_mean_image(area_id)
#
# # Load model weights
# # Predict and Save prediction result
# fn_model = FMT_VALMODEL_PATH.format(prefix + '_{epoch:02d}')
# fn_model = fn_model.format(epoch=epoch)
# model = get_unet()
# model.load_weights(fn_model)
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
#
# y_pred = model.predict_generator(
# generate_valtest_batch(
# area_id,
# batch_size=64,
# immean=X_mean,
# enable_tqdm=enable_tqdm,
# ),
# val_samples=len(df_test) * 9,
# )
# del model
#
# # Save prediction result
# if save_pred:
# fn = FMT_VALTESTPRED_PATH.format(prefix)
# with tb.open_file(fn, 'w') as f:
# atom = tb.Atom.from_dtype(y_pred.dtype)
# filters = tb.Filters(complib='blosc', complevel=9)
# ds = f.create_carray(f.root,
# 'pred',
# atom,
# y_pred.shape,
# filters=filters)
# ds[:] = y_pred
# return y_pred
# def _internal_validate_fscore_wo_pred_file(area_id,
# epoch=3,
# min_th=MIN_POLYGON_AREA,
# enable_tqdm=False):
# prefix = area_id_to_prefix(area_id)
#
# # Prediction phase
# logger.info("Prediction phase")
# y_pred = _internal_validate_predict(
# area_id,
# save_pred=False,
# epoch=epoch,
# enable_tqdm=enable_tqdm)
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
# image_ids = df_test.index.tolist()
# spacing = 1
#
# fn_out = FMT_VALTESTPOLY_PATH.format(prefix)
#
# write_csv_predict(y_pred, image_ids, spacing, fn_out)
#
# """
# # Postprocessing phase
# logger.info("Postprocessing phase")
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
#
# fn_out = FMT_VALTESTPOLY_PATH.format(prefix)
# with open(fn_out, 'w') as f:
# f.write("ImageId,WKT_Pix\n")
# test_list = df_test.index.tolist()
# iterator = enumerate(test_list)
#
# for idx, image_id in tqdm.tqdm(iterator, total=len(test_list)):
# pred_values = np.zeros((1300, 1300))
# pred_count = np.zeros((1300, 1300))
# for slice_pos in range(9):
# slice_idx = idx * 9 + slice_pos
#
# pos_j = int(math.floor(slice_pos / 3.0))
# pos_i = int(slice_pos % 3)
# x0 = STRIDE_SZ * pos_i
# y0 = STRIDE_SZ * pos_j
# pred_values[x0:x0+INPUT_SIZE, y0:y0+INPUT_SIZE] += (
# y_pred[slice_idx][0]
# )
# pred_count[x0:x0+INPUT_SIZE, y0:y0+INPUT_SIZE] += 1
# pred_values = pred_values / pred_count
#
# linstrings = mask2linestrings(pred_values, spacing)
# if len(linstrings) > 0:
# for i, row in linstrings.iterrows():
# line = "{},{}\n".format(
# image_id,
# row.wkt)
# f.write(line)
# else:
# f.write("{},{},{},0\n".format(
# image_id,
# -1,
# "EMPTY"))
# """
#
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test)
# image_ids = df_test.ImageId.unique()
# spacing = 1
#
# fn_out = FMT_VALTESTTRUTH_PATH.format(prefix)
#
# write_csv_predict(y_pred, image_ids, spacing, fn_out)
#
# """
# # ------------------------
# # Validation solution file
# logger.info("Validation solution file")
# fn_true = FMT_TRAIN_SUMMARY_PATH.format(prefix=prefix)
# df_true = pd.read_csv(fn_true)
# # # Remove prefix "PAN_"
# # df_true.loc[:, 'ImageId'] = df_true.ImageId.str[4:]
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test)
# df_test_image_ids = df_test.ImageId.unique()
#
# fn_out = FMT_VALTESTTRUTH_PATH.format(prefix)
# with open(fn_out, 'w') as f:
# f.write("ImageId,WKT_Pix\n")
# df_true = df_true[df_true.ImageId.isin(df_test_image_ids)]
# for idx, r in df_true.iterrows():
# f.write("{},{},\"{}\",{:.6f}\n".format(
# r.ImageId,
# r.BuildingId,
# r.WKT_Pix,
# 1.0))
# """
# def _internal_validate_fscore(area_id,
# epoch=3,
# predict=True,
# min_th=MIN_POLYGON_AREA,
# enable_tqdm=False):
# prefix = area_id_to_prefix(area_id)
#
# # Prediction phase
# logger.info("Prediction phase")
# if predict:
# _internal_validate_predict(
# area_id,
# epoch=epoch,
# enable_tqdm=enable_tqdm)
#
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
# image_ids = df_test.index.tolist()
# spacing = 1
#
# fn_out = FMT_VALTESTPOLY_PATH.format(prefix)
#
# write_csv_predict(y_pred, image_ids, spacing, fn_out)
#
# """
# # Postprocessing phase
# logger.info("Postprocessing phase")
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test, index_col='ImageId')
# fn = FMT_VALTESTPRED_PATH.format(prefix)
# with tb.open_file(fn, 'r') as f:
# y_pred = np.array(f.get_node('/pred'))
#
# fn_out = FMT_VALTESTPOLY_PATH.format(prefix)
# with open(fn_out, 'w') as f:
# f.write("ImageId,WKT_Pix\n")
# test_list = df_test.index.tolist()
# iterator = enumerate(test_list)
#
# for idx, image_id in tqdm.tqdm(iterator, total=len(test_list)):
# pred_values = np.zeros((1300, 1300))
# pred_count = np.zeros((1300, 1300))
# for slice_pos in range(9):
# slice_idx = idx * 9 + slice_pos
#
# pos_j = int(math.floor(slice_pos / 3.0))
# pos_i = int(slice_pos % 3)
# x0 = STRIDE_SZ * pos_i
# y0 = STRIDE_SZ * pos_j
# pred_values[x0:x0+INPUT_SIZE, y0:y0+INPUT_SIZE] += (
# y_pred[slice_idx][0]
# )
# pred_count[x0:x0+INPUT_SIZE, y0:y0+INPUT_SIZE] += 1
# pred_values = pred_values / pred_count
#
# linstrings = mask2linestrings(pred_values, spacing)
# if len(linstrings) > 0:
# for i, row in linstrings.iterrows():
# line = "{},{}\n".format(
# image_id,
# row.wkt)
# f.write(line)
# else:
# f.write("{},{},{},0\n".format(
# image_id,
# -1,
# "EMPTY"))
#
# """
#
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test)
# image_ids = df_test.ImageId.unique()
# spacing = 1
#
# fn_out = FMT_VALTESTTRUTH_PATH.format(prefix)
#
# write_csv_predict(y_pred, image_ids, spacing, fn_out)
#
# """
# # ------------------------
# # Validation solution file
# logger.info("Validation solution file")
# # if not Path(FMT_VALTESTTRUTH_PATH.format(prefix)).exists():
# if True:
# fn_true = FMT_TRAIN_SUMMARY_PATH.format(prefix=prefix)
# df_true = pd.read_csv(fn_true)
# # # Remove prefix "PAN_"
# # df_true.loc[:, 'ImageId'] = df_true.ImageId.str[4:]
#
# fn_test = FMT_VALTEST_IMAGELIST_PATH.format(prefix=prefix)
# df_test = pd.read_csv(fn_test)
# df_test_image_ids = df_test.ImageId.unique()
#
# fn_out = FMT_VALTESTTRUTH_PATH.format(prefix)
# with open(fn_out, 'w') as f:
# f.write("ImageId,WKT_Pix\n")
# df_true = df_true[df_true.ImageId.isin(df_test_image_ids)]
# for idx, r in df_true.iterrows():
# f.write("{},\"{}\",{:.6f}\n".format(
# r.ImageId,
# r.WKT_Pix,
# 1.0))
# """
# def mask_to_poly(mask, min_polygon_area_th=MIN_POLYGON_AREA):
# mask = (mask > 0.5).astype(np.uint8)
# shapes = rasterio.features.shapes(mask.astype(np.int16), mask > 0)
# poly_list = []
# mp = shapely.ops.cascaded_union(
# shapely.geometry.MultiPolygon([
# shapely.geometry.shape(shape)
# for shape, value in shapes
# ]))
#
# if isinstance(mp, shapely.geometry.Polygon):
# df = pd.DataFrame({
# 'area_size': [mp.area],
# 'poly': [mp],
# })
# else:
# df = pd.DataFrame({
# 'area_size': [p.area for p in mp],
# 'poly': [p for p in mp],
# })
#
# df = df[df.area_size > min_polygon_area_th].sort_values(
# by='area_size', ascending=False)
# df.loc[:, 'wkt'] = df.poly.apply(lambda x: shapely.wkt.dumps(
# x, rounding_precision=0))
# df.loc[:, 'bid'] = list(range(1, len(df) + 1))
# df.loc[:, 'area_ratio'] = df.area_size / df.area_size.max()
# return df
def jaccard_coef(y_true, y_pred):
## Used in the unet code
smooth = 1e-12
intersection = K.sum(y_true * y_pred, axis=[0, -1, -2])
sum_ = K.sum(y_true + y_pred, axis=[0, -1, -2])
jac = (intersection + smooth) / (sum_ - intersection + smooth)
return K.mean(jac)
def jaccard_coef_int(y_true, y_pred):
## Used in the unet code
smooth = 1e-12
y_pred_pos = K.round(K.clip(y_pred, 0, 1))
intersection = K.sum(y_true * y_pred_pos, axis=[0, -1, -2])
sum_ = K.sum(y_true + y_pred_pos, axis=[0, -1, -2])
jac = (intersection + smooth) / (sum_ - intersection + smooth)
return K.mean(jac)
def generate_test_batch(area_id,
batch_size=64,
immean=None,
enable_tqdm=False):
## Used in the test function
prefix = area_id_to_prefix(area_id)