-
Notifications
You must be signed in to change notification settings - Fork 0
/
dedomena.py
1510 lines (985 loc) · 52.5 KB
/
dedomena.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
# -*- coding: utf-8 -*-
"""DEDOMENA.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zAHGgXLAB0LQy-WC-TaBP_U7PDOKU31c
# **FINAL_SUBMISSION**
**THE CHALLANGE**
Help find ways to improve the performance of machine learning and predictive models by filling in gaps in the datasets prior to model training.
ANATOMY OF THE CHALLANGE:
DO WHAT?
Improve performance of Machine Learning (ML) models by collecting a complete and continuous sensor data stream.
WHY DID IT HAPPEN?
* Sensor issues or signal noise due to experimental environment/setup
* Corrupted of data
* Loss of data during transmission (also due to limited bandwidth of transmission)
* Interference
* Limited amount of power for data collection and transmission
WHAT IT DOES?
* Limits the ability to train accurate ML models to predict features/characteristics in data, which in turn renders the data "useless"
* Hinders the collection of good-quality data silos
HOW TO SOLVE/OBJECTIVE?
* By "filling in" the missing datapoints in the datasets
* By "generating" the missing datapoints in the datasets
* By eliminating/removing the noisy/corrupted information that is embedded in individual datapoints
DO IT WHEN?
* Prior to training, i.e. during data cleaning and preprocessing.
We started by investigating the reasons behind data loss when the data is acquired through a sensor or sensor array. In addition, we also started doing research finding the reasons behind the loss.
Our research concluded that data loss in any dataset does not only occur due to missing data (be it discreet or continuous/timeseries) but also due to incomplete or corrupted or noisy collection of these data that are acquired by the sensors due to the reasons mentioned above.
---
HYPOTHESIS:
We propose an end-to-end Machine learning pipeline to -fill in the missing data using Generative modeling which involves using a model to generate new examples that plausibly come from an existing distribution of samples.
Stacked Denoising Autoencoder for when the sensor data is corrupted or there is a bit of noise in it, we call this type of data noisy data.
To obtain proper information about the data, we want Denoising.
We define our autoencoder to remove (if not all)most of the noise our data.
Transforms the input into a lower dimensional representation, and a decoder, which tries to reconstruct the original input from the lower dimensional representation. Therefore, these models present some some sort of “bottle neck” in the middle that forces the network to learn how to compress the data in a lower dimensional space. When training these algorithms, the objective is to be able to reconstruct the original input with the minimum amount of information loss. Once the model is trained, we can compress data at will by only using the encoder component of the autoencoder.
---
**(A)**
DETAILS:
One model is called the “generator” or “generative network” model that learns to generate new plausible samples. The other model is called the “discriminator” or “discriminative network” and learns to differentiate generated examples from real examples.
The two models are set up in a contest or a game (in a game theory sense) where the generator model seeks to fool the discriminator model, and the discriminator is provided with both examples of real and generated samples.
After training, the generative model can then be used to create new plausible samples on demand.
----
**(B)**
An autoencoder is a neural network used for dimensionality reduction; that is, for feature selection and extraction. Autoencoders with more hidden layers than inputs run the risk of learning the identity function – where the output simply equals the input – thereby becoming useless.
Denoising autoencoders are an extension of the basic autoencoder, and represent a stochastic version of it. Denoising autoencoders attempt to address identity-function risk by randomly corrupting input (i.e. introducing noise) that the autoencoder must then reconstruct, or denoise.
Stacked Denoising Autoencoder
A stacked denoising autoencoder is simply many denoising autoencoders strung together.
A key function of SDAs, and deep learning more generally, is unsupervised pre-training, layer by layer, as input is fed through. Once each layer is pre-trained to conduct feature selection and extraction on the input from the preceding layer, a second stage of supervised fine-tuning can follow.
A word on stochastic corruption in SDAs: Denoising autoencoders shuffle data around and learn about that data by attempting to reconstruct it. The act of shuffling is the noise, and the job of the network is to recognize the features within the noise that will allow it to classify the input. When a network is being trained, it generates a model, and measures the distance between that model and the benchmark through a loss function. Its attempts to minimize the loss function involve resampling the shuffled inputs and re-reconstructing the data, until it finds those inputs which bring its model closest to what it has been told is true.
---
**(C)**
Encoder network: It translates the original high-dimension input into the latent low-dimensional code. The input size is larger than the output size.
Decoder network: The decoder network recovers the data from the code, likely with larger and larger output layers.
The encoder network essentially accomplishes the dimensionality reduction, just like how we would use Principal Component Analysis (PCA) or Matrix Factorization (MF) for. In addition, the autoencoder is explicitly optimized for the data reconstruction from the code.
---
**(D)**
Disentangled Variational autoencoders
The idea of Variational Autoencoder is actually less similar to all the autoencoder models above, but deeply rooted in the methods of variational bayesian and graphical model.
Instead of mapping the input into a fixed vector, we want to map it into a distribution.
If each variable in the inferred latent representation is only sensitive to one single generative factor and relatively invariant to other factors, we will say this representation is disentangled or factorized. One benefit that often comes with disentangled representation is good interpretability and easy generalization to a variety of tasks.
For example, a model trained on photos of human faces might capture the gentle, skin color, hair color, hair length, emotion, whether wearing a pair of glasses and many other relatively independent factors in separate dimensions. Such a disentangled representation is very beneficial to facial image generation.
https://lilianweng.github.io/lil-log/2018/08/12/from-autoencoder-to-beta-vae.html#beta-vae
# **Download NASA Satellite Images of the Earth (NASA MODIS)**
This function can download an entire history of any NASA image dataset that follow the GIBS RESTful API pattern of calls
**Sample call**: https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/2012-07-09/250m/6/13/36.jpg
**Pattern**: https://gibs.earthdata.nasa.gov/wmts/epsg{EPSG:Code}/best/{ProductName}/default/{Time}/{TileMatrixSet}/{ZoomLevel}/{TileRow}/{TileCol}.png
**GIBS API webpage**: https://wiki.earthdata.nasa.gov/display/GIBS/GIBS+API+for+Developers
"""
import requests
import shutil
import os
"""
This function can download an entire history of any NASA image dataset that follow the GIBS RESTful API pattern of calls
Sample call: https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/2012-07-09/250m/6/13/36.jpg
Pattern: https://gibs.earthdata.nasa.gov/wmts/epsg{EPSG:Code}/best/{ProductName}/default/{Time}/{TileMatrixSet}/{ZoomLevel}/{TileRow}/{TileCol}.png
"""
def download_MODIS_image(num_images, year, month, day, max_day, max_month, end_date):
# input parameters
# num_images: number of images to download (for this URL, don't go over 80)
# year: year when image was taken; e.g. 2019
# month: month when image was taken; e.g. 7
# day: day when image was taken; e.g. 12
# max_day: day of each month on which you want to stop and move on to the next month; e.g. 30
# max_month: month of each year on which you want to stop and move on to the next year; e.g. 12
# end_date: a data (string) on which you want to break the loop; e.g. ''2019-10-20
if month < 10 and day < 10:
date = str(year) + '-0' + str(month) + '-0' + str(day)
elif month < 10 and day >= 10:
date = str(year) + '-0' + str(month) + '-' + str(day)
elif month >= 10 and day < 10:
elif month >= 10 and day < 10:
date = str(year) + '-' + str(month) + '-0' + str(day)
else:
date = str(year) + '-' + str(month) + '-' + str(day)
#max_day = 30 # not going to take the data from 31st day of any month (future imoprovement)
#max_month = 12
image_num = 0
for m in range(month, max_month+1):
for d in range(day, max_day+1):
for i in range(num_images):
if date == end_date:
print('end date','end_date', ' reached')
break
image_id = i
#image_num = str(img_counter)
url = 'https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/' + date + '/250m/6/13/' + str(image_id) + '.jpg'
#Save file in local hard drive
filepath = 'D:\SpaceApps2019\Chasers_of_lost_data\downloads\images_modis_nasa\\'
filename = 'nasa_modis_image_' + date + '_' + str(image_num) + '.jpg'
full_filepath = filepath + filename
# Open the url image, set stream to True, this will return the stream content.
response = requests.get(url, stream=True)
# Open a local file with wb ( write binary ) permission.
local_file = open(full_filepath, 'wb')
# Set decode_content value to True, otherwise the downloaded image file's size will be zero.
response.raw.decode_content = True
# Copy the response stream raw data to local image file.
shutil.copyfileobj(response.raw, local_file)
# Remove the image url response object.
local_file.close()
del response
filesize = os.path.getsize(full_filepath)
if filesize > 428:
print('image #', 'image_num', 'downloaded')
else:
print('image #','image_num', 'is a zero sized file --> invalid image')
image_num += 1
#### MAIN ####
# Loop over dates in a month to download in larger batches
#num_images = 80
#day = 1
#month = 7
#year = 2019
#max_day = 30
#max_month = 9
#end_date = '2019-09-15'
#download_MODIS_image(num_images, year, month, day, max_day, max_month, end_date)
"""# **Image Completion with Deep Learning in TensorFlow**
Content-aware fill is a powerful tool designers and photographers use to fill in unwanted or missing parts of images. Image completion and inpainting are closely related technologies used to fill in missing or corrupted parts of images. There are many ways to do content-aware fill, image completion, and inpainting.
We use Semantic Image Inpainting with Deep Generative Models
"Semantic image inpainting is a challenging task where large missing regions have to be filled based on the available visual data. Existing methods which extract information from only a single image generally produce unsatisfactory results due to the lack of high level context. In this paper, we propose a novel method for semantic image inpainting, which generates the missing content by conditioning on the available data. Given a trained generative model, we search for the closest encoding of the corrupted image in the latent image manifold using our context and prior losses. This encoding is then passed through the generative model to infer the missing content. In our method, inference is possible irrespective of how the missing content is structured, while the state-of-the-art learning based method requires specific information about the holes in the training phase. Experiments show that the method successfully predicts information in large missing regions and achieves pixel-level photorealism, significantly outperforming the state-of-the-art methods."
---
---
---
---
---
---
---
---
---
---
# **Proof of Concept #1**
# **Filling up missing portions of NASA earth images with **
# **# Algorithm: Deep Convolutional Generative Adversarial Network (DCGAN)**
This is a modified version of a DCGAN tutorial that was originally developed to generate fake MNIST images. **We have modified the code to take a single, corrupted NASA earth image as input and repair it.**
The code is written using the [Keras Sequential API](https://www.tensorflow.org/guide/keras) with a `tf.GradientTape` training loop.
## What are GANs?
[Generative Adversarial Networks](https://arxiv.org/abs/1406.2661) (GANs) are one of the most interesting ideas in computer science today. Two models are trained simultaneously by an adversarial process. A *generator* ("the artist") learns to create images that look real, while a *discriminator* ("the art critic") learns to tell real images apart from fakes.
![A diagram of a generator and discriminator](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/images/gan1.png?raw=1)
During training, the *generator* progressively becomes better at creating images that look real, while the *discriminator* becomes better at telling them apart. The process reaches equilibrium when the *discriminator* can no longer distinguish real images from fakes.
![A second diagram of a generator and discriminator](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/images/gan2.png?raw=1)
### Import TensorFlow and other libraries
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# Commented out IPython magic to ensure Python compatibility.
try:
# %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
tf.__version__
# To generate GIFs
!pip install imageio
import glob
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
from tensorflow.keras import layers
import time
from IPython import display
"""### Load and prepare the dataset
You will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.
"""
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]
BUFFER_SIZE = 60000
BATCH_SIZE = 256
# Batch and shuffle the data
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
"""## Create the models
Both the generator and discriminator are defined using the [Keras Sequential API](https://www.tensorflow.org/guide/keras#sequential_model).
### The Generator
The generator uses `tf.keras.layers.Conv2DTranspose` (upsampling) layers to produce an image from a seed (random noise). It starts with a **`Dense` layer that takes this seed as input**, then **upsamples it several times until it reaches the desired image size** of 28x28x1. Notice the `tf.keras.layers.LeakyReLU` activation for each layer, except the output layer which uses tanh.
"""
def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size
model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 14, 14, 64)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 28, 28, 1)
return model
"""Use the (as yet untrained) generator to create an image."""
generator = make_generator_model()
noise = tf.random.normal([1, 100])
generated_image = generator(noise, training=False)
plt.imshow(generated_image[0, :, :, 0], cmap='gray')
"""### The Discriminator
The discriminator is a CNN-based image classifier.
"""
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Flatten())
model.add(layers.Dense(1))
return model
"""Use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images."""
discriminator = make_discriminator_model()
decision = discriminator(generated_image)
print (decision)
"""## Define the loss and optimizers
Define loss functions and optimizers for both models.
"""
# This method returns a helper function to compute cross entropy loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
"""### Discriminator loss
This method quantifies how well the discriminator is able to distinguish real images from fakes. It compares the discriminator's predictions on real images to an array of 1s, and the discriminator's predictions on fake (generated) images to an array of 0s.
"""
def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss
"""### Generator loss
The generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminators decisions on the generated images to an array of 1s.
"""
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
"""The discriminator and the generator optimizers are different since we will train two networks separately."""
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
"""### Save checkpoints
Save and restore models, which can be helpful in case a long running training task is interrupted.
"""
checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
discriminator_optimizer=discriminator_optimizer,
generator=generator,
discriminator=discriminator)
"""## Define the training loop"""
EPOCHS = 50
noise_dim = 100
num_examples_to_generate = 16
# We will reuse this seed overtime (so it's easier)
# to visualize progress in the animated GIF)
seed = tf.random.normal([num_examples_to_generate, noise_dim])
"""The training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator."""
# Notice the use of `tf.function`
# This annotation causes the function to be "compiled".
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for image_batch in dataset:
train_step(image_batch)
# Produce images for the GIF as we go
display.clear_output(wait=True)
generate_and_save_images(generator,
epoch + 1,
seed)
# Save the model every 15 epochs
if (epoch + 1) % 15 == 0:
checkpoint.save(file_prefix = checkpoint_prefix)
print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))
# Generate after the final epoch
display.clear_output(wait=True)
generate_and_save_images(generator,
epochs,
seed)
"""**Generate and save images**"""
def generate_and_save_images(model, epoch, test_input):
# Notice `training` is set to False.
# This is so all layers run in inference mode (batchnorm).
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
plt.axis('off')
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
"""## Train the model
Call the `train()` method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).
At the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one minute / epoch with the default settings on Colab.
"""
# Commented out IPython magic to ensure Python compatibility.
# %%time
# train(train_dataset, EPOCHS)
"""Restore the latest checkpoint."""
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
"""## Create a GIF"""
# Display a single image using the epoch number
def display_image(epoch_no):
return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))
display_image(EPOCHS)
"""---
---
---
---
---
---
---
---
---
---
# **Proof of Concept #2**
# **Cleaning up noisy/missing data from NASA datasets**
# **# Algorithm: Denoising Autoencoder**
**Denoising_autoencoders_NASA_earth_data**
https://colab.research.google.com/drive/1Sj_J9yKrNXkFQCBMcZAqF03MOJqUIt_N#forceEdit=true&sandboxMode=true
https://colab.research.google.com/drive/1Sj_J9yKrNXkFQCBMcZAqF03MOJqUIt_N
https://github.com/pilillo/img-notebooks
https://github.com/pilillo/img-notebooks/blob/master/Denoising_autoencoders.ipynb
"""
!pwd
cd Colab\ Notebooks
!ls
# mount google drive location where you saved a .zip archive of your folder that contains images; then unzip the file
from google.colab import drive
drive.mount('/content/drive')
# get RGB images from Google drive and store them as numpy array
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import glob
import math
import cv2
#filelist = glob.glob('Bulk/*.jpg')
#good_im = np.array([np.array(Image.open(fname).convert('LA')) for fname in filelist]) # Already converts to grayscale but has an extra dummy layer
filelist = glob.glob('Bulk/*.jpg')
data = []
for file in filelist:
img = cv2.imread(file)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
data.append(img_gray)
np.shape(data)
data_array = np.array(data)
data_array.shape, type(data_array)
plt.imshow(data_array[56,:,:])
# split the batch into training and test set: 80-20 partition
batch_size = len(data_array[:,0,0])
train_size = int(math.ceil(batch_size*0.8))
test_size = batch_size - train_size
x_train = data_array[0:train_size,:,:]
x_test = data_array[train_size:,:,:]
train_size, test_size
x_train.shape, x_test.shape
# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
import keras
#from keras.datasets import cifar10
#from keras.datasets import mnist
from matplotlib import pyplot
from matplotlib.pyplot import imshow
import numpy as np
# https://keras.io/datasets/#mnist-database-of-handwritten-digits
# load mnist in a grayscale format bunch of images
#(x_train, y_train), (x_test, y_test) = mnist.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
for i in range(0, 9):
pyplot.subplot(330 + 1 + i)
imshow(x_train[i])
imgplot = pyplot.imshow(x_train[i])
print "training set shape is", x_train.shape
#print y_train.shape
# since we deal with square images
image_size = x_train.shape[1]
# inspect the format of x and y
print "First image in the training set"
pyplot.imshow(x_train[0])
initial_seed = 1234
np.random.seed(initial_seed)
print np.amax(x_train)
# normalize the pixel values to have everything between 0 and 1
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# https://github.com/keras-team/keras/blob/master/examples/mnist_denoising_autoencoder.py
# https://blog.keras.io/building-autoencoders-in-keras.html
# x_train_ = np.reshape(x_train, [-1, image_size, image_size, 1])
x_train_ = np.reshape(x_train, (len(x_train), image_size, image_size, 1))
print "Reshaped train from", x_train.shape, "to", x_train_.shape
#x_test_ = np.reshape(x_test, [-1, image_size, image_size, 1])
x_test_ = np.reshape(x_test, (len(x_test), image_size, image_size, 1))
print "Reshaped test from", x_test.shape, "to", x_test_.shape
# Generate corrupted MNIST images by adding noise with normal dist
# centered at 0.5 and std=0.5
noise = np.random.normal(loc=0.5,
scale=0.5,
size=x_train_.shape)
print "x_train noise.shape", noise.shape
x_train_noisy = x_train_ + noise
noise = np.random.normal(loc=0.5,
scale=0.5,
size=x_test_.shape)
x_test_noisy = x_test_ + noise
print "x_test noise.shape", noise.shape
# make sure the data are in the [0,1] range by clipping lower and higher ones
# https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.clip.html
x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)
"""Let's see how noisy became the first training entry after adding the noise:"""
pyplot.imshow(
np.reshape(x_train_noisy[0], (1, image_size, image_size))[0]
)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD, rmsprop
from keras.layers.convolutional import Conv2D, MaxPooling2D, UpSampling2D
model = Sequential()
model.add(Conv2D(16, (3, 3),
input_shape=x_train_.shape[1:], # (28, 28)
activation='relu',
padding='same'))
model.add(MaxPooling2D((2, 2), padding="same"))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), padding="same"))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), padding="same"))
# ** encoded representation **
# at this point the representation is (4, 4, 8) i.e. 128-dimensional
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))
model.compile(optimizer='adadelta', loss='binary_crossentropy')
model.fit(x_train_noisy,
x_train_,
epochs=250,
batch_size=128,
shuffle=True,
validation_data=(x_test_noisy, x_test_))
# example prediction on the corrupted test images
decoded = model.predict(
# only predict the first element as example
np.reshape(x_test_noisy[0], (1, image_size, image_size, 1))
)
pyplot.imshow(
np.reshape(x_test_noisy[0], (1, image_size, image_size))[0]
)
pyplot.imshow(
np.reshape(decoded, (1, image_size, image_size))[0]
)
"""---
---
---
---
---
---
---
---
---
---
# **Proof of Concept #3**
# **NASA Meteorite Landing dataset: Recovering/approximating/imputing missing values**
# **# Algorithm: Deep Convolutional Generative Adversarial Network (DCGAN)**
# **Our approach**
Here, we are transforming each sample (row) of the Meteorite CSV dataset into an image. The dataset has 45716 rows and 9 columns, including metorites' names and IDs. Our algorithm transforms each row it into a 3x3 image and zero pads the outer periphery of the 3x3 matrix (to make it a 7x7 matrix) so that each row fits into a 2D Convolutional filter. Then, once the training and evaluation is complete, we plan to recover the original data (CSV) from the images generated by the DCGAN.
# **Challenges**
There are mainly 2 challenges that we faced (#1 and #2) while implementing this demo. #3 is our planned future work.
1. The dataset is probably not big enough for a regular Convolutional Neural Network (CNN)-based DCGAN architecture.
2. We had to encode all categorical values to numeric values, including the names. The problem here was our label encoder generated different numeric values for the meteorite names compared to their IDs. We chose not to exclude these two columns from the dataset for the sake of architectural simplicity at this moment.
# **Future work**
Due to time constraints, we are yet to recover the generated csv data from the output images and evaluate whether the algorithm converged or not. If it did not converge, then we plan to tune the hyperparameters, modify the CNN architecture if necessary and re-train the DCGAN algorithm.
### Import TensorFlow and other libraries
"""
# Commented out IPython magic to ensure Python compatibility.
from __future__ import absolute_import, division, print_function, unicode_literals
try:
# %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
tf.__version__
# To generate GIFs
!pip install imageio
import glob
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import time
from tensorflow.keras import layers
from sklearn import preprocessing
from sklearn.preprocessing import normalize
from sklearn.preprocessing import MinMaxScaler
from IPython import display
"""### Load and prepare NASA Meteorite dataset for **training**"""
##### Initialize training dataset #####
# mount google drive location where you saved a .zip archive of your folder that contains images; then unzip the file
from google.colab import drive
drive.mount('/content/drive')
cd /content/drive/My\ Drive/Colab\ Notebooks/NASA-challenge-sample-datasets/
"""**Load dataset and encode categorical values**"""
# Load dataset and encode categorical values
import pandas as pd
df = pd.read_csv('/content/drive/My Drive/Colab Notebooks/NASA-challenge-sample-datasets/Meteorite_Landings_clean.csv')
df_filled = df.fillna(0)
# Encode categorical values
label_enc = preprocessing.LabelEncoder()
data_clean = df_filled.apply(lambda series: pd.Series(label_enc.fit_transform(series), index=series.index))
#data_clean.to_csv('Meteorite_not_normalized.csv',index=True)
# Normalize numeric data only (range: 0-255)
first_2_col = data_clean[data_clean.columns[:2]]
minmax = MinMaxScaler(feature_range=(0, 255), copy=True)
data_norm_minmax = minmax.fit_transform(data_clean[['nametype', 'recclass', 'mass (g)', 'fall', 'year_numeric', 'reclat', 'reclong']])
#data_norm = normalize(data_clean[['nametype', 'recclass', 'mass (g)', 'fall', 'year_numeric', 'reclat', 'reclong']])
dataset_complete = np.hstack((first_2_col, data_norm_minmax))
#np.savetxt("Meteorite_clean_minmax.csv", dataset_complete, delimiter=",")
"""**Start zero padding the data so that it fits into a 2D Convolutional filter**"""
## Start zero padding the data so that it fits into a 2D Convolutional filter
zeros_vert = np.zeros((3, 2))
zeros_hori = np.zeros((2, 7))
zeros_vert.shape, zeros_hori.shape, dataset_complete.shape
# Rehsape data and pad zeros to increase dimensionality
dataset_intermed = dataset_complete.reshape(dataset_complete.shape[0], 3, 3).astype('float32')
dataset_intermed.shape
# Pad zeros horizontally
dataset_hor_pad = []
for i in range(dataset_intermed.shape[0]):
dataset_hor_pad_1 = np.hstack((zeros_vert, dataset_intermed[i,:,:], zeros_vert))
dataset_hor_pad.append(dataset_hor_pad_1)
dataset_hor_pad = np.array(dataset_hor_pad)
dataset_hor_pad_1.shape, dataset_hor_pad.shape
# Pad zeros vertically
dataset_ver_pad = []
for i in range(dataset_hor_pad.shape[0]):
dataset_ver_pad_1 = np.vstack((zeros_hori, dataset_hor_pad[i,:,:], zeros_hori))
dataset_ver_pad.append(dataset_ver_pad_1)
dataset_padded = np.array(dataset_ver_pad)
dataset_ver_pad_1.shape, dataset_padded.shape
dataset_padded[1111,:,:]
"""**Reshape training data, define batch and buffer sizes**"""
# Reshape training data, define batch and buffer sizes
dataset = dataset_padded.reshape(dataset_padded.shape[0], 7, 7, 1).astype('float32')
# Initialize buffer and batch size
BUFFER_SIZE = dataset_padded.shape[0]
BATCH_SIZE = 256
# BATCH and SHUFFLE the data
train_dataset = tf.data.Dataset.from_tensor_slices(dataset).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
dataset.shape
"""## Create the models
Both the generator and discriminator are defined using the [Keras Sequential API](https://www.tensorflow.org/guide/keras#sequential_model).
### The Generator
The generator uses `tf.keras.layers.Conv2DTranspose` (upsampling) layers to produce an image from a seed (random noise). It starts with a **`Dense` layer that takes this seed as input**, then **upsamples it several times until it reaches the desired image size** of 28x28x1. Notice the `tf.keras.layers.LeakyReLU` activation for each layer, except the output layer which uses tanh.
"""
# Create generator
def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size
model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(64, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 64)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(1, (5, 5), strides=(1, 1), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 7, 7, 1)
return model
"""**Use the (as yet untrained) generator to create an image.**"""
generator = make_generator_model()
noise = tf.random.normal([1, 100])
generated_image = generator(noise, training=False)
plt.imshow(generated_image[0, :, :, 0])
"""### The Discriminator
The discriminator is a CNN-based image classifier.
"""