-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathprogram17_Keras_NN.py
731 lines (497 loc) · 22.7 KB
/
program17_Keras_NN.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
# we use Keras, we use: https://www.manning.com/books/deep-learning-with-python
# use datasets
from keras.datasets import imdb
# we use tuples, (..., ...)
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words = 10000)
print(max([max(sequence) for sequence in train_data]))
#print('')
#print(train_data.shape)
#print(test_data.shape)
#print('')
#print(train_data[0])
#print(train_labels[0])
word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]])
import numpy as np
# define the function vectorize_sequences
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
#model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
from keras import optimizers
model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])
from keras import losses
from keras import metrics
model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy])
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
history = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))
# we use mini-batches
# we use: batch_size=512
history_dict = history.history
# history_dict.keys()
print(history_dict.keys())
import matplotlib.pyplot as plt
history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
epochs = range(1, len(loss_values) + 1)
plt.plot(epochs, loss_values, 'bo', label='Training loss')
plt.plot(epochs, val_loss_values, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
#plt.show()
#plt.close()
plt.clf()
acc_values = history_dict['acc']
val_acc_values = history_dict['val_acc']
plt.plot(epochs, acc_values, 'bo', label='Training acc')
plt.plot(epochs, val_acc_values, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
#plt.show()
#plt.close()
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=4, batch_size=512)
results = model.evaluate(x_test, y_test)
print('')
print(results)
print('')
#model.predict(x_test)
print(model.predict(x_test))
import keras
import keras.datasets
# use datasets
import keras.datasets
from keras.datasets import cifar10
from keras.datasets import cifar100
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
(x_train, y_train), (x_test, y_test) = cifar100.load_data()
from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
from keras.datasets import cifar100
(x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode='fine')
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
from keras.datasets import fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
from keras.datasets import fashion_mnist
((trainX, trainY), (testX, testY)) = fashion_mnist.load_data()
# set the matplotlib backend so figures can be saved in the background
import matplotlib
#matplotlib.use("Agg")
# import the necessary packages
from sklearn.metrics import classification_report
from keras.optimizers import SGD
# use Fashion-MNIST
from keras.datasets import fashion_mnist
from keras.utils import np_utils
from keras import backend as K
#from imutils import build_montages
import numpy as np
# use matplotlib
import matplotlib.pyplot as plt
#image_index = 7777
image_index = 777
# ((trainX, trainY), (testX, testY))
# (x_train, y_train), (x_test, y_test)
y_train = trainY
x_train = trainX
# ((trainX, trainY), (testX, testY))
# (x_train, y_train), (x_test, y_test)
y_test = testY
x_test = testX
print(trainX.shape)
print(trainY.shape)
print(testX.shape)
print(testY.shape)
print(y_train[image_index].shape)
print(x_train[image_index].shape)
print(y_train[image_index])
plt.imshow(x_train[image_index], cmap='Greys')
#plt.imshow(x_train[image_index])
#plt.pause(5)
plt.pause(2)
#x_train.shape
print(x_train.shape)
# Reshaping the array to 4-dims so that it can work with the Keras API
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
# we define the input shape
input_shape = (28, 28, 1)
# import the necessary packages
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers.core import Dropout
from keras.layers.core import Dense
from keras import backend as K
class MiniVGGNet:
@staticmethod
def build(width, height, depth, classes):
# initialize the model along with the input shape to be
# "channels last" and the channels dimension itself
model = Sequential()
inputShape = (height, width, depth)
chanDim = -1
# if we are using "channels first", update the input shape
# and channels dimension
if K.image_data_format() == "channels_first":
inputShape = (depth, height, width)
chanDim = 1
# first CONV => RELU => CONV => RELU => POOL layer set
model.add(Conv2D(32, (3, 3), padding="same",
input_shape=inputShape))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(32, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# second CONV => RELU => CONV => RELU => POOL layer set
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# first (and only) set of FC => RELU layers
model.add(Flatten())
model.add(Dense(512))
model.add(Activation("relu"))
model.add(BatchNormalization())
model.add(Dropout(0.5))
# softmax classifier
model.add(Dense(classes))
model.add(Activation("softmax"))
# return the constructed network architecture
return model
# use numpy
import numpy as np
#matplotlib inline
import matplotlib.pyplot as plt
# use tensorflow
import tensorflow as tf
# we use the MNIST dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# https://towardsdatascience.com/image-classification-in-10-minutes-with-mnist-dataset-54c35b77a38d
# use: https://towardsdatascience.com/image-classification-in-10-minutes-with-mnist-dataset-54c35b77a38d
# use matplotlib
import matplotlib.pyplot as plt
image_index = 7777
# The label is 8
print(y_train[image_index])
plt.imshow(x_train[image_index], cmap='Greys')
#plt.pause(5)
plt.pause(2)
#x_train.shape
print(x_train.shape)
# Reshaping the array to 4-dims so that it can work with the Keras API
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
# we define the input shape
input_shape = (28, 28, 1)
# the values are float so that we can get decimal points after division
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# Normalizing the RGB codes by dividing it to the max RGB value.
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])
# Importing the required Keras modules containing model and layers
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
# Creating a Sequential Model and adding the layers
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
# Flatten the 2D arrays for fully connected layers
model.add(Flatten())
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))
# compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# ADAM, adaptive momentum
# we use the Adam optimizer
# fit the model
#model.fit(x=x_train,y=y_train, epochs=10)
#model.fit(x=x_train,y=y_train, epochs=10)
model.fit(x=x_train,y=y_train, epochs=8)
# evaluate the model
model.evaluate(x_test, y_test)
# https://towardsdatascience.com/image-classification-in-10-minutes-with-mnist-dataset-54c35b77a38d
# use index 4444
image_index = 4444
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
#plt.pause(5)
plt.pause(2)
#pred = model.predict(x_test[image_index].reshape(1, img_rows, img_cols, 1))
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())
# Deep Generative Models
# GANs and VAEs, Generative Models
# random noise
# from random noise to a tensor
# We use batch normalisation.
# GANs are very difficult to train. Super-deep models. This is why we use batch normalisation.
# GANs and LSTM RNNs
# use LSTM RNNs together with GANs
# combine the power of LSTM RNNs and GANs
# it is possible to use LSTM RNN together with GANs
# https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
# https://github.com/life-efficient/Academy-of-AI/tree/master/Lecture%2013%20-%20Generative%20Models
# https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
# Anomaly detection (AD)
# Unsupervised machine learning
# GANs for super-resolution
# Generative Adversarial Networks, GANs
# the BigGAN dataset
# BigGAN => massive dataset
# latent space, BigGAN, GANs
# down-sampling, sub-sample, pooling
# throw away samples, pooling, max-pooling
# partial derivatives
# loss function and partial derivatives
# https://github.com/Students-for-AI/The-Academy-of-AI
# https://github.com/life-efficient/Academy-of-AI/tree/master/Lecture%2013%20-%20Generative%20Models
# Generator G and Discriminator D
# the loss function of the Generator G
# up-convolution
# We use a filter we do up-convolution with.
# use batch normalisation
# GANs are very difficult to train and this is why we use batch normalisation.
# We normalize across a batch.
# Mean across a batch. We use batches. Normalize across a batch.
# the ReLU activation function
# ReLU is the most common activation function. We use ReLU.
# use: https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
# we use PyTorch
import torch
#import torch
import torchvision
from torchvision import datasets, transforms
# use matplotlib
import matplotlib.pyplot as plt
#import torch
#import torchvision
#from torchvision import transforms, datasets
# use nn.functional
import torch.nn.functional as F
#import matplotlib.pyplot as plt
#batch_size = 128
# download the training dataset
#train_data = datasets.FashionMNIST(root='fashiondata/',
# transform=transforms.ToTensor(),
# train=True,
# download=True)
# we create the train data loader
#train_loader = torch.utils.data.DataLoader(train_data,
# shuffle=True,
# batch_size=batch_size)
# define the batch size
batch_size = 100
train_data = datasets.FashionMNIST(root='fashiondata/',
transform=transforms.ToTensor(),
train=True,
download=True
)
train_samples = torch.utils.data.DataLoader(dataset=train_data,
batch_size=batch_size,
shuffle=True
)
# combine the power of LSTM RNNs and GANs
# it is possible to use LSTM RNN together with GANs
# GANs and LSTM RNNs
# use LSTM RNNs together with GANs
# class for D and G
# we train the discriminator and the generator
# we make the discriminator
class discriminator(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(1, 64, kernel_size=4, stride=2, padding=1) # 1x28x28-> 64x14x14
self.conv2 = torch.nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1) # 64x14x14-> 128x7x7
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)
# use sigmoid for the output layer
x = F.sigmoid(self.dense1(x))
return x
# this was for the discriminator
# we now do the same for the generator
# 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)
self.uconv1 = torch.nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1) # 128x7x7 -> 64x14x14
self.uconv2 = torch.nn.ConvTranspose2d(64, 1, kernel_size=4, stride=2, padding=1) # 64x14x14 -> 1x28x28
self.bn1 = torch.nn.BatchNorm1d(256)
self.bn2 = torch.nn.BatchNorm1d(1024)
self.bn3 = torch.nn.BatchNorm1d(128 * 7 * 7)
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)))
x = F.sigmoid(self.uconv2(x))
return x
# https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
# use: https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
# instantiate the model
d = discriminator()
g = generator()
# training hyperparameters
#epochs = 100
#epochs = 100
epochs = 10
# learning rate
#dlr = 0.0003
#glr = 0.0003
dlr = 0.003
glr = 0.003
d_optimizer = torch.optim.Adam(d.parameters(), lr=dlr)
g_optimizer = torch.optim.Adam(g.parameters(), lr=glr)
dcosts = []
gcosts = []
plt.ion()
fig = plt.figure()
loss_ax = fig.add_subplot(121)
loss_ax.set_xlabel('Batch')
loss_ax.set_ylabel('Cost')
loss_ax.set_ylim(0, 0.2)
generated_img = fig.add_subplot(122)
plt.show()
# https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
# https://github.com/life-efficient/Academy-of-AI/tree/master/Lecture%2013%20-%20Generative%20Models
# use: https://github.com/life-efficient/Academy-of-AI/blob/master/Lecture%2013%20-%20Generative%20Models/GANs%20tutorial.ipynb
def train(epochs, glr, dlr):
g_losses = []
d_losses = []
for epoch in range(epochs):
# iteratre over mini-batches
for batch_idx, (real_images, _) in enumerate(train_samples):
z = torch.randn(batch_size, 128) # generate random latent variable to generate images from
generated_images = g.forward(z) # generate images
gen_pred = d.forward(generated_images) # prediction of discriminator on generated batch
real_pred = d.forward(real_images) # prediction of discriminator on real batch
dcost = -torch.sum(torch.log(real_pred)) - torch.sum(torch.log(1 - gen_pred)) # cost of discriminator
gcost = -torch.sum(torch.log(gen_pred)) / batch_size # cost of generator
# train discriminator
d_optimizer.zero_grad()
dcost.backward(retain_graph=True) # retain the computational graph so we can train generator after
d_optimizer.step()
# train generator
g_optimizer.zero_grad()
gcost.backward()
g_optimizer.step()
# give us an example of a generated image after every 10000 images produced
#if batch_idx * batch_size % 10000 == 0:
# give us an example of a generated image after every 20 images produced
if batch_idx % 20 == 0:
g.eval() # put in evaluation mode
noise_input = torch.randn(1, 128)
generated_image = g.forward(noise_input)
generated_img.imshow(generated_image.detach().squeeze(), cmap='gray_r')
# pause for some seconds
plt.pause(5)
# put back into training mode
g.train()
dcost /= batch_size
gcost /= batch_size
print('Epoch: ', epoch, 'Batch idx:', batch_idx, '\tDisciminator cost: ', dcost.item(),
'\tGenerator cost: ', gcost.item())
dcosts.append(dcost)
gcosts.append(gcost)
loss_ax.plot(dcosts, 'b')
loss_ax.plot(gcosts, 'r')
fig.canvas.draw()
#print(torch.__version__)
train(epochs, glr, dlr)
# We obtain:
# Epoch: 0 Batch idx: 0 Disciminator cost: 1.3832124471664429 Generator cost: 0.006555716972798109
# Epoch: 0 Batch idx: 1 Disciminator cost: 1.0811840295791626 Generator cost: 0.008780254982411861
# Epoch: 0 Batch idx: 2 Disciminator cost: 0.8481155633926392 Generator cost: 0.011281056329607964
# Epoch: 0 Batch idx: 3 Disciminator cost: 0.6556042432785034 Generator cost: 0.013879001140594482
# Epoch: 0 Batch idx: 4 Disciminator cost: 0.5069876909255981 Generator cost: 0.016225570812821388
# Epoch: 0 Batch idx: 5 Disciminator cost: 0.4130948781967163 Generator cost: 0.018286770209670067
# Epoch: 0 Batch idx: 6 Disciminator cost: 0.33445805311203003 Generator cost: 0.02015063539147377
# Epoch: 0 Batch idx: 7 Disciminator cost: 0.279323011636734 Generator cost: 0.021849267184734344
# Epoch: 0 Batch idx: 8 Disciminator cost: 0.2245958000421524 Generator cost: 0.02352861315011978
# Epoch: 0 Batch idx: 9 Disciminator cost: 0.18664218485355377 Generator cost: 0.025215130299329758
# Epoch: 0 Batch idx: 10 Disciminator cost: 0.14700829982757568 Generator cost: 0.02692217379808426
# Epoch: 0 Batch idx: 32 Disciminator cost: 0.2818330228328705 Generator cost: 0.022729918360710144
# Epoch: 0 Batch idx: 33 Disciminator cost: 0.7310256361961365 Generator cost: 0.05649786815047264
# Epoch: 0 Batch idx: 34 Disciminator cost: 0.31759023666381836 Generator cost: 0.02075548656284809
# Epoch: 0 Batch idx: 35 Disciminator cost: 0.35554683208465576 Generator cost: 0.018939709290862083
# Epoch: 0 Batch idx: 36 Disciminator cost: 0.07700302451848984 Generator cost: 0.04144695773720741
# Epoch: 0 Batch idx: 37 Disciminator cost: 0.08900360018014908 Generator cost: 0.05888563022017479
# Epoch: 0 Batch idx: 38 Disciminator cost: 0.0921328067779541 Generator cost: 0.0593753345310688
# Epoch: 0 Batch idx: 39 Disciminator cost: 0.09943853318691254 Generator cost: 0.05279992148280144
# Epoch: 0 Batch idx: 40 Disciminator cost: 0.2455407679080963 Generator cost: 0.036564696580171585
# Epoch: 0 Batch idx: 41 Disciminator cost: 0.10074597597122192 Generator cost: 0.03721988573670387
# Epoch: 0 Batch idx: 42 Disciminator cost: 0.07906078547239304 Generator cost: 0.04363853484392166
# Epoch: 0 Batch idx: 108 Disciminator cost: 0.22247043251991272 Generator cost: 0.03322262689471245
# Epoch: 0 Batch idx: 109 Disciminator cost: 0.20719386637210846 Generator cost: 0.02638845518231392
# Epoch: 0 Batch idx: 110 Disciminator cost: 0.2795112133026123 Generator cost: 0.027195550501346588
# Epoch: 0 Batch idx: 111 Disciminator cost: 0.49694764614105225 Generator cost: 0.02403220161795616
# Epoch: 0 Batch idx: 112 Disciminator cost: 0.581132173538208 Generator cost: 0.026757290586829185
# Epoch: 0 Batch idx: 113 Disciminator cost: 0.16659873723983765 Generator cost: 0.0335114412009716
# Epoch: 0 Batch idx: 114 Disciminator cost: 0.0639999508857727 Generator cost: 0.04211951419711113
# Epoch: 0 Batch idx: 115 Disciminator cost: 0.018385086208581924 Generator cost: 0.05511172115802765
# Epoch: 0 Batch idx: 116 Disciminator cost: 0.012170110829174519 Generator cost: 0.06555930525064468
# Epoch: 0 Batch idx: 117 Disciminator cost: 0.006641524378210306 Generator cost: 0.07086272537708282
# Epoch: 0 Batch idx: 118 Disciminator cost: 0.010556117631494999 Generator cost: 0.06929603219032288
# Epoch: 0 Batch idx: 119 Disciminator cost: 0.017774969339370728 Generator cost: 0.07270769774913788
# Epoch: 0 Batch idx: 444 Disciminator cost: 0.06787727028131485 Generator cost: 0.04046594724059105
# Epoch: 0 Batch idx: 445 Disciminator cost: 0.07139576226472855 Generator cost: 0.03837932273745537
# Epoch: 0 Batch idx: 446 Disciminator cost: 0.08202749490737915 Generator cost: 0.039551254361867905
# Epoch: 0 Batch idx: 447 Disciminator cost: 0.12328958511352539 Generator cost: 0.03817861154675484
# Epoch: 0 Batch idx: 448 Disciminator cost: 0.06865841150283813 Generator cost: 0.03938257694244385
# generate random latent variable to generate images
z = torch.randn(batch_size, 128)
# generate images
im = g.forward(z)
# use "forward(.)"
plt.imshow(im)