-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathprogram12_GAN.py
2037 lines (1340 loc) · 53 KB
/
program12_GAN.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
# GAN, Generative Adversarial Network
# we use GANs with images
# In a GAN, a G competes with a D
# G = Generative model and D = Discriminative model
# two models compete, the generator and the discriminator
# the generator creates fake data, generative model
# the discriminator classifies the data as fake or true
# the discriminator has to find the fake data produced by the generator
# minmax game, two models compete in a minimax game
# the one model tries to minimize a function and the other to maximize the function
# min max (E_{x ~ Pdata} {log(D(x))} + E_{Z ~ P(Z)} {log(1-D(G(Z)))})
# min => generator, generative model
# max => discriminator, discriminative model
# Z ~ P(z)
# the D(G(z)) is important, D=Discriminator, G=Generator
# the discriminator distinguishes between true and fake images
# GANs are generative models, they create new data
# generative models compute joint distributions and can create new data
# Generator: min_{\theta_g} (E{Z~P(Z)} {log(1-D(G(Z)))})
# E{log(D(Z))}
# E{.} = mean = average over a large sample, we sample distributions
# two NNs battle each other until they become experts in their own tasks
# GANs are usually used with images
# GANs can synthesize new images
# do GANs find a Nash equilibrium?
# do GANs find a Nash equilibrium in game theory between two opposing tasks?
# we now import libraries
# Pytorch
import torch
# we use Variable
from torch.autograd import Variable
# torchvision
import torchvision
# we use torchvision
from torchvision import transforms, datasets
# use nn.functional
import torch.nn.functional as F
# use matplotlib
import matplotlib.pyplot as plt
batch_size = 100
train_data = datasets.FashionMNIST(root='fashiondata/',
transform=transforms.ToTensor(),
train=True,
download=True)
test_data = datasets.FashionMNIST(root='fashiondata/',
transform=transforms.ToTensor(),
train=False,
download=True)
# print(train_data[0])
# print(train_data[0][0])
# plt.imshow(train_data[5][0][0], cmap='gray_r')
train_samples = torch.utils.data.DataLoader(dataset=train_data,
batch_size=batch_size,
shuffle=True)
test_samples = torch.utils.data.DataLoader(dataset=test_data,
batch_size=batch_size)
# discriminator D
class discriminator(torch.nn.Module):
def __init__(self):
super().__init__()
# images go from 1x28x28 to 64x14x14
self.conv1 = torch.nn.Conv2d(1, 64, kernel_size=4, stride=2, padding=1)
# images go from 64x14x14 to 128x7x7
self.conv2 = torch.nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1)
self.dense1 = torch.nn.Linear(128 * 7 * 7, 1)
self.bn1 = torch.nn.BatchNorm2d(64)
self.bn2 = torch.nn.BatchNorm2d(128)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x))).view(-1, 128 * 7 * 7)
x = F.sigmoid(self.dense1(x))
return x
# generator G
class generator(torch.nn.Module):
def __init__(self):
super().__init__()
self.dense1 = torch.nn.Linear(128, 256)
self.dense2 = torch.nn.Linear(256, 1024)
self.dense3 = torch.nn.Linear(1024, 128 * 7 * 7)
# from 128x7x7 to 64x14x14
self.uconv1 = torch.nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1)
# from 64x14x14 to 1x28x28
self.uconv2 = torch.nn.ConvTranspose2d(64, 1, kernel_size=4, stride=2, padding=1)
# we use "BatchNorm1d(.)"
self.bn1 = torch.nn.BatchNorm1d(256)
# we use "BatchNorm1d(.)"
self.bn2 = torch.nn.BatchNorm1d(1024)
# we use "BatchNorm1d(.)"
self.bn3 = torch.nn.BatchNorm1d(128 * 7 * 7)
# we use "BatchNorm2d(.)"
self.bn4 = torch.nn.BatchNorm2d(64)
def forward(self, x):
x = F.relu(self.bn1(self.dense1(x)))
x = F.relu(self.bn2(self.dense2(x)))
x = F.relu(self.bn3(self.dense3(x))).view(-1, 128, 7, 7)
x = F.relu(self.bn4(self.uconv1(x)))
s = F.sigmoid(self.uconv(2))
# we use GPU ".cuda()"
d = discriminator().cuda()
# use cuda
g = generator().cuda()
# we define the hyper-parameters
no_epochs = 100
# learning rate
dlr = 0.0003
glr = 0.0003
# we use ADAM momentum
d_optimizer = torch.optim.Adam(d.parameters(), lr=dlr)
# we use ADAM momentum
g_optimizer = torch.optim.Adam(g.parameters(), lr=glr)
# training loop
for epoch in range(no_epochs):
epochdcost = 0
epochgcost = 0
for k, (real_images,) in enumerate(train_samples):
real_images = Variable(real_images).cuda()
# Z is the noise input
noise_input = Variable(torch.randn(batch_size, 128)).cuda()
generated_images = g.forward(noise_input)
# D(G(Z))
gen_pred = d.forward(generated_images)
real_pred = d.forward(real_images)
# we use the binary cross-entropy cost
dcost = -torch.sum(torch.log(real_pred) + torch.log(1 - gen_pred)) / batch_size
gcost = -torch.sum(torch.log(gen_pred)) / batch_size
d_optimizer.zero_grad()
# we re-use the graph and we use "retain_graph"
dcost.backward(retain_graph=True)
d_optimizer.step()
g_optimizer.zero_grad()
gcost.backward()
g_optimizer.step()
epochdcost += dcost.data[0]
epochgcost += gcost.data[0]
epochcost /= 60000 / batch_size
epochgcost /= 60000 / batch_size
print('Epoch: ', epoch)
print('Discriminator Cost: ', epochdcost)
print('Generator Cost: ', epochgcost)
dcosts.append(epochdcost)
gcosts.append(epochgcost)
# plot figure with the cost
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('Epoch')
ax.set_ylabel('Cost')
ax.set_xlim(0, no_epochs)
ax.plot(dcosts, 'b')
from __future__ import absolute_import
from __future__ import print_function
# numpy
import numpy
#CIFAR-10 Dataset
#CIFAR-100 Dataset
#Caltech-101 Dataset
# we use Sequential
from keras.models import Sequential
from keras.layers import Dense
# use dropout
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import initializers
from keras import backend as K
K.set_image_dim_ordering('th')
import os
import numpy as np
import scipy.io
import scipy.misc
# matplotlib
import matplotlib.pyplot as plt
# tensorflow
import tensorflow as tf
def imread(path):
img = scipy.misc.imread(path).astype(np.float)
if len(img.shape) == 2:
img = np.transpose(np.array([img, img, img]), (2, 0, 1))
return img
#cwd = os.getcwd()
#path = cwd + "/101_ObjectCategories"
#path = "/101_ObjectCategories"
path = "/Users/dionelisnikolaos/Downloads/101_ObjectCategories"
#CIFAR-10 Dataset
#Caltech-101 Dataset
#CIFAR-10 Dataset
#CIFAR-100 Dataset
#Caltech-101 Dataset
valid_exts = [".jpg", ".gif", ".png", ".jpeg"]
print("[%d] CATEGORIES ARE IN \n %s" % (len(os.listdir(path)), path))
categories = sorted(os.listdir(path))
ncategories = len(categories)
imgs = []
labels = []
print('')
#print(categories)
print(categories[1:])
print('')
categories = categories[1:]
# LOAD ALL IMAGES
for i, category in enumerate(categories):
iter = 0
for f in os.listdir(path + "/" + category):
if iter == 0:
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_exts:
continue
fullpath = os.path.join(path + "/" + category, f)
img = scipy.misc.imresize(imread(fullpath), [128, 128, 3])
img = img.astype('float32')
img[:, :, 0] -= 123.68
img[:, :, 1] -= 116.78
img[:, :, 2] -= 103.94
imgs.append(img) # NORMALIZE IMAGE
label_curr = i
labels.append(label_curr)
# iter = (iter+1)%10;
print("Num imgs: %d" % (len(imgs)))
print("Num labels: %d" % (len(labels)))
print(ncategories)
seed = 7
np.random.seed(seed)
# use pandas
import pandas as pd
# use sklearn
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(imgs, labels, test_size=0.1)
X_train = np.stack(X_train, axis=0)
y_train = np.stack(y_train, axis=0)
X_test = np.stack(X_test, axis=0)
y_test = np.stack(y_test, axis=0)
print("Num train_imgs: %d" % (len(X_train)))
print("Num test_imgs: %d" % (len(X_test)))
# # one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
print(y_test.shape)
print(X_train[1, 1, 1, :])
print(y_train[1])
# normalize inputs from 0-255 to 0.0-1.0
print(X_train.shape)
print(X_test.shape)
X_train = X_train.transpose(0, 3, 1, 2)
X_test = X_test.transpose(0, 3, 1, 2)
print(X_train.shape)
print(X_test.shape)
# we use scipy
import scipy.io as sio
data = {}
data['categories'] = categories
data['X_train'] = X_train
data['y_train'] = y_train
data['X_test'] = X_test
data['y_test'] = y_test
sio.savemat('caltech_del.mat', data)
# CIFAR-10 Dataset
# CNN model for CIFAR-10
# numpy
import numpy
# CIFAR-10 dataaset
from keras.datasets import cifar10
# Sequential
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD, Adam
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')
seed = 7
numpy.random.seed(seed)
# load data
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
# we now create the model
# we use: https://github.com/acht7111020/CNN_object_classification
# use Sequential
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), activation='relu', padding='same'))
model.add(Dropout(0.2))
model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(Dropout(0.2))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(Dropout(0.2))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(1024, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
epochs = 50
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
adam = Adam(lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
print('')
print(model.summary())
print('')
# https://github.com/acht7111020/CNN_object_classification
# use: https://github.com/acht7111020/CNN_object_classification
#CIFAR-10 Dataset
#CIFAR-100 Dataset
#Caltech-101 Dataset
# we use Sequential
from keras.models import Sequential
from keras.layers import Dense
# use dropout
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import initializers
from keras import backend as K
K.set_image_dim_ordering('th')
import os
import numpy as np
import scipy.io
import scipy.misc
# matplotlib
import matplotlib.pyplot as plt
# tensorflow
import tensorflow as tf
def imread(path):
img = scipy.misc.imread(path).astype(np.float)
if len(img.shape) == 2:
img = np.transpose(np.array([img, img, img]), (2, 0, 1))
return img
#cwd = os.getcwd()
#path = cwd + "/101_ObjectCategories"
#path = "/101_ObjectCategories"
path = "/Users/dionelisnikolaos/Downloads/101_ObjectCategories"
#CIFAR-10 Dataset
#Caltech-101 Dataset
#CIFAR-10 Dataset
#CIFAR-100 Dataset
#Caltech-101 Dataset
valid_exts = [".jpg", ".gif", ".png", ".jpeg"]
print("[%d] CATEGORIES ARE IN \n %s" % (len(os.listdir(path)), path))
categories = sorted(os.listdir(path))
ncategories = len(categories)
imgs = []
labels = []
print('')
#print(categories)
print(categories[1:])
print('')
categories = categories[1:]
# LOAD ALL IMAGES
for i, category in enumerate(categories):
iter = 0
for f in os.listdir(path + "/" + category):
if iter == 0:
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_exts:
continue
fullpath = os.path.join(path + "/" + category, f)
img = scipy.misc.imresize(imread(fullpath), [128, 128, 3])
img = img.astype('float32')
img[:, :, 0] -= 123.68
img[:, :, 1] -= 116.78
img[:, :, 2] -= 103.94
imgs.append(img) # NORMALIZE IMAGE
label_curr = i
labels.append(label_curr)
# iter = (iter+1)%10;
print("Num imgs: %d" % (len(imgs)))
print("Num labels: %d" % (len(labels)))
print(ncategories)
seed = 7
np.random.seed(seed)
# use pandas
import pandas as pd
# use sklearn
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(imgs, labels, test_size=0.1)
X_train = np.stack(X_train, axis=0)
y_train = np.stack(y_train, axis=0)
X_test = np.stack(X_test, axis=0)
y_test = np.stack(y_test, axis=0)
print("Num train_imgs: %d" % (len(X_train)))
print("Num test_imgs: %d" % (len(X_test)))
# # one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
print(y_test.shape)
print(X_train[1, 1, 1, :])
print(y_train[1])
# normalize inputs from 0-255 to 0.0-1.0
print(X_train.shape)
print(X_test.shape)
X_train = X_train.transpose(0, 3, 1, 2)
X_test = X_test.transpose(0, 3, 1, 2)
print(X_train.shape)
print(X_test.shape)
# we use scipy
import scipy.io as sio
data = {}
data['categories'] = categories
data['X_train'] = X_train
data['y_train'] = y_train
data['X_test'] = X_test
data['y_test'] = y_test
sio.savemat('caltech_del.mat', data)
from keras.regularizers import l1, l2
from keras.callbacks import EarlyStopping
earlyStopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='auto')
# Create the model
model = Sequential()
# model.add(Conv2D(32, (3, 3), padding='same', activation='relu', kernel_constraint=maxnorm(3)))
# model.add(Conv2D(32, (3, 3), activation='relu', padding='same', kernel_constraint=maxnorm(3)))
# model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, (3, 3), input_shape=(3, 128, 128), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(128, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(256, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(512, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
# Compile mode
epochs = 300
lrate = 0.0001
decay = lrate / epochs
# sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
adam = SGD(lr=0.0001)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
# model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
print(model.summary())
np.random.seed(seed)
hist = model.fit(X_train, y_train, validation_data=(X_test, y_test),
epochs=epochs, batch_size=56, shuffle=True, callbacks=[earlyStopping])
# hist = model.load_weights('./64.15/model.h5');
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1] * 100))
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.legend(['train', 'test'])
plt.title('loss')
plt.savefig("loss7.png", dpi=300, format="png")
plt.figure()
plt.plot(hist.history['acc'])
plt.plot(hist.history['val_acc'])
plt.legend(['train', 'test'])
plt.title('accuracy')
plt.savefig("accuracy7.png", dpi=300, format="png")
model_json = model.to_json()
with open("model7.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model7.h5")
print("Saved model to disk")
#import numpy
import numpy as np
# https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
# use: https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
# we use: https://skymind.ai/wiki/open-datasets
# use: http://people.csail.mit.edu/yalesong/cvpr12/
from keras.datasets import mnist
((trainX, trainY), (testX, testY)) = mnist.load_data()
print(trainX.shape)
print(testX.shape)
from keras.datasets import fashion_mnist
((trainX2, trainY2), (testX2, testY2)) = fashion_mnist.load_data()
print(trainX2.shape)
print(testX2.shape)
print('')
from keras.datasets import imdb
((trainX3, trainY3), (testX3, testY3)) = imdb.load_data()
print(trainX3.shape)
print(testX3.shape)
print('')
from keras.datasets import cifar10
((trainX4, trainY4), (testX4, testY4)) = cifar10.load_data()
print(trainX4.shape)
print(testX4.shape)
from keras.datasets import cifar100
((trainX5, trainY5), (testX5, testY5)) = cifar100.load_data()
print(trainX5.shape)
print(testX5.shape)
print('')
# use: https://medium.com/@erikhallstrm/work-remotely-with-pycharm-tensorflow-and-ssh-c60564be862d
# we now use: https://medium.com/@erikhallstrm/work-remotely-with-pycharm-tensorflow-and-ssh-c60564be862d
from keras.datasets import reuters
((trainX6, trainY6), (testX6, testY6)) = reuters.load_data()
print(trainX6.shape)
print(testX6.shape)
from keras.datasets import boston_housing
((trainX7, trainY7), (testX7, testY7)) = boston_housing.load_data()
print(trainX7.shape)
print(testX7.shape)
print('')
# use: https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
# we use: https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
#from sklearn import datasets
#from sklearn import datasets2
import sklearn
#from sklearn.datasets2 import kddcup99
#import sklearn.datasets2
#import sklearn.datasets
#dataset_boston = datasets.load_boston()
#dataset_boston = datasets2.load_boston()
#dataset_kddcup99 = datasets2.load_digits()
# use .io
import scipy.io
#mat2 = scipy.io.loadmat('NATOPS6.mat')
mat2 = scipy.io.loadmat('/Users/dionelisnikolaos/Downloads/NATOPS6.mat')
# NATOPS6.mat
print(mat2)
#mat = scipy.io.loadmat('thyroid.mat')
mat = scipy.io.loadmat('/Users/dionelisnikolaos/Downloads/thyroid.mat')
# thyroid.mat
print(mat)
# usenet_recurrent3.3.data
# we use: usenet_recurrent3.3.data
# use pandas
import pandas as pd
# numpy
import numpy
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, zero_one_loss
from sklearn.model_selection import train_test_split
data_dir = "/Users/dionelisnikolaos/Downloads/"
raw_data_filename = data_dir + "usenet_recurrent3.3.data"
#raw_data_filename = "/Users/dionelisnikolaos/Downloads/usenet_recurrent3.3.data"
# raw_data_filename = "/Users/dionelisnikolaos/Downloads/usenet_recurrent3.3.data"
# use: raw_data_filename = "/Users/dionelisnikolaos/Downloads/usenet_recurrent3.3.data"
print ("Loading raw data")
raw_data = pd.read_csv(raw_data_filename, header=None)
print ("Transforming data")
# Categorize columns: "protocol", "service", "flag", "attack_type"
raw_data[1], protocols= pd.factorize(raw_data[1])
raw_data[2], services = pd.factorize(raw_data[2])
raw_data[3], flags = pd.factorize(raw_data[3])
raw_data[41], attacks = pd.factorize(raw_data[41])
# separate features (columns 1..40) and label (column 41)
features= raw_data.iloc[:,:raw_data.shape[1]-1]
labels= raw_data.iloc[:,raw_data.shape[1]-1:]
# convert them into numpy arrays
#features= numpy.array(features)
#labels= numpy.array(labels).ravel() # this becomes an 'horizontal' array
labels= labels.values.ravel() # this becomes a 'horizontal' array
# Separate data in train set and test set
df= pd.DataFrame(features)
# create training and testing vars
# Note: train_size + test_size < 1.0 means we are subsampling
# Use small numbers for slow classifiers, as KNN, Radius, SVC,...
X_train, X_test, y_train, y_test = train_test_split(df, labels, train_size=0.8, test_size=0.2)
print('')
print ("X_train, y_train:", X_train.shape, y_train.shape)
print ("X_test, y_test:", X_test.shape, y_test.shape)
print('')
print(X_train.shape)
print(y_train.shape)
print('')
print(X_train.shape)
print(X_test.shape)
print('')
# use matplotlib
import matplotlib.pyplot as plt
# we use: https://skymind.ai/wiki/open-datasets
# use: http://people.csail.mit.edu/yalesong/cvpr12/
from csv import reader
# Load a CSV file
def load_csv(filename):
file = open(filename, "r")
lines = reader(file)
dataset = list(lines)
return dataset
dataset = load_csv('/Users/dionelisnikolaos/Downloads/ann-train.data.txt')
# Load dataset
filename = '/Users/dionelisnikolaos/Downloads/ann-train.data.txt'
#print('Loaded data file {0} with {1} rows and {2} columns').format(filename, len(dataset), len(dataset[0]))
#file = open(filename, 'r')
#for line in file:
# print (line,)