-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathprogram42_TrainGANs.py
5347 lines (3755 loc) · 170 KB
/
program42_TrainGANs.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
from __future__ import print_function
from __future__ import absolute_import
import sys
import numpy
import sklearn
import numpy.random
import scipy.stats as ss
import os, tarfile, errno
import matplotlib.pyplot as plt
import tensorflow as tf
print(tf.__version__) # 1.14.0
# https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
# https://www.analyticsinsight.net/best-computer-vision-courses-to-master-in-2019/
# UCI data: https://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
# Human Activity Recognition Using Smartphones Data Set, archive.ics.uci.edu, Human Activity Recognition
# https://www.cfasociety.org/cleveland/Lists/Events%20Calendar/Attachments/1045/BIG-Data_AI-JPMmay2017.pdf
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
if sys.version_info >= (3, 0, 0):
import urllib.request as urllib
else:
import urllib
try:
from imageio import imsave
except:
from scipy.misc import imsave
print(sys.version_info) # we use: sys.version_info
from sklearn.ensemble import IsolationForest # Import IsolationForest module
# use: https://towardsdatascience.com/anomaly-detection-for-dummies-15f148e559c1
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import cv2
import numpy.random
import tensorflow as tf
import scipy.stats as ss
from sklearn import metrics
from sklearn.mixture import GaussianMixture
# use: https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
# https://www.analyticsinsight.net/best-computer-vision-courses-to-master-in-2019/
# www.cfasociety.org/cleveland/Lists/Events%20Calendar/Attachments/1045/BIG-Data_AI-JPMmay2017.pdf
import scipy
import matplotlib
import numpy as np
from scipy.misc import imshow
from scipy import ndimage, misc
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from gluoncv import data, utils
from gluoncv.data import ImageNet
from mxnet.gluon.data import DataLoader
from mxnet.gluon.data.vision import transforms
import scipy.io as sio
from matplotlib import pyplot as plt
import torch # use pytorch
from torchvision import datasets
import torchvision.transforms as transforms
# https://www.renom.jp/notebooks/tutorial/generative-model/anoGAN/notebook.html
# use: https://www.renom.jp/notebooks/tutorial/generative-model/anoGAN/notebook.html
import numpy as np
#import renom as rm
from copy import deepcopy
import matplotlib.pyplot as plt
import external.renom as rm
#from renom.optimizer import Adam
#from renom.cuda import set_cuda_active
from external.renom.optimizer import Adam
from external.renom.cuda import set_cuda_active
import numpy as np
import tensorflow as tf
from keras.layers import Dense
from keras.datasets import mnist
from keras.models import Sequential
# MNIST: Keras or scikit-learn embedded datasets
# Keras: from keras.datasets import mnist
ds = tf.contrib.distributions
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, BatchNormalization
from keras.callbacks import TensorBoard
from keras.callbacks import ModelCheckpoint
from keras.optimizers import adam
def load_minst_data():
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = (x_train.astype(np.float32) - 127.5) / 127.5
x_train = x_train.reshape(60000, 784)
return (x_train, y_train, x_test, y_test)
np.random.seed(10)
random_dim = 100
def get_generator(optimizer):
generator = Sequential()
generator.add(Dense(256, input_dim=random_dim, kernel_initializer=initializers.RandomNormal(stddev=0.02)))
generator.add(LeakyReLU(0.2))
generator.add(Dense(512))
generator.add(LeakyReLU(0.2))
generator.add(Dense(1024))
generator.add(LeakyReLU(0.2))
generator.add(Dense(784, activation='tanh'))
generator.compile(loss='binary_crossentropy', optimizer=optimizer)
return generator
def get_discriminator(optimizer):
discriminator = Sequential()
discriminator.add(Dense(1024, input_dim=784, kernel_initializer=initializers.RandomNormal(stddev=0.02)))
discriminator.add(LeakyReLU(0.2))
discriminator.add(Dropout(0.3))
discriminator.add(Dense(512))
discriminator.add(LeakyReLU(0.2))
discriminator.add(Dropout(0.3))
discriminator.add(Dense(256))
discriminator.add(LeakyReLU(0.2))
discriminator.add(Dropout(0.3))
discriminator.add(Dense(1, activation='sigmoid'))
discriminator.compile(loss='binary_crossentropy', optimizer=optimizer)
return discriminator
from keras.models import Model
from keras.layers import Input, Dense
def get_gan_network(discriminator, random_dim, generator, optimizer):
discriminator.trainable = False
gan_input = Input(shape=(random_dim,))
x = generator(gan_input)
gan_output = discriminator(x)
gan = Model(inputs=gan_input, outputs=gan_output)
gan.compile(loss='binary_crossentropy', optimizer=optimizer)
return gan
from tqdm import tqdm
from keras import optimizers
from keras import initializers
from keras.layers import LeakyReLU
def train(epochs=1, batch_size=128):
x_train, y_train, x_test, y_test = load_minst_data()
batch_count = x_train.shape[0] / batch_size
adam = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
generator = get_generator(adam)
discriminator = get_discriminator(adam)
gan = get_gan_network(discriminator, random_dim, generator, adam)
for e in range(1, epochs + 1):
print('-' * 15, 'Epoch %d' % e, '-' * 15)
for _ in tqdm(range(int(batch_count))):
noise = np.random.normal(0, 1, size=[batch_size, random_dim])
image_batch = x_train[np.random.randint(0, x_train.shape[0], size=batch_size)]
generated_images = generator.predict(noise)
X = np.concatenate([image_batch, generated_images])
y_dis = np.zeros(2 * batch_size)
y_dis[:batch_size] = 0.9
discriminator.trainable = True
discriminator.train_on_batch(X, y_dis)
noise = np.random.normal(0, 1, size=[batch_size, random_dim])
y_gen = np.ones(batch_size)
discriminator.trainable = False
gan.train_on_batch(noise, y_gen)
if e == 1 or e % 20 == 0:
plot_generated_images(e, generator)
train()
#def sample_mog(batch_size, n_mixture=8, std=0.01, radius=1.0):
def sample_mog(batch_size, n_mixture=6, std=0.03, radius=1.0):
#thetas = np.linspace(0, 2 * np.pi, n_mixture)
thetas = np.linspace(0, 2 * np.pi, n_mixture)
xs, ys = radius * np.sin(thetas), radius * np.cos(thetas)
cat = ds.Categorical(tf.zeros(n_mixture))
comps = [ds.MultivariateNormalDiag([xi, yi], [std, std]) for xi, yi in zip(xs.ravel(), ys.ravel())]
data = ds.Mixture(cat, comps)
return data.sample(batch_size)
print(sample_mog(128)) # sample_mog(128)
samplePoints = sample_mog(100)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./2DGaussianMixtures.png')
plt.show()
samplePoints = sample_mog(100, 7, 0.03, 0.7)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./2DGaussianMixtures2.png')
plt.show()
samplePoints = sample_mog(100, 9, 0.03, 0.7)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./2DGaussianMixtures3.png')
plt.show()
samplePoints = sample_mog(100, 4, 0.03, 0.7)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./2DGaussianMixtures4.png')
plt.show()
#def sample_mog2(batch_size, n_mixture=8, std=0.01, radius=1.0):
def sample_mog2(batch_size, n_mixture=6, std=0.03, radius=1.0):
#thetas = np.linspace(0, 2 * np.pi, n_mixture)
thetas = np.linspace(0, (radius*n_mixture/2)-1, n_mixture/2)
xs, ys = thetas, np.zeros(thetas.shape)
xs = np.concatenate((xs, thetas))
ys = np.concatenate((ys, np.ones(thetas.shape)))
cat = ds.Categorical(tf.zeros(n_mixture))
comps = [ds.MultivariateNormalDiag([xi, yi], [std, std]) for xi, yi in zip(xs.ravel(), ys.ravel())]
data = ds.Mixture(cat, comps)
return data.sample(batch_size)
#print(sample_mog2(128)) # sample_mog(128)
samplePoints = sample_mog2(100)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./GaussianMixtures.png')
plt.show()
#def sample_mog3(batch_size, n_mixture=8, std=0.01, radius=1.0):
def sample_mog3(batch_size, n_mixture=6, std=0.03, radius=1.0):
#thetas = np.linspace(0, 2 * np.pi, n_mixture)
thetas = np.linspace(0, (radius*n_mixture/3)-1, n_mixture/3)
xs, ys = thetas, np.zeros(thetas.shape)
xs = np.concatenate((xs, thetas))
ys = np.concatenate((ys, np.ones(thetas.shape)))
xs = np.concatenate((xs, thetas))
ys = np.concatenate((ys, 2*np.ones(thetas.shape)))
cat = ds.Categorical(tf.zeros(n_mixture))
comps = [ds.MultivariateNormalDiag([xi, yi], [std, std]) for xi, yi in zip(xs.ravel(), ys.ravel())]
data = ds.Mixture(cat, comps)
return data.sample(batch_size)
#print(sample_mog3(128)) # sample_mog(128)
samplePoints = sample_mog3(100)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./GaussianMixtures2.png')
plt.show()
samplePoints = sample_mog3(100, 9)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./GaussianMixtures3.png')
plt.show()
from keras.datasets.mnist import load_data
(x_train, y_train), (x_test, y_test) = load_data()
# summarize the shape of the dataset
print('MNIST Train', x_train.shape, y_train.shape)
print('MNIST Test', x_test.shape, y_test.shape)
from keras.datasets.fashion_mnist import load_data
(_, _), (x_fashion, y_fashion) = load_data()
# summarize the shape of the dataset
print('Fashion-MNIST Test', x_fashion.shape, y_fashion.shape)
print('')
num_workers = 0
batch_size = 128
transform = transforms.ToTensor()
train_data = datasets.MNIST(root='data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers)
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy()
img = np.squeeze(images[0])
fig = plt.figure(figsize = (3,3))
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray')
plt.show()
# https://runestone.academy/runestone/books/published/pythonds/index.html
# https://github.com/Garima13a/MNIST_GAN/blob/master/MNIST_GAN_Solution.ipynb
import torch.nn as nn
import torch.nn.functional as F
class Discriminator(nn.Module):
def __init__(self, input_size, hidden_dim, output_size):
super(Discriminator, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_dim * 4)
self.fc2 = nn.Linear(hidden_dim * 4, hidden_dim * 2)
self.fc3 = nn.Linear(hidden_dim * 2, hidden_dim)
self.fc4 = nn.Linear(hidden_dim, output_size)
self.dropout = nn.Dropout(0.3) # define dropout layer
def forward(self, x):
x = x.view(-1, 28 * 28)
x = F.leaky_relu(self.fc1(x), 0.2) # (input, negative_slope=0.2)
x = self.dropout(x)
x = F.leaky_relu(self.fc2(x), 0.2)
x = self.dropout(x)
x = F.leaky_relu(self.fc3(x), 0.2)
x = self.dropout(x)
out = self.fc4(x)
return out
class Generator(nn.Module):
def __init__(self, input_size, hidden_dim, output_size):
super(Generator, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim * 2)
self.fc3 = nn.Linear(hidden_dim * 2, hidden_dim * 4)
self.fc4 = nn.Linear(hidden_dim * 4, output_size)
self.dropout = nn.Dropout(0.3)
def forward(self, x):
x = F.leaky_relu(self.fc1(x), 0.2) # (input, negative_slope=0.2)
x = self.dropout(x)
x = F.leaky_relu(self.fc2(x), 0.2)
x = self.dropout(x)
x = F.leaky_relu(self.fc3(x), 0.2)
x = self.dropout(x)
out = F.tanh(self.fc4(x))
return out
# Discriminator
input_size = 784
d_output_size = 1
d_hidden_size = 32
z_size = 100 # For generator
g_output_size = 784
g_hidden_size = 32
# we now instantiate both the discriminator and the generator
D = Discriminator(input_size, d_hidden_size, d_output_size)
G = Generator(z_size, g_hidden_size, g_output_size)
print(D)
print(G)
# we calculate the losses
def real_loss(D_out, smooth=False):
batch_size = D_out.size(0)
if smooth:
labels = torch.ones(batch_size) * 0.9
else:
labels = torch.ones(batch_size) # real labels = 1
criterion = nn.BCEWithLogitsLoss()
loss = criterion(D_out.squeeze(), labels)
return loss
def fake_loss(D_out):
batch_size = D_out.size(0)
labels = torch.zeros(batch_size) # fake labels = 0
criterion = nn.BCEWithLogitsLoss()
loss = criterion(D_out.squeeze(), labels)
return loss
lr = 0.002
import torch.optim as optim
d_optimizer = optim.Adam(D.parameters(), lr)
g_optimizer = optim.Adam(G.parameters(), lr)
# sklearn.datasets.make_moons(n_samples=100, shuffle=True, noise=None, random_state=None)
# Use: sklearn.datasets.make_moons(n_samples=100, shuffle=True, noise=None, random_state=None)
# Make two interleaving half circles: A toy dataset to visualize clustering and classification algorithms.
# We now use: sklearn.datasets.make_moons(n_samples=100, shuffle=True, noise=None, random_state=None)
# Parameters: n_samples : int, optional (default=100). The total number of points generated.
# shuffle : bool, optional (default=True). Whether to shuffle the samples.
# noise : double or None (default=None). Standard deviation of Gaussian noise added to the data.
# random_state : int, RandomState instance or None (default)
# Determines random number generation for dataset shuffling and noise.
# Returns: X : array of shape [n_samples, 2]. The generated samples.
# y : array of shape [n_samples]. The integer labels (0 or 1) for class membership of each sample.
from sklearn import datasets as dsets
X_moon, y_moon = dsets.make_moons(n_samples=200, shuffle=True, noise=0.09)
print(X_moon.shape)
print(y_moon.shape)
plt.plot(X_moon[:,0], X_moon[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./HalfMoon_dataset.png')
plt.show()
# sklearn.datasets.make_swiss_roll(n_samples=100, noise=0.0, random_state=None)
X_swiss_roll, y_swiss_roll = dsets.make_swiss_roll(n_samples=200, noise=0.09)
print(X_swiss_roll.shape)
print(y_swiss_roll.shape)
import time
import matplotlib
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.ensemble import IsolationForest
from sklearn.covariance import EllipticEnvelope
from sklearn.neighbors import LocalOutlierFactor
from sklearn.datasets import make_moons, make_blobs
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
outliers_fraction = 0.15 # Example settings
n_samples = 300 # Set example settings
n_outliers = int(outliers_fraction * n_samples)
n_inliers = n_samples - n_outliers
# define the anomaly detection methods to be compared
# we define the anomaly detection methods to be compared
anomaly_algorithms = [("Robust covariance", EllipticEnvelope(contamination=outliers_fraction)),
("One-Class SVM", svm.OneClassSVM(nu=outliers_fraction, kernel="rbf", gamma=0.1)),
("Isolation Forest", IsolationForest(contamination=outliers_fraction, random_state=42)),
("Local Outlier Factor", LocalOutlierFactor(n_neighbors=35, contamination=outliers_fraction))]
# we now define the datasets
blobs_params = dict(random_state=0, n_samples=n_inliers, n_features=2)
datasets = [make_blobs(centers=[[0, 0], [0, 0]], cluster_std=0.5, **blobs_params)[0],
make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[0.5, 0.5], **blobs_params)[0],
make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[1.5, .3], **blobs_params)[0],
4. * (make_moons(n_samples=n_samples, noise=.05, random_state=0)[0] - np.array([0.5, 0.25])),
14. * (np.random.RandomState(42).rand(n_samples, 2) - 0.5)]
# compare the given classifiers under the given settings
xx, yy = np.meshgrid(np.linspace(-7, 7, 150), np.linspace(-7, 7, 150))
plt.figure(figsize=(len(anomaly_algorithms) * 2 + 3, 12.5))
plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05, hspace=.01)
plot_num = 1
rng = np.random.RandomState(42)
for i_dataset, X in enumerate(datasets): # Add the outliers
X = np.concatenate([X, rng.uniform(low=-6, high=6, size=(n_outliers, 2))], axis=0)
for name, algorithm in anomaly_algorithms:
t0 = time.time()
algorithm.fit(X)
t1 = time.time()
plt.subplot(len(datasets), len(anomaly_algorithms), plot_num)
if i_dataset == 0:
plt.title(name, size=18)
# fit the data and tag outliers
if name == "Local Outlier Factor":
y_pred = algorithm.fit_predict(X)
else:
y_pred = algorithm.fit(X).predict(X)
if name != "Local Outlier Factor": # the LOF does not implement predict
Z = algorithm.predict(np.c_[xx.ravel(), yy.ravel()]) # plot level lines and points
Z = Z.reshape(xx.shape)
plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='black')
colors = np.array(['#377eb8', '#ff7f00'])
plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[(y_pred + 1) // 2])
plt.xlim(-7, 7)
plt.ylim(-7, 7)
plt.xticks(())
plt.yticks(())
plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'),
transform=plt.gca().transAxes, size=15, horizontalalignment='right')
plot_num += 1
plt.savefig('./OoD_AnomalyDetection.png')
plt.show()
import numpy as np
import tensorflow as tf
ds = tf.contrib.distributions
# MNIST: Keras or scikit-learn embedded datasets
# For example, Keras: from keras.datasets import mnist
#def sample_mog(batch_size, n_mixture=8, std=0.01, radius=1.0):
def sample_mog(batch_size, n_mixture=6, std=0.03, radius=1.0):
#thetas = np.linspace(0, 2 * np.pi, n_mixture)
thetas = np.linspace(0, 2 * np.pi, n_mixture)
xs, ys = radius * np.sin(thetas), radius * np.cos(thetas)
cat = ds.Categorical(tf.zeros(n_mixture))
comps = [ds.MultivariateNormalDiag([xi, yi], [std, std]) for xi, yi in zip(xs.ravel(), ys.ravel())]
data = ds.Mixture(cat, comps)
return data.sample(batch_size)
print(sample_mog(128)) # sample_mog(128)
samplePoints = sample_mog(100)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./2Dmixtures.png')
plt.show()
samplePoints = sample_mog(100, 4, 0.03, 0.7)
print(samplePoints)
tf.InteractiveSession()
samplePoints2 = samplePoints.eval()
#plt.plot(samplePoints2[:,0], samplePoints2[:,1])
plt.plot(samplePoints2[:,0], samplePoints2[:,1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./2Dmixtures2.png')
plt.show()
image_ind = 10 # we define the index
#train_data = sio.loadmat('train_32x32.mat')
train_data = sio.loadmat('/Users/dionelisnikolaos/Downloads/train_32x32.mat')
# The SVHN Dataset
# Street View House Numbers (SVHN)
# we access the dict
x_train = train_data['X']
y_train = train_data['y']
plt.imshow(x_train[:,:,:,image_ind])
plt.show() # we show the sample
print(y_train[image_ind])
image_ind = 10 # index, we now define the image index
test_data = sio.loadmat('/Users/dionelisnikolaos/Downloads/test_32x32.mat')
x_test = test_data['X'] # access the dict
y_test = test_data['y'] # access to the dict
plt.imshow(x_test[:,:,:,image_ind])
plt.show() # show the sample
print(y_test[image_ind])
# Import Line2D for marking legend in graph
from matplotlib.lines import Line2D
mean = [0, 0] # we define the mean vector
cov = [[1, 0], [0, 100]] # diagonal covariance
import matplotlib.pyplot as plt
x, y = np.random.multivariate_normal(mean, cov, 1000).T
plt.plot(x, y, 'o')
plt.axis('equal')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./MultivariateNormal.png')
plt.show()
x, y = np.random.multivariate_normal([0, 0], [[100, 0], [0, 1]], 1000).T
plt.plot(x, y, 'o')
plt.axis('equal')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('./MultivariateNormal2.png')
plt.show()
n = 10000
numpy.random.seed(0x5eed)
norm_params = np.array([[5, 1], [1, 1.3], [9, 1.3]]) # parameters of the components
n_components = norm_params.shape[0] # The components and the weights of each component
weights = np.ones(n_components, dtype=np.float64) / float(n_components) # Weight of each component
mixture_idx = numpy.random.choice(n_components, size=n, replace=True, p=weights) # Indices to choose the component
y = numpy.fromiter((ss.norm.rvs(*(norm_params[i])) for i in mixture_idx), dtype=np.float64) # y is the mixture sample
xs = np.linspace(y.min(), y.max(), 200) # Theoretical PDF plotting
ys = np.zeros_like(xs) # Generate the x and y plotting positions
for (l, s), w in zip(norm_params, weights):
ys += ss.norm.pdf(xs, loc=l, scale=s) * w
plt.plot(xs, ys)
plt.hist(y, normed=True, bins="fd")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.show()
# we generate synthetic data
N,D = 1000, 2 # number of points and dimensionality
if D == 2:
#set gaussian ceters and covariances in 2D
#set gaussian ceters and covariances in 2D
means = np.array([[0.5, 0.0], [0, 0], [-0.5, -0.5], [-0.8, 0.3]])
covs = np.array([np.diag([0.01, 0.01]), np.diag([0.025, 0.01]),
np.diag([0.01, 0.025]), np.diag([0.01, 0.01])])
elif D == 3:
# set gaussian ceters and covariances in 3D
# set gaussian ceters and covariances in 3D
means = np.array([[0.5, 0.0, 0.0], [0.0, 0.0, 0.0],
[-0.5, -0.5, -0.5], [-0.8, 0.3, 0.4]])
covs = np.array([np.diag([0.01, 0.01, 0.03]), np.diag([0.08, 0.01, 0.01]),
np.diag([0.01, 0.05, 0.01]), np.diag([0.03, 0.07, 0.01])])
n_gaussians = means.shape[0]
points = []
for i in range(len(means)):
x = np.random.multivariate_normal(means[i], covs[i], N )
points.append(x)
points = np.concatenate(points)
# Create a normally distributed dataset for training
# Generate a normally distributed dataset for training
X = 0.3 * np.random.randn(100, 2)
X_train_normal = np.r_[X + 2, X - 2]
# Generate anomalies and outliers for training
X_train_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))
# Generate a normally distributed dataset for testing
X = 0.3 * np.random.randn(20, 2)
X_test_normal = np.r_[X + 2, X - 2]
# Generate anomalies and outliers for testing
X_test_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))
plt.figure(figsize=(10,7.5)) # we plot and visualise the data points
plt.scatter(X_train_normal[:,0],X_train_normal[:,1],label='X_train_normal')
#plt.scatter(X_train_outliers[:,0],X_train_outliers[:,1],label='X_train_outliers')
plt.scatter(X_test_normal[:,0],X_test_normal[:,1],label='X_test_normal')
#plt.scatter(X_test_outliers[:,0],X_test_outliers[:,1],label='X_test_outliers')
plt.scatter(X_train_outliers[:,0],X_train_outliers[:,1],label='X_test_outliers')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.savefig('./DataNormalAbnormal.png')
plt.show()
plt.figure(figsize=(10,7.5)) # Plot and visualise the data points
plt.scatter(X_train_normal[:,0],X_train_normal[:,1],label='X_train_normal')
plt.scatter(X_train_outliers[:,0],X_train_outliers[:,1],label='X_train_outliers')
plt.scatter(X_test_normal[:,0],X_test_normal[:,1],label='X_test_normal')
plt.scatter(X_test_outliers[:,0],X_test_outliers[:,1],label='X_test_outliers')
plt.xlabel('x') #plt.xlabel('Feature 1')
plt.ylabel('y') #plt.ylabel('Feature 2')
plt.legend()
plt.savefig('./NormalAbnormal.png')
plt.show()
# we append the normal points and outliers- train and test separately
X_train=np.append(X_train_normal,X_train_outliers,axis=0)
X_test=np.append(X_test_normal,X_test_outliers,axis=0)
# train with the isolation forest algorithm
clf = IsolationForest(random_state=0, contamination=0.1)
clf.fit(X_train)
# we predict the anomaly state for data
y_train=clf.predict(X_train)
y_test=clf.predict(X_test)
# Now we will plot and visualize how good our algorithm works for training data
# y_train(the state) will mark the colors accordingly
plt.figure(figsize=(10, 7.5))
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
plt.xlabel('x') #plt.xlabel('Feature 1')
plt.ylabel('y') #plt.ylabel('Feature 2')
# This is to set the legend appropriately
legend_elements = [Line2D([], [], marker='o', color='yellow', label='Marked as normal', linestyle='None'),
Line2D([], [], marker='o', color='indigo', label='Marked as anomaly', linestyle='None')]
plt.legend(handles=legend_elements)
plt.savefig('./NormalAbnormal2.png')
plt.show()
# Now we will do the same for the test data
plt.figure(figsize=(10, 7.5))
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test)
#plt.xlabel('Feature 1')
#plt.ylabel('Feature 2')
plt.xlabel('x')
plt.ylabel('y')
legend_elements = [Line2D([], [], marker='o', color='yellow', label='Marked as normal', linestyle='None'),
Line2D([], [], marker='o', color='indigo', label='Marked as anomaly', linestyle='None')]
plt.legend(handles=legend_elements)
plt.savefig('./NormalAbnormal3.png')
plt.show()
import glob
#import imageio
import tensorflow as tf
import os
import numpy as np
import matplotlib.pyplot as plt
import PIL
import time
from tensorflow.keras import layers
(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
BUFFER_SIZE = 10000
BATCH_SIZE = 256 # Batch and shuffle the data
#BUFFER_SIZE = 60000 # Batch and shuffle the data
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
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
generator = make_generator_model()
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
discriminator = make_discriminator_model()
# This method returns a helper function to compute cross entropy loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
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
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
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)
noise_dim = 100 # Also: EPOCHS = 50
#num_examples_to_generate = 16
#EPOCHS = 50
EPOCHS = 8
#num_examples_to_generate = 16
num_examples_to_generate = 4
# We will reuse this seed overtime to visualize progress in the animated GIF
seed = tf.random.normal([num_examples_to_generate, noise_dim])
# Notice the use of `tf.function`
# 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)