<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saif Gazali on Medium]]></title>
        <description><![CDATA[Stories by Saif Gazali on Medium]]></description>
        <link>https://medium.com/@saifgazali?source=rss-1415c924f99f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g6Pucn8GV2cFDhf6lGMNBw.jpeg</url>
            <title>Stories by Saif Gazali on Medium</title>
            <link>https://medium.com/@saifgazali?source=rss-1415c924f99f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:51:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saifgazali/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cell Nuclei Segmentation using VGG16-UNET And Double-UNET]]></title>
            <link>https://saifgazali.medium.com/cell-nuclei-segmentation-using-vgg16-unet-and-double-unet-eafb65bb959a?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eafb65bb959a</guid>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 21:07:42 GMT</pubDate>
            <atom:updated>2021-08-14T21:07:42.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*yqGx_FFNcsBtct9E3eKvuw.png" /></figure><p>Image Segmentation is the process of dividing an image into segments in order to make use of important segments for processing the image instead of processing the entire image. An image is made of pixels and using image segmentation the pixels having similar attributes are grouped together which allows us to get a far better granular understanding about the content of the image. Each grouped part is assigned a label and using these labels we specify boundaries which separate the required objects in the image from the rest of the image.</p><p>In this article we would be segmenting Cell Nuclei images that would allow us to automate the process of nucleus identification which leads to more efficient drug testing. The dataset can be downloaded from <a href="https://www.kaggle.com/dataset/84613660e1f97d3b23a89deb1ae6199a0c795ec1f31e2934527a7f7aad7d8c37">here</a>. The training dataset contains the retina image, mask and the annotated image. The training set and the test dataset both contains around 20 images. Plotting the Image and its annotated image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*UhvLiEJV5Fts2a_Bluezcg.png" /></figure><p><strong>Loading Dataset</strong></p><p>Creating training, testing and validation set from our dataset.</p><pre>from sklearn.model_selection import train_test_split<br>def load_path(path,split=0.2):<br>  X = sorted(glob(os.path.join(path,&quot;images&quot;,&quot;*.jpg&quot;)))<br>  Y = sorted(glob(os.path.join(path,&quot;masks&quot;,&quot;*.jpg&quot;)))</pre><pre>  size = int(len(X) * split)</pre><pre>  train_x,valid_x = train_test_split(X,test_size=size,random_state=1)<br>  train_y,valid_y = train_test_split(Y,test_size=size,random_state=1)</pre><pre>  train_x,test_x = train_test_split(train_x,test_size=size,random_state=1)</pre><pre>  train_y,test_y = train_test_split(train_y,test_size=size,random_state=1)</pre><pre>  return (train_x,train_y), (valid_x,valid_y), (test_x,test_y)</pre><p>Creating a method to shuffle the images.</p><pre>from sklearn.utils import shuffle<br>def shuffling(x,y):<br>  x,y = shuffle(x,y)<br>  return x,y</pre><p>Loading the training, testing and validation dataset.</p><pre>path = &#39;/content/drive/MyDrive/DSB&#39;</pre><pre>(train_x,train_y), (valid_x,valid_y), (test_x,test_y) = load_path(path)</pre><p>We have around 402 images in our training set, 134 images each in testing and validation set.</p><pre>print(len(train_x),&#39;-&#39;,len(train_y)) #402 - 402</pre><pre>print(len(valid_x),&#39;-&#39;,len(valid_y)) #134 - 134</pre><pre>print(len(test_x),&#39;-&#39;,len(test_y)) #134 - 134</pre><p><strong>Data Pipeline</strong></p><p>Creating a method to read the image which would take a path and read an image from it followed by normalizing the image.</p><pre>def read_image(path):<br>  path = path.decode()<br>  x = cv2.imread(path,cv2.IMREAD_COLOR)</pre><pre>  x = x/255.0<br>  x = x.astype(np.float32)<br>  return x</pre><p>Creating a method to read the annotated image which would take a path and read the annotated image. We would normalize the image and expand its dimension to make it as 3D.</p><pre>def read_mask(path):<br>  path = path.decode()<br>  x = cv2.imread(path,cv2.IMREAD_GRAYSCALE)<br>  x = x/255.0<br>  x = x.astype(np.float32)<br>  x = np.expand_dims(x,axis=-1) #(256,256,1)<br>  return x</pre><p>Creating a method to parse the image and its mask which would process the images.</p><pre>def tf_parse(x,y):<br>  def _parse(x,y):<br>    x = read_image(x)<br>    y = read_mask(y)<br>    return x,y<br>  x,y = tf.numpy_function(_parse,[x,y],[tf.float32,tf.float32])<br>  x.set_shape([256,256,3])<br>  y.set_shape([256,256,1])<br>  return x,y</pre><p>Creating a method tf_dataset() which would take list of images and masks along with a batch size. It would use tensorflow Dataset API and returned a batched dataset after processing it through the above defined methods.</p><pre>def tf_dataset(X,Y,batch_size=2):<br>  dataset = tf.data.Dataset.from_tensor_slices((X,Y))<br>  dataset = dataset.map(tf_parse)<br>  dataset = dataset.batch(batch_size)<br>  dataset = dataset.prefetch(4)<br>  return dataset</pre><p>Getting the dataset.</p><pre>train_dataset = tf_dataset(train_x,train_y)<br>valid_dataset = tf_dataset(valid_x,valid_y)</pre><p>Calculating the number of steps to train our model.</p><pre>#no of steps</pre><pre>train_steps = len(train_x)//batch_size<br>test_steps = len(valid_x)//batch_size</pre><pre>if len(train_x) % batch_size != 0:<br>  train_steps +=1</pre><pre>if len(valid_x) % batch_size != 0:<br>  test_steps +=1</pre><pre>print(train_steps) #201<br>print(test_steps) #67</pre><p><strong>Evaluation Metrics</strong></p><p>Intersection-Over-Union is a common evaluation metric for semantic image segmentation, which first computes the IOU for each semantic class and then computes the average over classes. IOU is defined as follows: IOU = true_positive / (true_positive + false_positive + false_negative). The predictions are accumulated in a confusion matrix, weighted by sample_weight and the metric is then calculated from it.</p><pre>def iou(y_true,y_pred):<br>  def f(y_true,y_pred):<br>    intersection = (y_true*y_pred).sum()<br>    union = y_true.sum() + y_pred.sum() - intersection<br>    x = (intersection + 1e-15) / (union + 1e-15)<br>    x = x.astype(np.float32)<br>    return x<br>  return tf.numpy_function(f,[y_true,y_pred],tf.float32)</pre><p>Dice Loss is essentially a measure of overlap between two samples. This measure ranges from 0 to 1 where a Dice coefficient of 1 denotes perfect and complete overlap. The Dice coefficient was originally developed for binary data and can be used in our case.</p><pre>smooth = 1e-15<br>def dice_coef(y_true,y_pred):<br>  y_true = tf.keras.layers.Flatten()(y_true)<br>  y_pred = tf.keras.layers.Flatten()(y_pred)<br>  intersection = tf.reduce_sum(y_true*y_pred)<br>  return (2. * intersection + smooth) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred))def dice_loss(y_true,y_pred):<br>  return 1.0 - dice_coef(y_true,y_pred)</pre><p><strong>VGG16-UNET Model</strong></p><p>The encoder layers in our UNET model will be using Pretrained layers from VGG-16 model whereas the other layers would be trained during the model training. Defining a method to return a covolutional block(Convolution-BatchNormalization-ReLU).</p><pre>def conv_block(inputs,num_filters):<br>  x = Conv2D(num_filters,3,padding=&#39;same&#39;)(inputs)<br>  x = BatchNormalization()(x)<br>  x = Activation(&#39;relu&#39;)(x)  x = Conv2D(num_filters,3,padding=&#39;same&#39;)(x)<br>  x = BatchNormalization()(x)<br>  x = Activation(&#39;relu&#39;)(x)  return x</pre><p>Defining our decoder block.</p><pre>def define_decoder(inputs,skip_layer,num_filters):<br>  init = RandomNormal(stddev=0.02)<br>  x = Conv2DTranspose(num_filters,(2,2),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(inputs)  g = Concatenate()([x,skip_layer])<br>  g = conv_block(g,num_filters)<br>  return g</pre><p>Importing the VGG-16 model from Keras applications library and printing its summary.</p><pre>vgg16 = VGG16(include_top=False,weights=&#39;imagenet&#39;)<br>vgg16.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*oDTG9LqOMhUf8AyhGrR6_w.png" /></figure><p>WE would select the layers according to our output shape required for each layer in our traditional encoder block of the UNET model. We require layers with output shape 512,256,128 and 64. Hence selecting the layers from the VGG16 model which satisfy the requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*PA5DgwlyUF3hfKLFXUA1Bw.jpeg" /></figure><pre>def vgg16_unet(input_shape):<br>  inputs = Input(shape=input_shape)  vgg16 = VGG16(include_top=False,weights=&#39;imagenet&#39;,input_tensor=inputs)  # We will extract encoder layers based on their output shape from vgg16 model  s1 = vgg16.get_layer(&#39;block1_conv2&#39;).output  <br>  s2 = vgg16.get_layer(&#39;block2_conv2&#39;).output  <br>  s3 = vgg16.get_layer(&#39;block3_conv3&#39;).output  <br>  s4 = vgg16.get_layer(&#39;block4_conv3&#39;).output    # bottleneck/bridege layer from vgg16<br>  b1 = vgg16.get_layer(&#39;block5_conv3&#39;).output #32<br>  <br>  # Decoder Block<br>  d1 = define_decoder(b1,s4,512)<br>  d2 = define_decoder(d1,s3,256)<br>  d3 = define_decoder(d2,s2,128)<br>  d4 = define_decoder(d3,s1,64)  #output layer<br>  outputs = Conv2D(1,1,padding=&#39;same&#39;,activation=&#39;sigmoid&#39;)(d4)<br>  model = Model(inputs,outputs)<br>  <br>  return model</pre><p>Defining our VGG16-UNET model and compiling.</p><pre>model = vgg16_unet((256,256,3))</pre><pre>model.compile(loss=dice_loss,optimizer=Adam(lr),metrics=[dice_coef,iou,Recall(),Precision()])</pre><p>Training our model for 25 epochs.</p><pre>model.fit(<br>train_dataset,<br>epochs=25,<br>validation_data=valid_dataset,<br>steps_per_epoch=train_steps,<br>validation_steps=test_steps)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oARQPMwlRHrzvOO2pBmYmg.png" /></figure><p>Intersection over Union ratio is around 88%.</p><p>Using our model to to plot segmented images for the test dataset and plotting it. The image plot has the cell image, its annotated image and our predicted image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*pFRIYhp8L8nzRVbdtb0fVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*yqGx_FFNcsBtct9E3eKvuw.png" /></figure><p><strong>Double UNET Model</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*foKUe_g8C-6FJBYlZz_asQ.png" /><figcaption>Double UNET Model Architecture</figcaption></figure><p>Double UNET starts with a VGG-19 as encoder sub-network, which is followed by decoder subnetwork. What distinguishes Double UNET from UNET in the first network (NETWORK 1) is the use of VGG-19 marked in yellow, ASPP marked in blue, and decoder block marked in light green. The squeeze-and-excite block [21] is used in the encoder of NETWORK 1 and decoder blocks of NETWORK 1 and NETWORK 2. An element-wise multiplication is performed between the output of NETWORK 1 with the input of the same network.</p><p>The first encoder in Double UNET (encoder1) uses a pretrained VGG-19 model, whereas the second encoder (encoder2), is built from scratch. we use two decoders in the entire network, with small modifications on the decoder as compared with that of the original UNET. Each block in the decoder performs a 2 × 2 bi-linear up-sampling on the input feature, which doubles the dimension of the input feature maps. Now, we concatenate the appropriate skip connections feature maps from the encoder to the output feature maps.</p><p><strong>Squeeze and Excitation block</strong></p><p>The Squeeze-and-Excitation Block is an architectural unit designed to improve the representational power of a network by enabling it to perform dynamic channel-wise feature recalibration. The process is:</p><ul><li>The block has a convolutional block as an input.</li><li>Each channel is “squeezed” into a single numeric value using average pooling.</li><li>A dense layer followed by a ReLU adds non-linearity and output channel complexity is reduced by a ratio.</li><li>Another dense layer followed by a sigmoid gives each channel a smooth gating function.</li><li>Finally, we weight each feature map of the convolutional block based on the side network; the “excitation”.</li></ul><pre>def squeeze_excite_block(inputs,ratio=8):</pre><pre>  init = inputs   # (b,128,128,32)<br>  channel_axis = -1<br>  filters = init.shape(channel_axis)</pre><pre>  print(filters) # 32</pre><pre>  se_shape = (1,1,filters)</pre><pre>  # global average pooling layer to supress/squeeze it<br>  se = GlobalAveragePooling2D()(init)  # (b,32) -&gt; (b,1,1,32)<br>  se = Reshape(se_shape)(se)<br>  se = Dense(filters//ratio,activation=&#39;relu&#39;,use_bias=False)(se) # ratio - how much we need to reduce the amount of features in the Dense layer</pre><pre>  se = Dense(filters,activation=&#39;sigmoid&#39;,use_bias=False)(se)  # contains value btw [0,1] - supresses the features not of importance</pre><pre>  #Channel wise attention<br>  x = Multiply()([inputs,se])</pre><pre>  return x</pre><p><strong>Atrous Spatial Pyramid Pooling</strong></p><p>Atrous Spatial Pyramid Pooling (ASSP) is a semantic segmentation module for resampling a given feature layer at multiple rates prior to convolution. This amounts to probing the original image with multiple filters that have complementary effective fields of view, thus capturing objects as well as useful image context at multiple scales. Rather than actually resampling features, the mapping is implemented using multiple parallel atrous convolutional layers with different sampling rates.</p><pre>def ASPP(x,filter):</pre><pre>  shape = x.shape</pre><pre>  # Taking an image map -&gt; Downsampling it -&gt; Upsampling it to original shape<br>  y1 = AveragePooling2D(pool_size=(shape[1],shape[2]))(x)<br>  y1 = Conv2D(filter,1,padding=&#39;same&#39;)(y1)<br>  y1 = BatchNormalization()(y1)<br>  y1 = Activation(&#39;relu&#39;)(y1)<br>  y1 = UpSampling2D((shape[1],shape[2]),interpolation=&#39;bilinear&#39;)(y1)</pre><pre>  #dilation_rate =1 is normal convolution<br>  y2 = Conv2D(filter,1,dilation_rate = 1,padding=&#39;same&#39;,use_bias=False)(x)<br>  y2 = BatchNormalization()(y2)<br>  y2 = Activation(&#39;relu&#39;)(y2)</pre><pre>  y3 = Conv2D(filter,3,dilation_rate = 6,padding=&#39;same&#39;,use_bias=False)(x)<br>  y3 = BatchNormalization()(y3)<br>  y3 = Activation(&#39;relu&#39;)(y3)</pre><pre>  y4 = Conv2D(filter,3,dilation_rate = 12,padding=&#39;same&#39;,use_bias=False)(x)<br>  y4 = BatchNormalization()(y4)<br>  y4 = Activation(&#39;relu&#39;)(y4)</pre><pre>  y5 = Conv2D(filter,3,dilation_rate = 18,padding=&#39;same&#39;,use_bias=False)(x)<br>  y5 = BatchNormalization()(y5)<br>  y5 = Activation(&#39;relu&#39;)(y5)</pre><pre>  y = Concatenate()([y1,y2,y3,y4,y5])<br>  <br>  y = Conv2D(filter,1,dilation_rate = 1,padding=&#39;same&#39;,use_bias=False)(y)<br>  y = BatchNormalization()(y)<br>  y = Activation(&#39;relu&#39;)(y)</pre><pre>  return y</pre><p>Defining the encoder-1 of the Double UNET model which uses the Pretrained VGG19 model layers.</p><pre># Encoder-1</pre><pre>def encoder1(input):<br>  skip_connections = []</pre><pre>  model = VGG19(include_top=False,weights=&#39;imagenet&#39;,input_tensor=input)</pre><pre>  names = [&quot;block1_conv2&quot;,&quot;block2_conv2&quot;,&quot;block3_conv4&quot;,&quot;block4_conv4&quot;]</pre><pre>  for name in names:<br>    skip_connections.append(model.get_layer(name).output)</pre><pre>    output = model.get_layer(&quot;block5_conv4&quot;).output<br>    <br>    return output,skip_connections</pre><p>The second encoder block of Double UNET model uses a Convolution-BatchNormalization-ReLU blocks of layers to create deep convolutional neural networks.</p><pre>def conv_block(x,filters):</pre><pre>  x = Conv2D(filters,3,padding=&#39;same&#39;)(x)<br>  x = BatchNormalization()(x)<br>  x = Activation(&#39;relu&#39;)(x)</pre><pre>  x = Conv2D(filters,3,padding=&#39;same&#39;)(x)<br>  x = BatchNormalization()(x)<br>  x = Activation(&#39;relu&#39;)(x)</pre><pre>  return x</pre><p>Defining our second encoder block.</p><pre>def encoder2(inputs):<br>  num_filters = [32,64,128,256]<br>  skip_connections = []</pre><pre>  x = inputs</pre><pre>  for i,f in enumerate(num_filters):<br>    x = conv_block(x,f)<br>    skip_connections.append(x)<br>    x = MaxPool2D((2,2))(x)</pre><pre>  return x, skip_connections</pre><p>The architecture of decoder-1 is same as unet , except that it uses bilinear upsampling instead of a transpose convolution.</p><pre>def decoder_1(input,skip_connection):<br>  num_filters = [256,128,64,32]<br>  skip_connection.reverse()</pre><pre>  x = input</pre><pre>  for i, f in enumerate(num_filters):<br>    x = UpSampling2D((2,2),interpolation=&#39;bilinear&#39;)(x)<br>    x = Concatenate()([x,skip_connection[i]])<br>    x = conv_block(x,f)</pre><pre>  return x</pre><p>Similarly defining our second decoder model.</p><pre>def decoder_2(input,skip_1,skip_2):</pre><pre>  num_filters = [256,128,64,32]<br>  skip_2.reverse()</pre><pre>  x = input</pre><pre>  for i, f in enumerate(num_filters):<br>    x = UpSampling2D((2,2),interpolation=&#39;bilinear&#39;)(x)<br>    x = Concatenate()([x,skip_1[i],skip_2[i]])<br>    x = conv_block(x,f)</pre><pre>  return x</pre><p>Defining our output block.</p><pre>def output_block(inputs):<br>  x = Conv2D(1,1,padding=&#39;same&#39;)(inputs)<br>  x = Activation(&#39;sigmoid&#39;)(x)<br>  return x</pre><p>Creating a method to build our double UNET model.</p><pre>def build_model(input_shape):</pre><pre>  inputs = Input(input_shape)<br>  x,skip_1 = encoder1(inputs)</pre><pre>  x = ASPP(x,64)</pre><pre>  x = decoder_1(x,skip_1)</pre><pre>  output1 = output_block(x)<br>  <br>  x = inputs * output1</pre><pre>  x,skip_2 = encoder2(x)</pre><pre>  x = ASPP(x,64)</pre><pre>  x = decoder_2(x,skip_1,skip_2)</pre><pre>  output2 = output_block(x)</pre><pre>  outputs = Concatenate()([output1,output2])</pre><pre>  model = Model(inputs,outputs)</pre><pre>  return model</pre><p>Creating our Double UNET model and plotting it.</p><pre>input_shape = (256,256,3)</pre><pre>doubleUnetModel = build_model(input_shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lmqx_uC_Rl4f0fqkZGHeEA.png" /></figure><p>Compiling our Double UNET model.</p><pre>doubleUnetModel.compile(loss=dice_loss,optimizer=Adam(lr),metrics=[dice_coef,iou,Recall(),Precision()])</pre><p>Training our model for 30 epochs.</p><pre>doubleUnetModel.fit(<br>train_dataset,<br>epochs=30,<br>validation_data=valid_dataset,<br>steps_per_epoch=train_steps,<br>validation_steps=test_steps)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jM7r4IYaYPZ24g-3aV_4sA.png" /></figure><p>Intersection over Union ratio has improved to around 92.8% for Double UNET model from 88%(for VGG16 UNET model).</p><p>Using our model to to plot segmented images for the test dataset and plotting it. The image plot has the cell image, its annotated image and our predicted image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*OprezSi6hHsO7hp5gmMtPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*QUMFsR4B61Vtuo8ghI2Zdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*we-WT00Uio6ARWjsnbdi4w.png" /></figure><p><strong>Resources</strong></p><h4><a href="https://arxiv.org/abs/2006.04868">DoubleU-Net: A Deep Convolutional Neural Network for Medical Image Segmentation</a></h4><h4><a href="https://paperswithcode.com/method/aspp">Atrous Spatial Pyramid Pooling</a></h4><h4><a href="https://paperswithcode.com/method/squeeze-and-excitation-block">Squeeze-and-Excitation Block</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eafb65bb959a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retina Blood Vessel Segmentation using VGG16-UNET]]></title>
            <link>https://saifgazali.medium.com/retina-blood-vessel-segmentation-using-vgg16-unet-7262f97e1695?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7262f97e1695</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[vgg16]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 17:08:41 GMT</pubDate>
            <atom:updated>2021-08-14T17:09:12.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*3f2rORiPR5TF4z0ODOqZGA.png" /></figure><p>This is a continuation from the previous <a href="https://saifgazali.medium.com/retina-blood-vessel-segmentation-using-unet-f9e21211fcbf">post</a>.</p><p>The UNET model uses a Convolution-BatchNormalization-ReLU blocks of layers to create deep convolutional neural networks. The configuration of a specific layer can be seen in the appendix of the <a href="https://arxiv.org/abs/1611.07004">paper</a>. The U-Net model architecture is used for the segmentation process rather than the traditional encoder-decoder model which involves taking image as input and down-sampling it for a few layers until a layer where in the image is up-sampled for a few layers and a final image is outputted. The UNET architecture also down-samples the image and up-samples it again but would have skip-connections between layers of same size in encoder and decoder which would allow the information to be shared between input and output.</p><p>The encoder layers in our UNET model will be using Pretrained layers from VGG-16 model whereas the other layers would be trained during the model training. Defining a method to return a covolutional block(Convolution-BatchNormalization-ReLU).</p><pre>def conv_block(inputs,num_filters):<br>  x = Conv2D(num_filters,3,padding=&#39;same&#39;)(inputs)<br>  x = BatchNormalization()(x)<br>  x = Activation(&#39;relu&#39;)(x)</pre><pre>  x = Conv2D(num_filters,3,padding=&#39;same&#39;)(x)<br>  x = BatchNormalization()(x)<br>  x = Activation(&#39;relu&#39;)(x)</pre><pre>  return x</pre><p>Defining our decoder block.</p><pre>def define_decoder(inputs,skip_layer,num_filters):<br>  init = RandomNormal(stddev=0.02)<br>  x = Conv2DTranspose(num_filters,(2,2),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(inputs)</pre><pre>  g = Concatenate()([x,skip_layer])<br>  g = conv_block(g,num_filters)<br>  return g</pre><p><strong>VGG16-UNET Model</strong></p><p>Importing the VGG-16 model from Keras applications library and printing its summary.</p><pre>vgg16 = VGG16(include_top=False,weights=&#39;imagenet&#39;)<br>vgg16.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*oDTG9LqOMhUf8AyhGrR6_w.png" /></figure><p>WE would select the layers according to our output shape required for each layer in our traditional encoder block of the UNET model. We require layers with output shape 512,256,128 and 64. Hence selecting the layers from the VGG16 model which satisfy the requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*PA5DgwlyUF3hfKLFXUA1Bw.jpeg" /></figure><pre>def vgg16_unet(input_shape):<br>  inputs = Input(shape=input_shape)</pre><pre>  vgg16 = VGG16(include_top=False,weights=&#39;imagenet&#39;,input_tensor=inputs)</pre><pre>  # We will extract encoder layers based on their output shape from vgg16 model</pre><pre>  s1 = vgg16.get_layer(&#39;block1_conv2&#39;).output  <br>  s2 = vgg16.get_layer(&#39;block2_conv2&#39;).output  <br>  s3 = vgg16.get_layer(&#39;block3_conv3&#39;).output  <br>  s4 = vgg16.get_layer(&#39;block4_conv3&#39;).output  </pre><pre>  # bottleneck/bridege layer from vgg16<br>  b1 = vgg16.get_layer(&#39;block5_conv3&#39;).output #32<br>  <br>  # Decoder Block<br>  d1 = define_decoder(b1,s4,512)<br>  d2 = define_decoder(d1,s3,256)<br>  d3 = define_decoder(d2,s2,128)<br>  d4 = define_decoder(d3,s1,64)</pre><pre>  #output layer<br>  outputs = Conv2D(1,1,padding=&#39;same&#39;,activation=&#39;sigmoid&#39;)(d4)<br>  model = Model(inputs,outputs)<br>  <br>  return model</pre><p>Defining our VGG16-UNET model and compiling.</p><pre>model = vgg16_unet((256,256,3))</pre><pre>model.compile(loss=dice_loss,optimizer=Adam(lr),metrics=[dice_coef,iou,Recall(),Precision()])</pre><p>Training our model for 500 epochs.</p><pre>model.fit(<br>train_dataset,<br>epochs=500,<br>validation_data=valid_dataset,<br>steps_per_epoch=train_steps,<br>validation_steps=test_steps)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaHp3SjlJXI5Q8AM1MjeAA.png" /></figure><p>Our Intersection over Union ratio has improved to around 78%.</p><p>Using our model to to plot segmented images for the test dataset and plotting it. The image plot has the retina image, its annotated image and our predicted image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Q5cJLj5UcFjpz5Jtj-Amzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*3f2rORiPR5TF4z0ODOqZGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*VVffwz8frnpJfrzsiUzIJg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7262f97e1695" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retina Blood Vessel Segmentation using UNET]]></title>
            <link>https://saifgazali.medium.com/retina-blood-vessel-segmentation-using-unet-f9e21211fcbf?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9e21211fcbf</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[unet]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 17:07:32 GMT</pubDate>
            <atom:updated>2021-08-14T17:09:37.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*ooS_ob1uyfIRG6MpnfCQoQ.png" /></figure><p>Image Segmentation is the process of dividing an image into segments in order to make use of important segments for processing the image instead of processing the entire image. An image is made of pixels and using image segmentation the pixels having similar attributes are grouped together which allows us to get a far better granular understanding about the content of the image. Each grouped part is assigned a label and using these labels we specify boundaries which separate the required objects in the image from the rest of the image.</p><p>In this article we would be segmenting retina blood vessel from the retina image and the dataset can be downloaded from <a href="https://academictorrents.com/details/062dc18f55b086c76c718ac88f98972789b3c04c">here</a>. The training dataset contains the retina image, mask and the annotated image. The training set and the test dataset both contains around 20 images. Plotting the retina and the annotated image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*4_jr47zotDptNG0Qyg7WSg.png" /><figcaption>Retina Image (Left) and Segmented Image(Right)</figcaption></figure><p><strong>Loading Dataset</strong></p><p>Loading our training and testing dataset. Images folder contains the retina images whereas the 1st_manual folder contains the annotated images.</p><pre>def load_data(path):<br>  train_x = sorted(glob(os.path.join(path,&quot;training&quot;,&quot;images&quot;,&quot;*.tif&quot;)))<br>  train_y = sorted(glob(os.path.join(path,&quot;training&quot;,&quot;1st_manual&quot;,&quot;*.gif&quot;)))</pre><pre>  test_x = sorted(glob(os.path.join(path,&quot;test&quot;,&quot;images&quot;,&quot;*.tif&quot;)))<br>  test_y =    sorted(glob(os.path.join(path,&quot;test&quot;,&quot;1st_manual&quot;,&quot;*.gif&quot;)))</pre><pre>return (train_x,train_y),(test_x,test_y)</pre><p>Loading the data.</p><pre># load the data</pre><pre>(train_x,train_y),(test_x,test_y) = load_data(&#39;/content/drive/MyDrive/DRIVE&#39;)</pre><p><strong>Data augmentation</strong></p><p>Data augmentation is the technique to artificially increase the size of our training dataset by creating new images from the existing images in the dataset using certain modifications. As we have only 20 images in our dataset and given that the deep learning neural networks perform better when trained on large set of data. Hence data augmentation is used to improve the performance of our model.</p><p>We would be using four transformations that would be applied to each image of our training dataset:</p><ol><li>Horizontal Flip.</li><li>Vertical Flip.</li><li>Elastic Transform.</li><li>Grid Distortion.</li></ol><pre>#data augmentation</pre><pre>from tqdm import tqdm</pre><pre>def augment_data(images,mask,save_path,augment=True):<br>  H = 256<br>  W = 256<br>  print(save_path)</pre><pre>  for idx, (x,y) in tqdm(enumerate(zip(images,mask)),total=len(images)):<br>    #extracting names of the image<br>    name = x.split(&quot;/&quot;) [- 1] .split (&quot;.&quot;) [0]<br>    print(name)</pre><pre>    #Reading image and mask<br>    x = cv2.imread(x,cv2.IMREAD_COLOR)<br>    y = imageio.mimread(y)[0]</pre><pre>    #data augmentation<br>    if augment == True:<br> <br>      # probability of horizantal flip applied to an image<br>      aug = HorizontalFlip(p=1.0)<br>      augmented = aug(image=x,mask=y)<br>      x1 = augmented[&#39;image&#39;]<br>      y1 = augmented[&#39;mask&#39;]</pre><pre>      aug = VerticalFlip(p=1.0)<br>      augmented = aug(image=x,mask=y)<br>      x2 = augmented[&#39;image&#39;]<br>      y2 = augmented[&#39;mask&#39;]</pre><pre>      aug = ElasticTransform(p=1.0,alpha=120,sigma=120*0.05)<br>      augmented = aug(image=x,mask=y)<br>      x3 = augmented[&#39;image&#39;]<br>      y3 = augmented[&#39;mask&#39;]</pre><pre>      aug = GridDistortion(p=1.0)<br>      augmented = aug(image=x,mask=y)<br>      x4 = augmented[&#39;image&#39;]<br>      y4 = augmented[&#39;mask&#39;]</pre><pre>      X = [x,x1,x2,x3,x4]<br>      Y = [y,y1,y2,y3,y4]</pre><pre>    # no need to augment the data</pre><pre>   else:<br>     X = [x]<br>     Y = [y]</pre><pre>   index = 0<br>   for i,m in zip(X,Y):<br>     i = cv2.resize(i,(W,H))<br>     m = cv2.resize(m,(W,H))<br>   <br>     if len(X) == 1:<br>       tmp_image_name = f&quot;{name}.jpg&quot;<br>       tmp_mask_name = f&quot;{name}.jpg&quot;<br>     else:<br>       tmp_image_name = f&quot;{name}_{index}.jpg&quot;<br>       tmp_mask_name = f&quot;{name}_{index}.jpg&quot;</pre><pre>     image_path = os.path.join(save_path,&quot;images&quot;,tmp_image_name)<br>     mask_path = os.path.join(save_path,&quot;mask&quot;,tmp_mask_name)</pre><pre>     print(image_path)<br>     print(mask_path)</pre><pre>     cv2.imwrite(image_path, i)<br>     cv2.imwrite(mask_path, m)</pre><pre>     index+=1</pre><p>Creating new directories in order to save the generated augmented images.</p><pre>#create new directories</pre><pre>create_dir(&#39;/content/drive/MyDrive/new_drive_data/train/images&#39;)<br>create_dir(&#39;/content/drive/MyDrive/new_drive_data/train/mask&#39;)</pre><pre>create_dir(&#39;/content/drive/MyDrive/new_drive_data/test/images&#39;)<br>create_dir(&#39;/content/drive/MyDrive/new_drive_data/test/mask&#39;)</pre><p>Augmenting the data.</p><pre>augment_data(train_x,train_y,&#39;/content/drive/MyDrive/new_drive_data/train&#39;,True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*iPyxhtgQN1v0OPCWF4UZBg.png" /></figure><p>Plotting the augmented images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*3t3xgaTDteWoMl7htK8PWQ.png" /></figure><p><strong>UNET Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS22EucRwD1zkHUOe9X8Ww.png" /><figcaption>UNET Architecture</figcaption></figure><p>The UNET model uses a Convolution-BatchNormalization-ReLU blocks of layers to create deep convolutional neural networks. The configuration of a specific layer can be seen in the appendix of the <a href="https://arxiv.org/abs/1611.07004">paper</a>. The U-Net model architecture is used for the segmentation process rather than the traditional encoder-decoder model which involves taking image as input and down-sampling it for a few layers until a layer where in the image is up-sampled for a few layers and a final image is outputted. The UNet architecture also down-samples the image and up-samples it again but would have skip-connections between layers of same size in encoder and decoder which would allow the information to be shared between input and output.</p><p>Defining the encoder block which is a part of UNET model and is used for down-sampling an image.</p><pre># define downsampling block for Unet<br>def encoder_block(n_nodes,con_layer,batchNorm=True):<br>  #points from gaussian distribution<br>  init = RandomNormal(stddev=0.002)</pre><pre>  g = Conv2D(n_nodes,(4,4),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(con_layer)</pre><pre>  if batchNorm:<br>    g = BatchNormalization()(g)<br>  <br>  g = LeakyReLU(0.2)(g)</pre><pre>  return g</pre><p>Defining the decoder block which is a part of UNET model and is used for up-sampling an image.</p><pre>#define upsampling block for Unet<br>def decoder_block(n_nodes,con_layer,skip_layer,dropout=True):</pre><pre>  #points from gaussian distribution<br>  init = RandomNormal(stddev=0.002)<br>  g = Conv2DTranspose(n_nodes,(4,4),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(con_layer)</pre><pre>  g = BatchNormalization()(g)</pre><pre>  if dropout:<br>    g = Dropout(0.2)(g)</pre><pre>  g = Concatenate()([g,skip_layer])</pre><pre>  g = Activation(&#39;relu&#39;)(g)</pre><pre>  return g</pre><p>Defining our UNET model.</p><pre># define unet model<br>def define_unet(img_shape=(256,256,3)):</pre><pre>  #getting points from gaussian distribution<br>  init = RandomNormal(stddev=0.02)<br>  inp = Input(shape=img_shape)</pre><pre>  #Downsampling layers<br>  e1 = encoder_block(64,inp,False)<br>  e2 = encoder_block(128,e1)<br>  e3 = encoder_block(256,e2)<br>  e4 = encoder_block(512,e3)<br>  e5 = encoder_block(512,e4)<br>  e6 = encoder_block(512,e5)<br>  e7 = encoder_block(512,e6)</pre><pre>  #Bottleneck layer<br>  b1 = Conv2D(512,(4,4),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(e7)<br>  b1 = Activation(&#39;relu&#39;)(b1)</pre><pre>  #Upsampling layers<br>  d1 = decoder_block(512,b1,e7)<br>  d2 = decoder_block(512,d1,e6)<br>  d3 = decoder_block(512,d2,e5)<br>  d4 = decoder_block(512,d3,e4,False)<br>  d5 = decoder_block(256,d4,e3,False)<br>  d6 = decoder_block(128,d5,e2,False)<br>  d7 = decoder_block(64,d6,e1,False)</pre><pre>  #Output layer<br>  g = Conv2DTranspose(1,1,strides=(2,2),padding=&#39;same&#39;,activation=&#39;sigmoid&#39;)(d7)</pre><pre>  #define model<br>  model = Model(inp,g)</pre><pre>  return model</pre><p>Plotting our UNET model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*3xjyPHt8Y4cL_z6SuE-ZCg.png" /><figcaption>UNET Model Architecture</figcaption></figure><p>Defining our Hyperparameters.</p><pre># directory to save files<br>create_dir(&quot;/content/drive/MyDrive/files&quot;)</pre><pre>#Hyperparameters<br>batch_size=2<br>lr = 1e-4<br>num_epochs = 100</pre><pre>model_path = os.path.join(&quot;/content/drive/MyDrive/files&quot;,&quot;model.h5&quot;)<br>csv_path = os.path.join(&quot;/content/drive/MyDrive/files&quot;,&quot;data.csv&quot;)</pre><p>Creating a method to load images from a given path.</p><pre>def load_path(path):<br>  X = sorted(glob(os.path.join(path,&quot;images&quot;,&quot;*.jpg&quot;)))<br>  Y = sorted(glob(os.path.join(path,&quot;mask&quot;,&quot;*.jpg&quot;)))</pre><pre>  return X,Y</pre><p>Creating a method to shuffle the images.</p><pre>from sklearn.utils import shuffle<br>def shuffling(x,y):<br>  x,y = shuffle(x,y)<br>  return x,y</pre><p>Defining the training and validation dataset path.</p><pre># Dataset</pre><pre>dataset_path = &quot;/content/drive/MyDrive/new_drive_data&quot;<br>train_path = os.path.join(dataset_path,&quot;train&quot;)<br>valid_path = os.path.join(dataset_path,&quot;test&quot;)</pre><p>Loading and shuffling training dataset whereas just loading the testing dataset.</p><pre>#Load and shuffle the data<br>train_x,train_y = load_path(train_path)<br>train_x,train_y = shuffling(train_x,train_y)</pre><pre>valid_x, valid_y = load_path(valid_path)</pre><p><strong>Data Pipeline</strong></p><p>Creating a method to read the image which would take a path and read an image from it followed by normalizing the image.</p><pre>def read_image(path):<br>  path = path.decode()<br>  x = cv2.imread(path,cv2.IMREAD_COLOR)<br>  x = x/255.0<br>  x = x.astype(np.float32)<br>  return x</pre><p>Creating a method to read the annotated image which would take a path and read the annotated image. We would normalize the image and expand its dimension to make it as 3D.</p><pre>def read_mask(path):<br>  path = path.decode()<br>  x = cv2.imread(path,cv2.IMREAD_GRAYSCALE)<br>  x = x/255.0<br>  x = x.astype(np.float32)<br>  x = np.expand_dims(x,axis=-1) #(256,256,1)<br>  return x</pre><p>Creating a method to parse the image and its mask which would process the images.</p><pre>def tf_parse(x,y):<br>  def _parse(x,y):<br>    x = read_image(x)<br>    y = read_mask(y)<br>    return x,y<br>  x,y = tf.numpy_function(_parse,[x,y],[tf.float32,tf.float32])<br>  x.set_shape([256,256,3])<br>  y.set_shape([256,256,1])<br>  return x,y</pre><p>Creating a method tf_dataset() which would take list of images and masks along with a batch size. It would use tensorflow Dataset API and returned a batched dataset after processing it through the above defined methods.</p><pre>def tf_dataset(X,Y,batch_size=2):<br>  dataset = tf.data.Dataset.from_tensor_slices((X,Y))<br>  dataset = dataset.map(tf_parse)<br>  dataset = dataset.batch(batch_size)<br>  dataset = dataset.prefetch(4)<br>  return dataset</pre><p>Getting the dataset.</p><pre>train_dataset = tf_dataset(train_x,train_y)<br>valid_dataset = tf_dataset(valid_x,valid_y)</pre><p>Printing the number of training and validation images.</p><pre>valid_x = np.array(valid_x)<br>valid_y = np.array(valid_y)<br>train_x = np.array(train_x)<br>train_y = np.array(train_y)</pre><pre>print(train_x.shape) #(75,)<br>print(train_y.shape) #(75,)</pre><pre>print(valid_x.shape) #(5,)<br>print(valid_y.shape) #(5,)</pre><p>Calculating the number of steps to train our model.</p><pre>#no of steps<br>train_steps = len(train_x)//batch_size<br>test_steps = len(valid_x)//batch_size</pre><pre>if len(train_x) % batch_size != 0:<br>  train_steps +=1</pre><pre>if len(valid_x) % batch_size != 0:<br>  test_steps +=1</pre><pre>print(train_steps) #39<br>print(test_steps) #4</pre><p><strong>Evaluation Metrics</strong></p><p>Intersection-Over-Union is a common evaluation metric for semantic image segmentation, which first computes the IOU for each semantic class and then computes the average over classes. IOU is defined as follows: IOU = true_positive / (true_positive + false_positive + false_negative). The predictions are accumulated in a confusion matrix, weighted by sample_weight and the metric is then calculated from it</p><pre>def iou(y_true,y_pred):<br>  def f(y_true,y_pred):<br>    intersection = (y_true*y_pred).sum()<br>    union = y_true.sum() + y_pred.sum() - intersection<br>    x = (intersection + 1e-15) / (union + 1e-15)<br>    x = x.astype(np.float32)<br>    return x<br>  return tf.numpy_function(f,[y_true,y_pred],tf.float32)</pre><p>Dice Loss is essentially a measure of overlap between two samples. This measure ranges from 0 to 1 where a Dice coefficient of 1 denotes perfect and complete overlap. The Dice coefficient was originally developed for binary data and can be used in our case.</p><pre>smooth = 1e-15<br>def dice_coef(y_true,y_pred):<br>  y_true = tf.keras.layers.Flatten()(y_true)<br>  y_pred = tf.keras.layers.Flatten()(y_pred)<br>  intersection = tf.reduce_sum(y_true*y_pred)<br>  return (2. * intersection + smooth) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred))</pre><pre>def dice_loss(y_true,y_pred):<br>  return 1.0 - dice_coef(y_true,y_pred)</pre><p>Compiling our UNET model using Adam optimizer and the above 2 metrics are used.</p><pre>model.compile(loss=dice_loss,optimizer=Adam(lr),metrics=[dice_coef,iou,Recall(),Precision()])</pre><p><strong>Model Training</strong></p><p>Callbacks are part of code which are executed during training of the model. We would save our model periodically. CSVLogger is also used in order to log all the losses.</p><pre>#it will run during the training</pre><pre>callbacks = [<br>ModelCheckpoint(model_path,verbose=1,save_best_only=True),<br>CSVLogger(csv_path)</pre><pre>]</pre><p>Training our model for 100 epochs.</p><pre>model.fit(<br>train_dataset,<br>epochs=500,<br>validation_data=valid_dataset,<br>steps_per_epoch=train_steps,<br>validation_steps=test_steps,<br>callbacks=callbacks)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZyRbzeAoldRU4I7l-hUOA.png" /></figure><p>Saving our model</p><pre>model.save(&#39;/content/drive/MyDrive/500epochs_model_vsl_loss.h5&#39;)</pre><p>Creating a method save_results which would save the retina image, its annotated image and our predicted image.</p><pre>def save_results(ori_x,ori_y,y_pred,save_image_path):<br>  line = np.ones((256,10,3))*255</pre><pre>  ori_y = np.expand_dims(ori_y,axis=-1)<br>  ori_y = np.concatenate([ori_y,ori_y,ori_y],axis=-1)</pre><pre>  y_pred = np.expand_dims(y_pred,axis=-1)<br>  y_pred = np.concatenate([y_pred,y_pred,y_pred],axis=-1) * 255</pre><pre>  cat_images = np.concatenate([ori_x,line,ori_y,line,y_pred],axis=1)</pre><pre>  cv2.imwrite(save_image_path,cat_images)</pre><p>Testing our model</p><pre>import matplotlib.pyplot as plt</pre><pre>#Make prediction and calculate the metrics value</pre><pre>def make_Predictions(mask_index,model):<br>  for x,y in tqdm(zip(test_x,test_y),total=len(test_x)):<br>    #extracting names of the image<br>    name = x.split (&quot;\\&quot;) [- 1] .split (&quot;.&quot;) [0]</pre><pre>    #Read the image and mask<br>    ori_x,x = read_image(x) #(256,256,3)<br>    ori_y,y = read_mask(y)</pre><pre>    #Prediction<br>    y_pred = model.predict(np.expand_dims(x,axis=0))[0] # (1,256,256,3)<br>    y_pred = y_pred &gt; 0.5<br>    y_pred = y_pred.astype(np.int32)<br>    y_pred = np.squeeze(y_pred,axis=-1)<br> <br>    #Save the images<br>    save_image_path = f&quot;/content/drive/MyDrive/results/(name)_{index+mask_index}.png&quot;</pre><pre>    save_results(ori_x,ori_y,y_pred,save_image_path)</pre><p>Plotting some of the generated images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*ooS_ob1uyfIRG6MpnfCQoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*hCpsZi6pGsFH7Sja0Yj0lA.png" /></figure><p>The model does not seem to generate plausible segmented images due to the limited number of data available. We would improve the model using transfer learning <a href="https://saifgazali.medium.com/retina-blood-vessel-segmentation-using-vgg16-unet-7262f97e1695">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9e21211fcbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cycle GAN Architecture]]></title>
            <link>https://saifgazali.medium.com/cycle-gan-architecture-c4a13e1ae45d?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4a13e1ae45d</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[style-transfer]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 17:21:14 GMT</pubDate>
            <atom:updated>2021-08-08T17:24:03.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*JWYnCgHWWbdudN_hQL9HuA.png" /></figure><p>Image-To-Image translation is the process of conversion of source image to target image. It requires specialized models and custom loss functions for a given task or dataset. These datasets are paired examples and are difficult and expensive to prepare. The dataset must consists many examples of input image (e.g. summer image) and the same image with the desired modification that is used as an expected output image(e.g. winter image). These datasets are difficult to prepare hence techniques which do not require such paired examples are preferred.</p><p>Cycle GAN is an approach to learn special characteristics of the source image and figuring out how these characteristics can be translated into target image in absence of any paired training examples. Generative Adversarial Networks includes a generator model which is capable of generating new plausible fake samples that can be considered to be coming from an existing distribution of samples and a discriminator model that would classify the given sample as real or fake. Cycle GAN is an extension of GAN architecture where in two generator models and two discriminator models are simultaneously trained.</p><p>The first generator model takes input from the first domain and generates a translated image for the second domain whereas the second generator takes image from the second domain and generates a translated image for the first domain. Both the discriminators are then used to determine whether the generated images are real or fake. This adversarial loss is good to generate plausible image in target domain but not sufficient to generate a plausible translation. Cycle consistency is a process where in an image outputted by the first generator model is provided as an input to the second generator model and the output from the second generator model should match the original image. Cycle GAN introduces cycle consistency by using an additional loss where in the difference between the generated output of the second generator and the original image is measured.</p><p><strong>Cycle GAN Model Architecture</strong></p><p>Consider the problem where in we would translate the images of apple to image of oranges and reverse. We have a dataset of apple images and a dataset of orange images and they are not paired meaning they are not the actual translation of each other. Two GANs are developed with each one having a generator and a discriminator model. The first GAN will generate image of an orange given an image of an apple. The second would do the reverse. Each GAN is also updated using cycle consistency loss which is designed to generate plausible translation of the input image. Cycle consistency loss compares an input image to the Cycle GAN to the generated image by calculating the difference between the pixel values.</p><p>Forward cycle consistency loss and backward cycle consistency loss are two ways to calculate Cycle consistency loss.</p><p><strong>Forward Cycle Consistency Loss:</strong></p><p>— Input photo of Apple(collection 1) to GAN 1</p><p>— Output photo of Orange from GAN 1</p><p>— Input photo of Orange from GAN 1 to GAN 2</p><p>— Output photo of Apple from GAN 2</p><p>— Compare photo of Apple(collection 1) to photo of Apple from GAN 2</p><p><strong>Backward Cycle Consistency Loss:</strong></p><p>— Input photo of Orange(collection 2) to GAN 2</p><p>— Output photo of Apple from GAN 2</p><p>— Input photo of Apple from GAN 2 to GAN 1</p><p>— Output photo of Orange from GAN 1</p><p>— Compare photo of Orange(collection 2) to photo of Orange from GAN 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*N24GeFPiLLTxcBoVzuUXvw.png" /></figure><p><strong>Discriminator model</strong></p><p>Cycle GAN uses a Patch GAN rather than a DCNN as it is discriminator model which helps it to classify patches of image as real or fake instead of an entire image. The discriminator is convolutionally run across the image where in we average all the responses to give the final output. The network outputs a single feature map of real and fake predictions that is averaged to give a single score. 70x70 patch size is considered to be effective across different image-to-image translation task. Hence Patch GAN has the ability to predict whether each 70 x 70 patch in the input image is real or fake.</p><p>The discriminator model described in the paper uses blocks of Conv2D-InstanceNorm-LeakyReLU layers with 4x4 filters and 2x2 strides. The architecture is C64-C128-C256-C512. After the last layer a convolution is applied to produce a 1D output. Instance normalization which involves standardizing the values on each feature map in order to remove image specific contrast information is used instead of batch normalization.</p><p>Discriminator model Summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*OYosZ_KSs6vLsVyn_lkACA.png" /><figcaption>Discriminator Model Summary</figcaption></figure><p>Plotting our Discriminator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*tAZ8Cak7A3pt1R8chzslaw.png" /><figcaption>Discriminator model plot</figcaption></figure><p><strong>Generator Model</strong></p><p>The generator model uses deep convolutional GAN which is implemented using multiple residual blocks from the ResNet architecture and is based on the approach described in the paper Perceptual Losses for Real-Time Style Transfer and Super-Resolution. The model uses a number of down-sampling convolutional blocks to encode the input image, a number of ResNet convolutional blocks to transform the image and a number of up-sampling convolutional blocks to generate the output image.</p><p>The architecture for 6-resnet block generator is as follows :</p><p>C7s1–64,d128,d256,R256,R256,R256,R256,R256,R256,u128,u64,C7s1–3.</p><p>Each Resnet block(R256) has two 3x3 convolutional neural network layers where the input is concatenated channel-wise. The down-sampling or d-blocks and up-sampling or u-blocks include Conv2D-InstanceNormalization-Activation blocks with the number of nodes as 128 or 256. The C7s1–64 and C7s1–3 is also a Conv2D-InstanceNormalization-Activation block with number of nodes as 64 and 3 respectively.</p><p>Plotting our generator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*oQYRBSUBQ9tun-2nxLDhHg.png" /><figcaption>Generator Model Plot</figcaption></figure><p><strong>Resources</strong></p><p><a href="https://arxiv.org/abs/1703.10593">Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks, 2017.</a></p><p><a href="https://arxiv.org/abs/1603.08155">Perceptual Losses for Real-Time Style Transfer and Super-Resolution, 2016.</a></p><p><a href="https://arxiv.org/abs/1611.07004">Image-to-Image Translation with Conditional Adversarial Networks, 2016.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4a13e1ae45d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pix2Pix GAN Architecture]]></title>
            <link>https://saifgazali.medium.com/pix2pix-gan-architecture-2f837ae68ae3?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f837ae68ae3</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pix2pix]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sat, 07 Aug 2021 10:59:14 GMT</pubDate>
            <atom:updated>2021-08-07T10:59:14.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*CUnRRcbV2Hkr6IdB2PSF8Q.png" /><figcaption>Photo by <a href="https://arxiv.org/abs/1611.07004">CGAN Paper</a></figcaption></figure><p>The conversion of source image to target image is known as Image-to-Image translation. It requires specialized models and custom loss functions for a given task or dataset. Generative Adversarial Networks includes a generator model which is capable of generating new plausible fake samples that can be considered to be coming from an existing distribution of samples and a discriminator model that would classify the given sample as real or fake. The model weights of discriminator and the generator are updated according to the performance of the discriminator model.</p><p>Conditional GAN involves conditional generation of images by a generator model. It has the ability to generate targeted images of a given type unlike other GAN model which generates a random image from the domain. Pix2Pix GAN is based on conditional GAN where a target image is generated based on a given input image. The generator model is given an input image and generates a translated version of the image. The discriminator model is given an input image and a translated image and it has to predict whether the image is real or fake.</p><p><strong>U-NET Generator Model</strong></p><p>The generator and discriminator model use a standard Convolution-BatchNormalization-ReLU blocks of layers to create deep convolutional neural networks. The configuration of a specific layer can be seen in the appendix of the <a href="https://arxiv.org/abs/1611.07004">paper</a>. The U-Net model architecture is used for the generator model rather than the traditional encoder-decoder model which involves taking image as input and down-sampling it for a few layers until a layer where in the image is up-sampled for a few layers and a final image is outputted. The UNet architecture also down-samples the image and up-samples it again but would have skip-connections between layers of same size in encoder and decoder which would allow the information to be shared between input and output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS22EucRwD1zkHUOe9X8Ww.png" /><figcaption><a href="https://idiotdeveloper.com/unet-implementation-in-pytorch/">UNET Architecture</a></figcaption></figure><p><strong>Discriminator Model</strong></p><p>The discriminator model takes an input image and a translated image and predicts the likelihood of the translated image as real or a generated image of a source input image. Pix2Pix GAN uses a PatchGAN rather than a DCNN which helps it classify patches of image as real or fake instead of an entire image. The discriminator is convolutionally run across the image where in we average all the responses to give the final output. The network outputs a single feature map of real and fake predictions that is averaged to give a single score. 70x70 patch size is considered to be effective across different image-to-image translation task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*HvoNo67BHm5IEGNxCajIiA.png" /><figcaption><a href="https://www.researchgate.net/figure/Architecture-of-the-PatchGAN-Discriminator-network_fig5_328150573">PatchGAN Discriminator Model</a></figcaption></figure><p><strong>Composite Adversarial and L1 loss</strong></p><p>The discriminator model is trained in a traditional standalone manner as in a standard GAN model minimizing the likelihood of identifying real and fake images. Both the adversarial loss and the L1 loss between the generated translated image and the expected image are used to train the generator model. A composite loss function is used to update the generator model which is a combination of adversarial loss and L1 loss. In the<a href="https://arxiv.org/abs/1611.07004"> paper</a> they evaluated L2 loss as well but found that the images generated were blurry. Both the loss have their own function, adversarial loss makes sure that generator model outputs image that are plausible in the target domain and L1 loss makes sure that generator model output are a plausible translation of the source image.</p><p><strong>Loss Function Analysis</strong></p><p>Experiments are performed using only the L1 loss, only the adversarial loss and combination of L1 and adversarial loss. The images generated using L1 loss alone were blurry and the images generated using adversarial loss introduced some new artifacts in the image. The images generated using combination of both were more clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*07COpbgrVNun058SyKfAnw.png" /></figure><p><strong>Generator model analysis</strong></p><p>The U-NET generator model was compared to a traditional encoder-decoder generator model using just L1 loss as well as L1+ adversarial loss. The encoder-decoder model was not able to generate realistic image. The U-NET generator model generated more sharper image. The results were not specific to loss functions as when both the models were trained only on L1 loss, the U-Net performed better again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*gjigvv91rNKSUMDhu3Uq7Q.png" /></figure><p><strong>Discriminator model analysis</strong></p><p>PatchGAN discriminator model with different sized receptive field were tested. The sizes experimented were 1 x 1, 16 x 16, 70 x 70 and 256 x 256 or ImageGAN. The larger the receptive field the deeper the network. Although the full sized ImageGAN produces crisper images but it is harder to train. 70 x 70 receptive field provided a good balance between the depth of the model and the image quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*tn2Hk0c3j_636mV01aVitg.png" /></figure><p><strong>Resources</strong></p><p><a href="https://arxiv.org/abs/1611.07004">Image-to-Image Translation with Conditional Adversarial Networks, 2016</a></p><p><a href="https://machinelearningmastery.com/">Machine Learning Mastery</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f837ae68ae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semi-Supervised GAN for MNIST Handwritten Digits]]></title>
            <link>https://saifgazali.medium.com/semi-supervised-gan-for-mnist-handwritten-digits-be5132efcc82?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5132efcc82</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Thu, 05 Aug 2021 19:32:31 GMT</pubDate>
            <atom:updated>2021-08-05T19:32:31.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4L49ocL6vIygBaI1bY4LIw.png" /><figcaption>Photo by<a href="https://towardsdatascience.com/semi-supervised-learning-and-gans-f23bbf4ac683"> TowardsDataScience</a></figcaption></figure><p>Semi-Supervised GAN involves training of a supervised discriminator, unsupervised discriminator and a generator model simultaneously. It results in a supervised classification predicting the class label of an image and a generator model that generate images from the domain. Generally, Semi-supervised learning is the problem of training a classifier for a dataset that has small number of labeled examples as compared to unlabeled examples. Hence the model must learn from the small amount of labeled data and also take into consideration unlabeled examples in order to generalize to classify new images.</p><p>The discriminator in a traditional GAN is used to predict whether the given image is real or fake. It can be used via transfer learning when developing a classifier allowing the supervised prediction task to take advantage from the unsupervised training of the GAN. The discriminator in Semi-Supervised GAN is updated to make predictions for N+1 classes where N is the number of classes in the prediction problem and the additional class label is added for a new fake class. Hence discriminator model is trained for both the unsupervised GAN task and the supervised task simultaneously. Unsupervised training allows the model to learn useful features from unlabeled dataset which is large in size and to use the extracted features in supervise training to apply class labels.</p><p><strong>Discriminator model</strong></p><p>There are many ways to develop a discriminator model for Semi-Supervised GAN such as having a Single Discriminator with 2 output layers — one for the supervised and the other for the unsupervised task. Both of which uses the same feature extraction layers. Another approach could be to have a separate discriminator models with shared weights. One model to predict whether the image is real or fake and a second model that predicts the class of a given model.</p><p>In this article, we would be creating a discriminator model using a stacked approach to reuse the output layers of one model to provide it as input into another model. This technique is based on the definition of semi-supervised learning in the 2016 paper by Tim Salimans, et al. where in the supervised model is created with K output classes and a softmax activation function where as the unsupervised model takes the output of the prior model and calculated a normalized sum of exponential outputs using the following equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*llKms1iuDzCuvEs7m9R0Yw.png" /></figure><p>The above equation can be implemented using Numpy.</p><pre># custom activation fn<br>def custom_activation(output):<br>  logexpsum = backend.sum(backend.exp(output),axis=-1,keepdims=True)<br>  result = (logexpsum) / (logexpsum + 1.0)<br>  return result</pre><p>Activations are the output of the unsupervised model before the activation function is applied to it. They are small positive or negative values. The model would output a large class prediction for real examples and a small class prediction for fake samples. The supervised model uses a softmax activation and categorical cross-entropy loss function whereas the unsupervised model is stacked on top of the output layer of the supervised model prior the activation. The activations of the node pass through the custom_activation function.</p><pre># Define stacked discriminator for semi supervised learning</pre><pre>def define_discriminator(in_shape=(28,28,1),n_classes=10):</pre><pre>  input = Input(shape = in_shape)</pre><pre>  # Downsample into 14x14<br>  fc = Conv2D(128,(3,3),strides=(2,2),padding=&#39;same&#39;)(input)<br>  fc = LeakyReLU(0.2)(fc)</pre><pre>  # Downsample into 7x7<br>  fc = Conv2D(128,(3,3),strides=(2,2),padding=&#39;same&#39;) (fc)<br>  fc = LeakyReLU(0.2)(fc)</pre><pre>  # flatten feature maps<br>  fc = Flatten()(fc)</pre><pre>  #ouput layer nodes<br>  fc = Dense(n_classes)(fc)</pre><pre>  # supervised output <br>  c_out_layer = Activation(&#39;softmax&#39;)(fc)</pre><pre>  # define and compile supervised discriminator model<br>  c_model = Model(input,c_out_layer)<br>  opt = Adam(lr=0.0002,beta_1=0.5)<br>  c_model.compile(loss=&#39;sparse_categorical_crossentropy&#39;,optimizer=opt,metrics=[&#39;accuracy&#39;])</pre><pre>  c_model.summary()</pre><pre>  # unsupervised ouput - image real or fake<br>  d_out_layer = Lambda(custom_activation)(fc)</pre><pre>  # define and compile unsupervised discriminator model<br>  d_model = Model(input,d_out_layer)<br>  d_model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=opt)<br>  d_model.summary()</pre><pre>  return d_model,c_model</pre><p>Plotting the unsupervised and supervised discriminator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*fdcRDdF-OZtWxdpEjPxgRw.png" /><figcaption>Unsupervised discriminator model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*E9NH0LxfY4s7S7YgBbQucw.png" /><figcaption>Supervised discriminator model</figcaption></figure><p><strong>Generator model</strong></p><p>The generator model takes a point from the latent space as input and outputs plausible image of handwritten digits. The latent space is a vector space of standard Gaussian distributed values. During training the generator model assign meaning to the latent points. The Dense layer is the first hidden layer that has enough nodes to represent a low resolution image (128 * 7 * 7 in our case where 7x7 is the size of image and as we would have multiple low resolution versions of output image we set that number to 128). We then need to reshape the output such as 128 different 7x7 feature maps. The next step involves upsampling the low resolution image to a high resolution version using the Conv2DTranspose layer by configuring the stride to (2x2). This is done twice to arrive at the 28x28 output image. The output layer is a Conv2D layer with a kernel size of 7x7 and using a sigmoid activation function to ensure the output values are in the desired range of [0,1]. The generator model is not compiles as it is not trained directly.</p><pre># define the standalone generator model</pre><pre>def define_generator(latent_dim):<br>  input = Input(shape=(latent_dim,))</pre><pre>  #creating enough activations for our (28,28,1) input image<br>  nodes = 128 * 7 * 7</pre><pre>  gen = Dense(nodes)(input)<br>  gen = LeakyReLU(0.2)(gen)<br>  gen = Reshape((7,7,128)) (gen)</pre><pre>  #upsample 14x14<br>  fc = Conv2DTranspose(128,(4,4),strides=(2,2),padding=&#39;same&#39;)(gen)<br>  fc = LeakyReLU(0.2)(fc)</pre><pre>  #upsample 28x28<br>  fc = Conv2DTranspose(128,(4,4),strides=(2,2),padding=&#39;same&#39;)(fc)<br>  fc = LeakyReLU(0.2)(fc)</pre><pre>  #ouput<br>  out_layer = Conv2D(1,(7,7),activation=&#39;tanh&#39;,padding=&#39;same&#39;)(fc)</pre><pre>  #define model<br>  model = Model(input,out_layer)<br>  model.summary()</pre><pre>  return model</pre><p>Plotting the generator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*PzGpewKkZU_AVJqZjBdxEA.png" /><figcaption>Generator model Plot</figcaption></figure><p>When the discriminator model is relatively good at detecting fake samples then the generator model is updated more whereas when the discriminator model is poor at detecting fake samples, the weights of the generator model is updated less. A new GAN model can be defined which takes a random input, generate samples and provide it as input to the discriminator model and output of the discriminator model is used to update the weight of the generator model.</p><pre># the generator model is updated via the unsupervised discriminator</pre><pre>def define_gan(g_model,d_model):</pre><pre>  # make weights in the discriminator model not trainable<br>  d_model.trainable = False</pre><pre>  # connect image output from generator as input to the discriminator<br>  gan_output = d_model(g_model.output)</pre><pre>  # define gan model as taking noise and ouputting a classification<br>  model = Model(g_model.input,gan_output)</pre><pre>  # compile model<br>  opt = Adam(lr=0.0002,beta_1=0.5)</pre><pre>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=opt)</pre><pre>  return model</pre><p>We create a latent space which would provide the points as an input to our generator model to generate images. This can be done using randn() function which generates arrays of random numbers from a standard Gaussian distribution. The arrays can be reshaped such as n rows with 100 elements (latent_dimension is set to 100) per row.</p><pre># generate latent space<br>def generate_latent_space(latent_dim,n_samples):<br>  # generate points in latent space<br>  X = randn(latent_dim*n_samples)  # reshape into a batch of inputs  for the network<br>  X = X.reshape(n_samples,latent_dim)<br>  return X</pre><p>The points from the latent space can be used as inputs to the generator model to generate new samples.</p><pre># use the generator to generate n fake samplesdef generate_fake_samples(model,latent_dim,n_samples):</pre><pre>  X = generate_latent_space(latent_dim,n_samples)<br>  X_output = model.predict(X)<br>  y = zeros((n_samples,1))<br>  return X_output,y</pre><p>We need to train our discriminator model on both real and fake images. Firstly, we create a method that would load real samples. We use mnist.load_data() function to load the MNIST dataset. The images loaded are 2D arrays of pixels however neural networks expect 3D arrays as input. Hence we would add an additional dimension for grayscale channel using the expand_dims() function of Numpy. Finally we normalize our image by making all the pixel values lie between [0,1]. All the steps are done in the function load_real_samples.</p><pre># getting all the required inputs</pre><pre>def load_real_samples():</pre><pre>  (trainX,trainY),(testX,testY) = load_data()<br>  X = expand_dims(trainX,axis=-1)<br>  X = X.astype(&#39;float32&#39;)</pre><pre>  # making values between [-1,1]<br>  X = (X - 127.5) / 127.5<br>  return [X,trainY]</pre><p>A subset of the training dataset is selected which has labels and is used to train the supervised version of the discriminator model using the function select_supervised_samples. The function makes sure that the examples are selected at random and the classes are balanced.</p><pre># select as supervised subset of the dataset , ensure classes are balanced</pre><pre>def select_supervised_samples(dataset,n_samples=100,n_classes=10):</pre><pre>  X,y = dataset<br>  X_list , y_list = list(), list()</pre><pre>  n_samples_per_class = int(n_samples / n_classes)</pre><pre>  for i in range(n_classes):<br>    # get all the images with specified class</pre><pre>    X_class = X[y == i]</pre><pre>    #choose random instances<br>    ix = randint(0,len(X_class),n_samples_per_class)</pre><pre>    #add to the list<br>   [X_list.append(X_class[j]) for j in ix]<br>   [y_list.append(i) for j in ix]</pre><pre> return np.array(X_list), np.array(y_list)</pre><p><strong>GAN Model Training</strong></p><p>The model training firstly involves getting the labeled subset of the training dataset and calculating the number of training steps. Supervised model is trained on the labeled examples and the unsupervised model is updated using the real and fake samples. Finally, the generator model is updated through the composite model.</p><pre>#train the generator and discriminator</pre><pre>def train_gan(gen_model,d_model,c_model,gan_model,dataset,latent_dim,n_epochs=20,n_batches=100):</pre><pre>  half_batch = int(n_batches/2)</pre><pre>  # calculate no of batches per epoch<br>  batches_per_epoch = int(dataset[0].shape[0]/n_batches)</pre><pre>  #calculating no of training iterations<br>  n_steps = int(batches_per_epoch * n_epochs)</pre><pre>  X_sup, y_sup = select_supervised_samples(dataset)</pre><pre>  print(X_sup.shape,y_sup.shape)</pre><pre>  for i in range(n_steps):<br>    <br>    # update the supervised discriminator<br>    [X_supReal, y_supReal],_ = generate_real_samples([X_sup,y_sup],half_batch)</pre><pre>    c_loss,c_acc =  c_model.train_on_batch(X_supReal,y_supReal)</pre><pre>    # update the unsupervised discriminator<br>    [X_real,_],y_real = generate_real_samples(dataset,half_batch)</pre><pre>    dlossreal = d_model.train_on_batch(X_real,y_real)</pre><pre>    X_fake, y_fake = generate_fake_samples(latent_dim,half_batch,gen_model)</pre><pre>    dlossfake = d_model.train_on_batch(X_fake,y_fake)</pre><pre>    #update the generator<br>    X_gan = generate_latent_points(latent_dim,n_batches)<br>    y_gan = np.ones((n_batches,1))<br>    <br>    gan_model.train_on_batch(X_gan,y_gan)</pre><p>Training the model for 12000 steps. We get a classification accuracy of around 93.37%.</p><pre># latent space<br>latent_dim = 100</pre><pre># discriminator model<br>d_model,c_model = define_discriminator()</pre><pre>#generator model<br>gen = define_generator(latent_dim)</pre><pre>#gan model<br>gan = define_gan(gen,d_model)</pre><pre>#load dataset<br>dataset = load_real_samples()</pre><pre>#train images<br>train_gan(gen,d_model,c_model,gan,dataset,latent_dim)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*kHlHYHv0jBqr8p4_zxMGYA.png" /></figure><p>Evaluating our supervised model on Test dataset gives us around 94% classification accuracy.</p><pre># Evaluating on the training data<br>classifier_model.evaluate(trainX,trainY)</pre><pre>#Evaluating on the testing data<br>classifier_model.evaluate(testX,testY)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_FF9NwVTYskDOQpdwdy9g.png" /></figure><p>Using our trained generator model to generate 100 random images of MNIST handwritten digits in a 10x10 grid.</p><pre># generating 100 new images with our generator model<br>latent_dim = 100<br>images,y = generate_fake_samples(latent_dim,100,gen_model)</pre><pre>for i in range(100):<br>  plt.subplot(10,10,i+1)</pre><pre>  plt.axis(&#39;off&#39;)</pre><pre>  plt.imshow(images[i,:,:,0],cmap=&#39;gray_r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*OZf_46DywxhvszzbnNEKGw.png" /><figcaption>Generated Plot</figcaption></figure><p>The image generated by our Semi-Supervised GAN model seems to be of better quality as compared to the generated images by other GAN models.</p><p>We have implemented other GAN models to generate MNIST handwritten digits as well and the articles can be found from the following links.</p><p><a href="https://saifgazali.medium.com/deep-convolutional-gan-for-mnist-handwritten-digits-7e18496b3e3e">Deep Convolutional GAN</a></p><p><a href="https://saifgazali.medium.com/conditional-gan-for-mnist-handwritten-digits-7e4c2967a341">Conditional GAN</a></p><p><a href="https://saifgazali.medium.com/auxiliary-gan-for-mnist-handwritten-digits-fcea053631d4">Auxiliary GAN</a></p><p><strong>Resources</strong></p><p><a href="https://arxiv.org/abs/1606.01583">Semi-Supervised Learning with Generative Adversarial Networks, 2016</a>.</p><p><a href="https://arxiv.org/abs/1606.03498">Improved Techniques for Training GANs, 2016.</a></p><p><a href="https://arxiv.org/abs/1511.06390">Unsupervised and Semi-supervised Learning with Categorical Generative Adversarial Networks, 2015</a>.</p><p><a href="https://machinelearningmastery.com/">Machine Learning Mastery</a></p><p><a href="https://keras.io/">Keras API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5132efcc82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auxiliary GAN for MNIST Handwritten Digits]]></title>
            <link>https://saifgazali.medium.com/auxiliary-gan-for-mnist-handwritten-digits-fcea053631d4?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcea053631d4</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[mnist]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 21:07:00 GMT</pubDate>
            <atom:updated>2021-08-04T21:07:00.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*n3fYddHLlbPUZKG1ExDwSg.png" /><figcaption>Photo by<a href="https://www.geeksforgeeks.org/understanding-auxiliary-classifier-gan/"> GeeksForGeeks</a></figcaption></figure><p>Generative Adversarial networks train deep convolutional neural networks for generating images. GAN requires a discriminator model for classifying whether a given image is real or fake and a generator model that transform an input into an image of pixel values. In this article we would be using MNIST handwritten digits dataset which is a standard image dataset allowing us to focus on GAN architecture.</p><p>The Auxiliary GAN is an extension of the Conditional GAN in which the discriminator model predicts class label of a given image rather than receive it as input. The training process is further stabilized and leads to generation of high quality images. Hence the discriminator model would predict whether the given image is real or fake and also the class label of the image. The generator model is provided both with a latent space point and the class label as input and it produces an image of that class label.</p><p><strong>Discriminator model</strong></p><p>The discriminator model comprises of an auxiliary classifier to classify the image and both of them can be considered as separate models but sharing the same model weights. In our model generation we would have a single fully connected neural network with 2 output. One for predicting whether the image is real or fake and the output would be a probability using the sigmoid activation function and the other is the probability of an image belonging to a class via the softmax activation function which is used for multiclass classification.</p><p>The discriminator model seeks to maximize the probability of predicting whether the image is real or fake and correctly predicting the image class label. The generator minimizes the ability of the discriminator to segregate real and fake images while also maximizing the discriminator’s ability to predict the class label of image. The appendix of the AC-GAN paper provides recommendations for the model configuration. The table summarizes the suggestions from the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*8BRMcgNBA3AXIDGjQC7OYg.png" /><figcaption>AC-GAN paper suggestion</figcaption></figure><p>The discriminator model is defined according to DCGAN architecture using Batchnormalization, LeakyReLU and Dropout. However the way in which AC-GAN discriminator differs from the traditional one is that it has 2 output layers. The model is trained using binary cross-entropy and categorical cross-entropy loss. In order to compare integer class labels directly rather than comparing a one hot encoding of the class labels we use sparse categorical cross-entropy instead of binary cross-entropy. The model is fit using the Adam optimizer with a miniscule learning rate recommended for DCGANs.</p><pre># define discriminator model</pre><pre>def define_discriminator(input_shape=(28,28,1),n_classes=10):</pre><pre>  init = RandomNormal(stddev=0.02)</pre><pre>  input_img = Input(shape=input_shape)</pre><pre>  #downsample to 14x14<br>  model = Conv2D(32,(3,3),strides=(2,2),kernel_initializer=init,padding=&#39;same&#39;)(input_img)</pre><pre>  model = LeakyReLU(0.2)(model)<br>  model = Dropout(0.5)(model)</pre><pre>  #normal<br>  model = Conv2D(64,(3,3),kernel_initializer=init,padding=&#39;same&#39;)(model)<br>  model = BatchNormalization()(model)<br>  model = LeakyReLU(0.2)(model)<br>  model = Dropout(0.5)(model)</pre><pre>  #downsample to 7x7<br>  model = Conv2D(128,(3,3),strides=(2,2),kernel_initializer=init,padding=&#39;same&#39;)(model)</pre><pre>  model = BatchNormalization()(model)<br>  model = LeakyReLU(0.2)(model)<br>  model = Dropout(0.5)(model)</pre><pre>  #normal<br>  model = Conv2D(256,(3,3),kernel_initializer=init,padding=&#39;same&#39;)(model)<br>  model = BatchNormalization()(model)<br>  model = LeakyReLU(0.2)(model)<br>  model = Dropout(0.5)(model)</pre><pre>  #flatten feature maps<br>  model = Flatten()(model)</pre><pre>  #classifier model predicting real or fake<br>  out_layer1 = Dense(1,activation=&#39;sigmoid&#39;)(model)</pre><pre>  #classifier model to predict the class of an image<br>  out_layer2 = Dense(n_classes,activation=&#39;softmax&#39;)(model)</pre><pre>  disc_model = Model(input_img,[out_layer1,out_layer2])</pre><pre>  # compile model<br>  opt = Adam(lr=0.0002, beta_1=0.5)</pre><pre>  disc_model.compile(loss=[&#39;binary_crossentropy&#39;, &#39;sparse_categorical_crossentropy&#39;],optimizer=opt)</pre><pre>  return disc_model</pre><p>Plotting our discriminator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*SklafUwMuVR4Z0LXXekBew.png" /></figure><p><strong>Generator model</strong></p><p>The generator model takes latent space point and a class label to generate an image. The class label can be provided as an additional channel in generator model by using an embedding layer, the output of which can be interpreted by a fully connected layer with a liner activation. Multiple feature maps of 7 x 7 are created to provide a basis for a low resolution version of the output image. The feature maps are passed through convolutional transpose layers to upsample. The final output is a grayscale image of 28x28 and pixels lying in the range[-1,1].</p><pre># define standalone generator which takes input a latent space and class label</pre><pre>def define_generator(latent_dim,n_classes=10):</pre><pre>  #label input<br>  label_input = Input(shape=(1,))<br>  nodes = 7*7<br>  init = RandomNormal(stddev=0.002)</pre><pre>  li = Embedding(n_classes,50)(label_input)<br>  li = Dense(nodes,kernel_initializer=init)(li)<br>  li = Reshape((7,7,1))(li)</pre><pre>  #image input<br>  image_input = Input(shape=(latent_dim,))<br>  m_nodes = 384*7*7</pre><pre>  gen = Dense(m_nodes,kernel_initializer=init)(image_input)<br>  gen = Activation(&#39;relu&#39;)(gen)<br>  gen = Reshape((7,7,384))(gen)</pre><pre>  #merge the inputs<br>  merge = Concatenate()([gen,li])</pre><pre>  #upsample<br>  gen = Conv2DTranspose(192,(5,5),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(merge)<br>  gen = BatchNormalization()(gen)<br>  gen =  Activation(&#39;relu&#39;)(gen)</pre><pre>  gen = Conv2DTranspose(1,(5,5),strides=(2,2),padding=&#39;same&#39;,kernel_initializer=init)(gen)</pre><pre>  out_layer = Activation(&#39;tanh&#39;)(gen)</pre><pre>  #Model<br>  model = Model([image_input,label_input],out_layer)<br>  return model</pre><p>Plotting the generator model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*XxmzPEVz5ZHwX51e4Jo4tQ.png" /></figure><p><strong>AC-GAN model</strong></p><p>When the discriminator model is relatively good at detecting fake samples then the generator model is updated more whereas when the discriminator model is poor at detecting fake samples, the weights of the generator model is updated less. A new GAN model can be defined which takes a random input, generate samples and provide it as input to the discriminator model and output of the discriminator model is used to update the weight of the generator model. The discriminator can be trained on real and fake samples in a standalone manner whereas the generator gets updated according to the performance of the discriminator model on detecting fake samples. Therefore the discriminator which is part of the new GAN model is marked as not trainable</p><pre># define gan model</pre><pre>def define_gan(g_model,d_model):</pre><pre>  #make discrimnator model non trainable<br>  d_model.trainable = False</pre><pre>  #output of generator model acts as input to the discriminator model<br>  gan_output = d_model(g_model.output)</pre><pre>  # define our gan model which takes noise and label as input and  outputs a classification<br>  model = Model(g_model.input,gan_output)<br>  opt = Adam(learning_rate=0.0002,beta_1=0.5)<br>  model.compile(loss=[&#39;binary_crossentropy&#39;,&#39;sparse_categorical_crossentropy&#39;],optimizer=opt)</pre><pre>  return model.</pre><p>Plotting the GAN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*y91CcRbUPyg0uLuDX4hQEg.png" /></figure><p><strong>Loading Dataset</strong></p><p>Loading the MNIST dataset from the Keras dataset. The images returned are 2D array but for providing them as input to the Embedding layer which expects 3D array, we add a new channel. We also normalize the images such that all the pixel values lies in [-1,1].</p><pre># getting the data for our AC gan</pre><pre>def load_real_samples():<br>  (trainX,trainY),(testX,testY) = load_data()<br>   X = expand_dims(trainX,axis=-1)</pre><pre>   X = X.astype(&#39;float32&#39;)</pre><pre>   #scale to [-1,1]<br>   X = (X-127.5)/127.5</pre><pre>   return [X,trainY]</pre><p>In order to select a batch of samples from our dataset we will use the following generate_real_samples method.</p><pre># generate real samples</pre><pre>def generate_real_samples(dataset,n_samples):</pre><pre>  images, labels = dataset</pre><pre>  # create random instances<br>  ix = randint(0,images.shape[0],n_samples)</pre><pre>  #get random images and labels<br>  X,labels = images[ix],labels[ix]</pre><pre>  #create labels for our samples i.e they are real<br>  y = np.ones((n_samples,1))</pre><pre>  return [X,labels],y</pre><p>We create a method to provide latent space points as input to the generator.</p><pre># generate latent space</pre><pre>def generate_latent_points(latent_dim,n_samples,n_classes=10):</pre><pre>  # generate latent space<br>  x_input = randn(latent_dim * n_samples)</pre><pre>  # reshape it<br>  z_input = x_input.reshape(n_samples,latent_dim)</pre><pre>  # generate labels<br>  labels = randint(0,n_classes,n_samples)</pre><pre>  return [z_input,labels]</pre><p>The generate_fake_samples() modifies the ouput from the above method such that it can be used as input by the generator model.</p><pre># generate fake samples</pre><pre>def generate_fake_samples(latent_dim,n_samples,gen_model):</pre><pre>  #generate latent space<br>  X,labels = generate_latent_points(latent_dim,n_samples)</pre><pre>  #generate image<br>  images = gen_model.predict([X,labels])</pre><pre>  #create the labels for the images<br>  y = np.zeros((n_samples,1))</pre><pre>  return [images,labels],y</pre><p><strong>Model Training</strong></p><p>We can now train our GAN model for around 100 epochs. Discriminator model is trained for half batch of real and fake images each. The generator is then updated via the composite GAN model. We save our generator model after every 10 epochs. A batch size of 128 is used as we have 60,000 images, for each training epoch we would have around 468 batches of real and fake samples each.</p><pre>def train_gan(gen_model,disc_model,gan_model,dataset,latent_dim,n_epochs=100,n_batches=64):</pre><pre>  #no of batches per epoch<br>  no_of_batches_per_epoch = int(dataset[0].shape[0]/n_batches)</pre><pre>  #no of steps<br>  n_steps = int(no_of_batches_per_epoch * n_epochs)</pre><pre>  #half batch so we can train the discriminator on real images and fake images of length half the batch size each.<br>  half_batch = int(n_batches/2)</pre><pre>  for i in range(n_steps):<br>    print(&#39;step &#39;,i)</pre><pre>    #generate real samples<br>    [X_real,labels_real],y_real = generate_real_samples(dataset,half_batch)</pre><pre>    #generate fake samples<br>    [X_fake,labels_fake],y_fake = generate_fake_samples(latent_dim,half_batch,gen_model)</pre><pre>    #train the discriminator on the real samples<br>    disc_model.train_on_batch(X_real,[y_real,labels_real])</pre><pre>    #train the discriminator on the fake samples<br>    disc_model.train_on_batch(X_fake,[y_fake,labels_fake])</pre><pre>    # generate inputs for the gan model<br>    [z_inputs,z_labels] = generate_latent_points(latent_dim,n_batches)</pre><pre>    #inverted labels for real or fake<br>    y_gan = np.ones((n_batches,1))</pre><pre>    gan_model.train_on_batch([z_inputs,z_labels],[y_gan,z_labels])</pre><pre>    if (i + 1)%(no_of_batches_per_epoch * 10)==0:<br>       summarize_perf(i,gen_model,latent_dim)</pre><p>Dimension of the latent space is set to 100 and we train our composite GAN model for 100,000 steps.</p><pre>#latent dimension<br>latent_dim = 100</pre><pre># define discriminator<br>disc = define_discriminator()</pre><pre># define generator<br>gen = define_generator(latent_dim)</pre><pre>#define gan model<br>gan = define_gan(gen,disc)</pre><pre>#load dataset<br>dataset = load_real_samples()</pre><pre>#train our gan<br>train_gan(gen,disc,gan,dataset,latent_dim)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*NUf4JwKS6bsT9ok7FOOWEg.png" /></figure><p>We can create a method to save a plot of generate images in a grid of specified n x n images.</p><pre>def save_plot(X,n):<br>  for i in range(n*n):<br>    plt.axis(&#39;off&#39;)    <br>    plt.subplot(n,n,i+1)    <br>    plt.imshow(X[i,:,:,0],cmap=&#39;gray_r&#39;)  <br>  plt.show()</pre><p>Plotting 100 randomly generated images in a 10x10 grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nq-Qljy72fLGtSttQXCGSQ.png" /></figure><p><strong>Resources</strong></p><p><a href="https://openreview.net/forum?id=BkDDM04Ke">Conditional Image Synthesis With Auxiliary Classifier GANs, Reviewer Comments</a></p><p><a href="https://machinelearningmastery.com/">Machine Learning Mastery</a></p><p><a href="https://keras.io/">Keras API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcea053631d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional GAN for MNIST Handwritten Digits]]></title>
            <link>https://saifgazali.medium.com/conditional-gan-for-mnist-handwritten-digits-7e4c2967a341?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4c2967a341</guid>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 17:39:55 GMT</pubDate>
            <atom:updated>2021-08-03T17:39:55.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4H1RzvDQKCgm6N5GyI2REg.jpeg" /><figcaption>Photo by <a href="https://www.youtube.com/watch?v=71Wg3GQGyx0">Developers Hutt</a></figcaption></figure><p>Generative Adversarial Networks includes a generator model which is capable of generating new plausible fake samples that can be considered to be coming from an existing distribution of samples and a discriminator model that would classify the given sample as real or fake. The model weights of discriminator and the generator are updated according to the performance of the discriminator model.</p><p>Conditional GAN involves conditional generation of images by a generator model. It has the ability to generate targeted images of a given type unlike other GAN model which generates a random image from the domain. In this article Conditional generative adversarial network is developed for the targeted generation of MNIST handwritten digits.</p><p>The Modified National Institute of Standards and Technology dataset contains 70,000 grayscale 28x28 pixel images of handwritten digits between 0 and 9. The dataset can be accessed using mnist.load_dataset() function which Keras provides. It automatically returns the training and testing dataset.</p><pre>import tensorflow</pre><pre>from tensorflow.keras.datasets.mnist import load_data</pre><pre>(trainX,trainY), (testX,testY) = load_data()</pre><p>We can plot some of the images from the training set using the matplotlib library imshow() function. We plot 25 images into a 5x5 matrix shape.</p><pre>import matplotlib.pyplot as pyplot<br>for i in range(25):<br>  # define subplot<br>  pyplot.subplot(5, 5, 1 + i)  # turn off axis<br>  pyplot.axis(&#39;off&#39;)  # plot raw pixel data<br>  pyplot.imshow(trainX[i], cmap=&#39;gray_r&#39;)pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*6I2f7RogAhG4usEJocTcNg.png" /></figure><p><strong>Discriminator model</strong></p><p>The discriminator model must take an image from the dataset and detect whether it is a real or fake image. The model would have the shape of the image and an integer for the class label of the image as its input. The class label is passed through an Embedding layer with the size of 50. Each of the class label would map to a different 50 vector representation. The output is passed to a fully connected layer. The Dense layer has enough activations which can be reshaped into single 28 x 28 activation map and concatenated with the input image. Hence the next layer would have 2 channel input image.</p><pre># define standalone discriminator</pre><pre>def define_discriminator(input_shape=(28,28,1),n_classes=10):</pre><pre>  # label input<br>  in_labels = Input(shape=(1,))</pre><pre>  # Embedding for categorical input<br>  em = Embedding(n_classes,50)(in_labels)</pre><pre>  # scale up the image dimension with linear activations<br>  d1 = Dense(input_shape[0] * input_shape[1])(em)</pre><pre>  # reshape to additional channel<br>  d1 = Reshape((input_shape[0],input_shape[1],1))(d1)</pre><pre>  # image input<br>  image_input = Input(shape=input_shape)</pre><pre>  #  concate label as channel<br>  merge = Concatenate()([image_input,d1])</pre><pre>  # downsample<br>  fe = Conv2D(128,(3,3),strides=(2,2),padding=&#39;same&#39;)(merge)<br>  fe = LeakyReLU(0.2)(fe)</pre><pre>  # downsample<br>  fe = Conv2D(128,(3,3),strides=(2,2),padding=&#39;same&#39;)(merge)<br>  fe = LeakyReLU(0.2)(fe)</pre><pre>  #flatten feature maps<br>  fe = Flatten()(fe)<br>  fe = Dropout(0.4)(fe)</pre><pre>  #ouput<br>  out_layer = Dense(1,activation=&#39;sigmoid&#39;)(fe)</pre><pre>  #define model<br>  model = Model([image_input,in_labels],out_layer)</pre><pre>  #compile model<br>  opt = Adam(lr=0.0002,beta_1=0.5)<br>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=opt,metrics=  [&#39;accuracy&#39;])</pre><pre>  return model</pre><p>Plotting the discriminator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*7Gek49BZk1AuAhAn8M1LWA.png" /><figcaption>Discriminator model plot</figcaption></figure><p>Summary of the discriminator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*ZOCdYrlZCod4MDIUdiV2Sw.png" /><figcaption>Discriminator model summary</figcaption></figure><p><strong>Generator model</strong></p><p>The generator model takes a point from the latent space as input and outputs plausible image of handwritten digits. The latent space is a vector space of standard Gaussian distributed values. The generator model takes the class label which makes the point in the latent space conditional on the provided class label. The class label passes through an Embedding layer which maps it to a 50 element vector and is then passed through a fully connected layer. The new 7x7 feature map is added as one more channel (for class labels) to the 128 making it 129 feature maps that are upsampled in the next layers using Conv2dTranspose and LeakyReLU activation function.</p><pre># define standalone generator model</pre><pre>def define_generator(latent_dim,n_classes=10):<br>  label_input = Input(shape=(1,))</pre><pre>  #Embedding layer<br>  em = Embedding(n_classes,50)(label_input)</pre><pre>  nodes = 7*7<br> <br>  em = Dense(nodes)(em)<br>  em = Reshape((7,7,1))(em)</pre><pre>  #image generator input<br>  image_input = Input(shape=(latent_dim,))</pre><pre>  nodes = 128*7*7<br>  d1 = Dense(nodes)(image_input)<br>  d1 = LeakyReLU(0.2)(d1)<br>  d1 = Reshape((7,7,128))(d1)</pre><pre>  # merge<br>  merge = Concatenate()([d1,em])</pre><pre>  #upsample to 14x14<br>  gen = Conv2DTranspose(128,(4,4),strides=(2,2),padding=&#39;same&#39;)(merge)<br>  gen = LeakyReLU(0.2)(gen)</pre><pre>  #upsample to 28x28<br>  gen = Conv2DTranspose(128,(4,4),strides=(2,2),padding=&#39;same&#39;)(gen)<br>  gen = LeakyReLU(0.2)(gen)</pre><pre>  #output layer <br>  out_layer = Conv2D(1,(7,7),activation=&#39;tanh&#39;,padding=&#39;same&#39;)(gen)</pre><pre>  #define model <br>  model = Model([image_input,label_input],out_layer)</pre><pre>  return model</pre><p>Summary of the generator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*v6xmoWzos96ZAIb7X1pOCg.png" /><figcaption>Generator model summary</figcaption></figure><p>Plotting the generator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*Cp71tUU7FQyRk_AIRKLczg.png" /><figcaption>Generator model plot</figcaption></figure><p><strong>GAN model</strong></p><p>When the discriminator model is relatively good at detecting fake samples then the generator model is updated more whereas when the discriminator model is poor at detecting fake samples, the weights of the generator model is updated less. A new GAN model can be defined which takes a random input, generate samples and provide it as input to the discriminator model and output of the discriminator model is used to update the weight of the generator model. The GAN model would take latent space point and a class label and predict whether the input is real or fake. The discriminator model in the GAN model as non trainable as it is updated it in a standalone manner on real as well as fake images.</p><pre># defining the combined generator and discriminator model for updating the generator</pre><pre>def define_gan(g_model,d_model):</pre><pre>  # make the discriminator layer as non trainable<br>  d_model.trainable = False</pre><pre>  # get the noise and label input from the generator<br>  gen_noise, gen_label = g_model.input</pre><pre>  # get the output from the generator<br>  gen_output = g_model.output</pre><pre>  #connect image output and label input from generator as inputs to      #discriminator</pre><pre>  gan_output = d_model([gen_output,gen_label])</pre><pre>  #define gan model as taking noise and label and outputting a #classification</pre><pre>  model = Model([gen_noise,gen_label],gan_output)</pre><pre>  opt = Adam(lr=0.0002,beta_1=0.5)</pre><pre>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=opt)</pre><pre>  return model</pre><p>Plotting our GAN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*KFlYG-G1M696pAHVs6DvxQ.png" /><figcaption>GAN model Plot</figcaption></figure><p><strong>Loading Dataset</strong></p><p>Loading the MNIST dataset from the Keras dataset. The images returned are 2D array but for providing them as input to the Embedding layer which expects 3D array, we add a new channel. We also normalize the images such that all the pixel values lies in [-1,1].</p><pre># load mnsit images</pre><pre>def load_real_samples():</pre><pre>  (trainX,trainY),(testX,testY) = load_data()</pre><pre>  # expand to 3d<br>  X = expand_dims(trainX,axis=-1)</pre><pre>  #make it float<br>  X = X.astype(&#39;float32&#39;)</pre><pre>  # scale from [0,255] tp [-1,1]<br>  X = (X - 127.5) / 127.5</pre><pre>  return [X,trainY]</pre><p>In order to select a batch of samples from our dataset we will use the following generate_real_samples method.</p><pre># select real samples</pre><pre>def generate_real_samples(dataset,n_samples):</pre><pre>  # split into images and labels<br>  images,labels = dataset</pre><pre>  #choose random instances<br>  ix = randint(0,images.shape[0],n_samples)</pre><pre>  # select images and labels<br>  X, Labels = images[ix], labels[ix]</pre><pre>  # generate class labels<br>  y = ones((n_samples,1))</pre><pre>  return [X,Labels], y</pre><p>We create a method to provide latent space points as input to the generator.</p><pre># generate points in latent space as input for the generator</pre><pre>def generate_latent_points(laten_dim,n_samples,n_classes=10):<br>  # generate points in the latent space<br>  x_input = randn(latent_dim*n_samples)</pre><pre>  # reshape into a batch of inputs to the network<br>  z_input = x_input.reshape(n_samples,latent_dim)</pre><pre>  # generate labels<br>  labels = randint(0,n_classes,n_samples)</pre><pre>  return [z_input,labels]</pre><p>The generate_fake_samples() modifies the ouput from the above method such that it can be used as input by the generator model.</p><pre># use generator to generate n fake samples, with class labels</pre><pre>def generate_fake_samples(latent_dim,n_samples,generator):</pre><pre>  #generate points in latent space<br>  z_input,labels = generate_latent_points(latent_dim,n_samples)</pre><pre>  #predict outputs<br>  images = generator.predict([z_input,labels])</pre><pre>  # create class labels<br>  y = zeros((n_samples,1))</pre><pre>  return [np.array(images),labels],y</pre><p><strong>Model Training</strong></p><p>We can now train our GAN model for around 100 epochs. Discriminator model is trained for half batch of real and fake images each. The generator is then updated via the composite GAN model. We save our generator model after every 10 epochs. A batch size of 128 is used as we have 60,000 images, for each training epoch we would have around 468 batches of real and fake samples each.</p><pre>def train_gan(gen_model,disc_model,gan_model,latent_dim,dataset,n_epochs=100,n_batches=128):</pre><pre>  batches_per_epoch = int(dataset[0].shape[0]/n_batches)</pre><pre>  half_batch = int(n_batches/2)</pre><pre>  for i in range(n_epochs):</pre><pre>    print(&#39;epoch &#39;,i)<br>    for j in range(batches_per_epoch):<br>      #generate real samples<br>      [X_real,labels_real], y_real = generate_real_samples(dataset,half_batch)</pre><pre>      #generate fake samples<br>      [X_fake,labels_fake], y_fake = generate_fake_samples(latent_dim,half_batch,gen_model)</pre><pre>      # train the discriminator on real and fake samples<br>      loss_real,acc_real = disc_model.train_on_batch([X_real,labels_real],y_real)<br>      loss_fake,acc_fake = disc_model.train_on_batch([X_fake,labels_fake],y_fake)</pre><pre>      # prepare points in the latent space as input to the generator<br>      [z_input,labels_input] = generate_latent_points(latent_dim,n_batches)</pre><pre>      # create inverted labels for fake samples<br>      y_gan = ones((n_batches,1))</pre><pre>      #update the generator model via the discriminator<br>      g_loss = gan_model.train_on_batch([z_input,labels_input],y_gan)</pre><pre>  if ((i+1)%10) == 0:<br>   gen_model.save(&#39;c_gan%3d.h5&#39;%i)</pre><p>Dimension of the latent space is set to 100 and we train our composite GAN model for 100 epochs.</p><pre># size of the latent dimensions<br>latent_dim = 100</pre><pre>#discriminator model<br>discriminator = define_discriminator()</pre><pre>#generator model<br>generator = define_generator(latent_dim)</pre><pre>#create the gan model<br>gan = define_gan(generator,discriminator)</pre><pre>#dataset<br>dataset = load_real_samples()</pre><pre>#train model<br>train_gan(generator,discriminator,gan,latent_dim,dataset)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*ag8oaJZtBzq6nv3DkIYPTw.png" /></figure><p>We can create a method to save a plot of generate images in a grid of specified n x n images.</p><pre>def save_plot(X,n):<br>  for i in range(n*n):<br>    plt.axis(&#39;off&#39;)</pre><pre>    plt.subplot(n,n,i+1)</pre><pre>    plt.imshow(X[i,:,:,0],cmap=&#39;gray_r&#39;)</pre><pre>  plt.show()</pre><p>In order for our generator model to make prediction we would need latent space points and the specific labels for which the images should be generated.</p><pre># latent_dim</pre><pre>latent_dim = 100</pre><pre>[inputs,labels] = generate_latent_points(latent_dim,100)</pre><pre>labels = np.asarray([x for _ in range(10) for x in range(10)])</pre><pre>X = model.predict([inputs,labels])</pre><pre>save_plot(X,10)</pre><p>Plotting the images generated by our GAN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*87Nxy-fq1qCdlBIbTfXf_g.png" /><figcaption>Handwritten digits generated by our GAN model</figcaption></figure><p><strong>Resources</strong></p><p><a href="https://arxiv.org/abs/1411.1784">Conditional Generative Adversarial Nets, 2014.</a></p><p><a href="https://arxiv.org/abs/1611.07004">Image-To-Image Translation With Conditional Adversarial Networks, 2017.</a></p><p><a href="https://machinelearningmastery.com/">Machine Learning Mastery</a></p><p><a href="https://keras.io/">Keras API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4c2967a341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Convolutional GAN for MNIST Handwritten digits]]></title>
            <link>https://saifgazali.medium.com/deep-convolutional-gan-for-mnist-handwritten-digits-7e18496b3e3e?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e18496b3e3e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 16:19:03 GMT</pubDate>
            <atom:updated>2021-08-01T16:19:03.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTYUL8Enns6ZjoON6hj-CQ.png" /><figcaption>Photo by <a href="https://developer.squareup.com/blog/making-ai-interpretable-with-generative-adversarial-networks/">SquareUp</a></figcaption></figure><p>Generative Adversarial networks train deep convolutional neural networks for generating images. GAN requires a discriminator model for classifying whether a given image is real or fake and a generator model that transform an input into an image of pixel values. In this article we would be using MNIST handwritten digits dataset which is a standard image dataset allowing us to focus on GAN architecture rather than data preprocessing part.</p><p>The Modified National Institute of Standards and Technology dataset contains 70,000 grayscale 28x28 pixel images of handwritten digits between 0 and 9. The dataset can be accessed using mnist.load_dataset() function which Keras provides. It automatically returns the training and testing dataset.</p><pre>import tensorflow</pre><pre>from tensorflow.keras.datasets.mnist import load_data</pre><pre>(trainX,trainY), (testX,testY) = load_data()</pre><p>Printing the shape out training and test dataset. We have around 60,000 images in training set and 10,000 images in the test set.</p><pre># summarize the shape of the dataset</pre><pre>print(&#39;Train&#39;, trainX.shape, trainY.shape) #Train (60000, 28, 28) (60000,)</pre><pre>print(&#39;Test&#39;, testX.shape, testY.shape) #Test (10000, 28, 28) (10000,)</pre><p>We can plot some of the images from the training set using the matplotlib library imshow() function. We plot 25 images into a 5x5 matrix shape.</p><pre>import matplotlib.pyplot as pyplot</pre><pre>for i in range(25):<br>  # define subplot<br>  pyplot.subplot(5, 5, 1 + i)</pre><pre>  # turn off axis<br>  pyplot.axis(&#39;off&#39;)</pre><pre>  # plot raw pixel data<br>  pyplot.imshow(trainX[i], cmap=&#39;gray_r&#39;)</pre><pre>pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*6I2f7RogAhG4usEJocTcNg.png" /></figure><p>The images from the dataset are used for training a Generative Adversarial Network and the generator model will be trained to develop new plausible images of handwritten digits between 0 and 9.</p><p><strong>Discriminator Model</strong></p><p>The discriminator model must take an image from the dataset and detect whether it is a real or fake image. Our discriminator model has 2 convolutional layers with 128 filters each and a stride of 2. Dropout layer is added for regularization and to reduce overfitting. We use LeakyReLU instead of ReLU which is the recommended on. Adam optimizer is used with a learning rate of 0.0002 and a momentum of 0.5.</p><pre># defining discriminator mode</pre><pre>def define_discriminator(input = (28,28,1)):<br>  model = Sequential()<br>  model.add(Conv2D(128,3,strides=(2,2),padding=&#39;same&#39;,input_shape=input))<br>  model.add(LeakyReLU(alpha=0.2))<br>  model.add(Dropout(0.4))</pre><pre>  model.add(Conv2D(128,3,strides=(2,2),padding=&#39;same&#39;))<br>  model.add(LeakyReLU(alpha=0.2))<br>  model.add(Dropout(0.4))</pre><pre>  model.add(Flatten())<br>  model.add(Dense(1,activation=&#39;sigmoid&#39;))<br>  opt = Adam(lr=0.002,beta_1=0.5)</pre><pre>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=opt,metrics=[&#39;accuracy&#39;])</pre><pre>  return model</pre><p>We would define the discriminator model and plot the summary.</p><pre>model = define_discriminator()<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*AyCWdSnJIADHwMqtGSP96g.png" /><figcaption>Model Summary</figcaption></figure><p><strong>Discriminator Model Training</strong></p><p>We need to train our discriminator model on both real and fake images. Firstly, we create a method that would load real samples. We use mnist.load_data() function to load the MNIST dataset. The images loaded are 2D arrays of pixels however neural networks expect 3D arrays as input. Hence we would add an additional dimension for grayscale channel using the expand_dims() function of Numpy. Finally we normalize our image by making all the pixel values lie between [0,1]. All the steps are done in the function load_real_samples.</p><pre>def load_real_samples():<br>  (trainX,_),(_,_) = load_data()</pre><pre>   X = expand_dims(trainX,axis=-1)</pre><pre>   X = X.astype(&#39;float32&#39;)</pre><pre>   X = X/255.0</pre><pre>   return X</pre><p>The model is updated in batches where in we select random images from the training set to train it. We would also return a class label of 1 specifying its a real image.</p><pre># define real samples</pre><pre>def generate_real_samples(dataset,n_samples):<br>  ix = randint(0,dataset.shape[0],n_samples)</pre><pre>  # retrieve selected images<br>  X = dataset[ix]</pre><pre>  # generate class labels<br>  y = ones((n_samples,1))</pre><pre>  return X,y</pre><p>For generating fake images we can use random pixel values in the range of [0,1].</p><pre># define fake samples<br>def generate_fake_samples(n_samples):<br>  X = rand(28*28*n_samples)</pre><pre>  X = X.reshape((n_samples,28,28,1))</pre><pre>  y = zeros((n_samples,1))</pre><pre>  return X,y</pre><p>Finally, we would train our discriminator model by using a batch of 256 images where 128 are real and 128 are fake images for each iteration. We train the model for 100 iterations using the train_on_batch method.</p><pre># train the discriminator model<br>def train_dicriminator(model,dataset,n_iter=100,n_batch=256):<br>  half_batch = int(n_batch/2)</pre><pre>  for i in range(n_iter):<br>    # generate real samples<br>    X_real,y_real = generate_real_samples(dataset,half_batch)</pre><pre>    # train the discriminator on the real samples<br>    lossreal,accreal = model.train_on_batch(X_real,y_real)</pre><pre>    # generate fake samples<br>    X_fake,y_fake = generate_fake_samples(half_batch)</pre><pre>    # train the discriminator on the real samples<br>    lossfake,accfake = model.train_on_batch(X_fake,y_fake)</pre><pre>    print(i+1,accreal,accfake)</pre><p>Training our discriminator model and printing out its accuracy for detecting real and fake images.</p><pre>model = define_discriminator()</pre><pre>dataset = load_real_samples()</pre><pre>train_dicriminator(model,dataset)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*SCoPSdLRfgYCo9i3AzbBkw.png" /><figcaption>Discriminator model training</figcaption></figure><p><strong>Generator Model</strong></p><p>The generator model takes a point from the latent space as input and outputs plausible image of handwritten digits. The latent space is a vector space of standard Gaussian distributed values. During training the generator model assign meaning to the latent points. The Dense layer is the first hidden layer that has enough nodes to represent a low resolution image (128 * 7 * 7 in our case where 7x7 is the size of image and as we would have multiple low resolution versions of output image we set that number to 128). We then need to reshape the output such as 128 different 7x7 feature maps. The next step involves upsampling the low resolution image to a high resolution version using the Conv2DTranspose layer by configuring the stride to (2x2). This is done twice to arrive at the 28x28 output image. The output layer is a Conv2D layer with a kernel size of 7x7 and using a sigmoid activation function to ensure the output values are in the desired range of [0,1]. The generator model is not compiles as it is not trained directly.</p><pre># define the generator model</pre><pre>def define_generator(input):<br>  model = Sequential()</pre><pre>  # foundations for 7x7 image<br>  model.add(Dense(128*7*7,input_dim=input))<br>  model.add(LeakyReLU(0.2))</pre><pre>  # reshape the image<br>  model.add(Reshape((7,7,128)))</pre><pre>  # upsample it to 14x14<br>  model.add(Conv2DTranspose(128,(4,4),strides=(2,2),padding=&#39;same&#39;))<br>  model.add(LeakyReLU(0.2))</pre><pre>  #upsample it to 28x28<br>  model.add(Conv2DTranspose(128,(4,4),strides=(2,2),padding=&#39;same&#39;))<br>  model.add(LeakyReLU(0.2))</pre><pre>  model.add(Conv2D(1,(7,7),activation=&#39;sigmoid&#39;,padding=&#39;same&#39;))</pre><pre>  return model</pre><p>Defining our generator model and plotting its summary.</p><pre># latent dimension<br>latent_dim = 100</pre><pre># generate a model<br>model = define_generator(latent_dim)<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*PnikxREo826QpV8cgj3UMQ.png" /><figcaption>Generator model summary</figcaption></figure><p>We create a latent space which would provide the points as an input to our generator model to generate images. This can be done using randn() function which generates arrays of random numbers from a standard Gaussian distribution. The arrays can be reshaped such as n rows with 100 elements (latent_dimension is set to 100) per row.</p><pre># generate latent space<br>def generate_latent_space(latent_dim,n_samples):</pre><pre>  # generate points in latent space<br>  X = randn(latent_dim*n_samples)</pre><pre>  # reshape into a batch of inputs for the network<br>  X = X.reshape(n_samples,latent_dim)</pre><pre>  return X</pre><p>The points from the latent space can be used as inputs to the generator model to generate new samples.</p><pre># use the generator to generate n fake samples</pre><pre>def generate_fake_samples(model,latent_dim,n_samples):<br>  X = generate_latent_space(latent_dim,n_samples)<br>  X_output = model.predict(X)</pre><pre>  y = zeros((n_samples,1))</pre><pre>  return X_output,y</pre><p>We can plot the random generated image by our generator model. The image would not make sense as our generator model is not yet trained.</p><pre>import matplotlib.pyplot as plt</pre><pre># latent dimension<br>latent_dim = 100</pre><pre># generate a model<br>model = define_generator(latent_dim)</pre><pre>n_samples = 10</pre><pre>X,y = generate_fake_samples(model,latent_dim,n_samples)</pre><pre>for i in range(n_samples):<br>  plt.imshow(X[i,:,:,0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*aTfK0WMXyzlI7fNIZ7G0Lw.png" /><figcaption>Random generated image</figcaption></figure><p><strong>Generator Model Training</strong></p><p>When the discriminator model is relatively good at detecting fake samples then the generator model is updated more whereas when the discriminator model is poor at detecting fake samples, the weights of the generator model is updated less. A new GAN model can be defined which takes a random input, generate samples and provide it as input to the discriminator model and output of the discriminator model is used to update the weight of the generator model.</p><p>The discriminator can be trained on real and fake samples in a standalone manner whereas the generator gets updated according to the performance of the discriminator model on detecting fake samples. Therefore the discriminator which is part of the new GAN model is marked as not trainable. Also the generated samples from the generator model are marked as real so the discriminator would detect it as real or fake and give a probability using which during backpropagation process the weights of the generator model is updated to minimize the loss.</p><pre># defining our gan model</pre><pre>def define_gan(generator,discriminator):<br>  # make the weights of discriminator as non trainable<br>  discriminator.trainable = False<br>  model = Sequential()<br>  model.add(generator)<br>  model.add(discriminator)</pre><pre>  opt = Adam(lr=0.002,beta_1=0.5)</pre><pre>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=opt,metrics=[&#39;accuracy&#39;])</pre><pre>  return model</pre><p>Defining our GAN model and plotting its summary.</p><pre># size of the latent space<br>latent_dim = 100</pre><pre># create the discriminator<br>d_model = define_discriminator()</pre><pre># create the generator<br>g_model = define_generator(latent_dim)</pre><pre># create the gan<br>gan_model = define_gan(g_model, d_model)</pre><pre># summarize gan mode<br>gan_model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*Lj8VBFhz9rnYJ5R9BFPI4g.png" /><figcaption>GAN model summary</figcaption></figure><p>Model training would include first updating the discriminator model with real and fake samples, then the generator model in the composite model is updated.</p><pre># Training our standalone discriminator and generator in gan</pre><pre>def train_gan(gen_model,disc_model,gan_model,dataset,latent_dim,n_epochs=50,n_batch=256):<br>  half_batch =int(n_batch/2)</pre><pre>  batch_per_epoch = int(dataset.shape[0]/n_batch)</pre><pre>  # manually enumerate epochs</pre><pre>  for i in range(n_epochs):<br>  # enumerate batches over the training set<br>    for j in range(batch_per_epoch):<br>      # generate random selected real samples<br>      X_real,y_real = generate_real_samples(dataset,half_batch)<br>     <br>      # generate fake samples<br>      X_fake, y_fake = generate_fake_samples(gen_model,latent_dim,half_batch)</pre><pre>      #train discriminator<br>      lossreal,accreal = disc_model.train_on_batch(X_real,y_real)<br>      lossfake,accfake = disc_model.train_on_batch(X_fake,y_fake)</pre><pre>      #train generator<br>      X_gan = generate_latent_space(latent_dim,n_batch)<br>      y_gan = ones((n_batch,1))<br> <br>      #update the generator via the discriminator&#39;s error<br>      loss,acc = gan_model.train_on_batch(X_gan,y_gan)</pre><pre>      if (i+1)%10 == 0:<br>       summarize_perf(i,gen_model,disc_model,dataset,latent_dim,100)</pre><p><strong>GAN Performance Evaluation</strong></p><p>Generally images generated by GANs are evaluated for quality by a human operator. Our approach would include 3 steps:</p><ol><li>Evaluate the accuracy of discriminator model on real and fake images.</li><li>Generate images using generator model periodically.</li><li>Save the generator model.</li></ol><p>We define a method summarize_performance to summarize the performance of the discriminator model by evaluating the accuracy of the discriminator model on real as well as fake images.</p><pre># evaluate the discriminator , plot and save the generated image</pre><pre>def summarize_perf(epoch,gen_model,disc_model,dataset,latent_dim,n_samples=100):</pre><pre>  X_real,y_real = generate_real_samples(dataset,n_samples)<br>  lossreal,accreal = disc_model.evaluate(X_real,y_real)</pre><pre>  X_fake,y_fake = generate_fake_samples(gen_model,latent_dim,n_samples)<br>  lossfake,accfake = disc_model.evaluate(X_real,y_real)</pre><pre>  print(accreal,accfake)</pre><pre>  #save plot<br>  save_plot(X_fake,epoch)</pre><pre>  #save the generator model<br>  filename = &#39;generated_model_%03d.h5&#39; % (epoch+1)<br>  gen_model.save(filename)</pre><p>We create a function to plot the images that are generated by our generator model. We plot 100 images as a 10x10 grid.</p><pre># create and save a plot of generated images</pre><pre># plot 100 images as 10x10 grid</pre><pre>def save_plot(examples,epoch,n=10):<br>  for i in range(n*n):<br>    plt.subplot(n,n,i+1)</pre><pre>    plt.axis(&#39;off&#39;)</pre><pre>    plt.imshow(examples[i,:,:,0],cmap=&#39;gray_r&#39;)</pre><pre> # save plot to file<br> filename = &#39;generated_plot_e%03d.png&#39; % (epoch+1)</pre><pre>  plt.savefig(filename)</pre><pre>  plt.close()</pre><p>Training our GAN model for around 50 epochs.</p><pre># size of the latent dim<br>latent_dim = 50</pre><pre># define discriminator<br>discriminator = define_discriminator()</pre><pre># define generator<br>generator = define_generator(latent_dim)</pre><pre># define gan<br>gan = define_gan(generator,discriminator)</pre><pre>#load image data<br>dataset = load_real_samples()</pre><pre>#train gan<br>train_gan(generator,discriminator,gan,dataset,latent_dim)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQgFlERav99Fu4ru0H1qkw.png" /><figcaption>GAN model training</figcaption></figure><p>Plotting some of the images generated by our generator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*rUOsgqUQMfyF3IOyQEu9qw.png" /><figcaption>Images generated after 20 epochs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*puNCijcW5olPvWLoL3Ev7w.png" /><figcaption>Images generated after 40 epochs</figcaption></figure><p>Our generator model seems to be generating plausible images of handwritten digits. We could use our saved generator model to generate more images.</p><pre>model = load_model(&#39;gen_10.h5&#39;)</pre><pre>latent_points = generate_latent_points(50,25)</pre><pre>X = model.predict(latent_points)</pre><pre>save_plot(X,5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*FDjaYjMW7Oa9gW1XBk2fYQ.png" /></figure><p>A single image can be generated as well using the model.</p><pre>vector = asarray([[0.0 for _ in range(50)]])</pre><pre>X = model.predict(vector)</pre><pre>plt.imshow(X[0,:,:,0],cmap=&#39;gray_r&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*pUbPMZiOYrJtAmwazJTw8Q.png" /></figure><p><strong>Resources</strong></p><p><a href="https://machinelearningmastery.com/">Machine Learning Mastery</a></p><p><a href="https://keras.io/">Keras API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e18496b3e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1D GAN for Sine Wave function]]></title>
            <link>https://saifgazali.medium.com/1d-gan-for-sine-wave-function-f7ea81e99c37?source=rss-1415c924f99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7ea81e99c37</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[adversarial-example]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Saif Gazali]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 00:29:20 GMT</pubDate>
            <atom:updated>2021-08-01T00:29:54.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hdKDU_1rUL38t61tztqeRg.jpeg" /><figcaption>Photo by <a href="https://towardsdatascience.com/machinex-generative-adversary-networks-gan-5a9c198b7e87">TowardsDataScience</a></figcaption></figure><p>Generative Adversarial Networks includes a generator model which is capable of generating new plausible fake samples that can be considered to be coming from an existing distribution of samples and a discriminator model that would classify the given sample as real or fake. The model weights of discriminator and the generator are updated according to the performance of the discriminator model.</p><p><strong>Function selection</strong></p><p>The first step is to select a function to model. In this article we would be using</p><p>y = sin(x) where x is the input value and y is the output value of the function. We can use numpy library to define the function.</p><pre>import numpy as np<br>def getSine(x):<br>  return np.sin(x)</pre><p>An input domain can be defined as real values between 0 and 10 (0.1,0.2…) and calculate the output for each input value in the domain. We could visualize it by plotting the points.</p><pre>time = np.arange(0, 10, 0.1)</pre><pre># Amplitude of the sine wave is sine of a variable like time.<br>amplitude = np.sin(time)</pre><pre># Plot a sine wave using time and amplitude obtained for the sine wave.<br>plt.plot(time, amplitude)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*l4_F-ksUsmYKZwFUkD-XNQ.png" /><figcaption>Sine wave plot</figcaption></figure><p><strong>Discriminator model</strong></p><p>The discriminator model takes a sample such as a point in the latent space and predicts whether it is real or fake. As the problem is not complex we would use a simple neural network model for defining our discriminator model. The model will have only one hidden layer with 25 nodes and ReLU activation function along with HE weight initialization. The output layer will have 1 node as it is a binary classification problem and would be using sigmoid activation function. For the compilation, The model would minimize the binary cross-entropy loss function. The discriminator is defined as follows:</p><pre># build discriminator model<br>def build_discriminator(n_inputs):<br>  model = Sequential()<br>  model.add(Dense(25,activation=&#39;relu&#39;,input_shape=(n_inputs,)))<br>  model.add(Dense(1,activation=&#39;sigmoid&#39;))<br>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;adam&#39;,metrics=[&#39;accuracy&#39;])<br>  model.summary()</pre><pre>  return model</pre><pre>model = build_discriminator(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*GOGPrKOndBsDB92lMmRV4A.png" /><figcaption>Discriminator model summary</figcaption></figure><p>Discriminator model is trained with both real and fake samples. Hence we would create functions to output real and fake samples. The generate_real_samples function would return a real sample and a class variable (1 as it is a real sample)</p><pre># defining our real samples</pre><pre>def gen_real_samples(n):<br>  time = randn(n)<br>  amplitude = np.sin(time)<br>  time = time.reshape(n,1)<br>  amplitude = amplitude.reshape(n,1)<br>  X = hstack((time,amplitude))<br>  y = np.ones((n,1))<br>  return X,y</pre><p>The generate_fake_samples function would return a fakr sample and a class variable (0 as it is a fake sample).</p><pre># defining our fake samples</pre><pre>def gen_fake_samples(n):<br>  time = randn(n)<br>  amplitude = time*2<br>  time = time.reshape(n,1)<br>  amplitude = amplitude.reshape(n,1)<br>  X = hstack((time,amplitude))</pre><pre>y = np.zeros((n,1))</pre><pre>return X,y</pre><p>Next, we would train and evaluate the discriminator model. For each epoch of training, we would generate half batch of real samples and a half batch of fake samples and train the model on both using the train_on_batch function. We can check the model accuracy for both real and fake samples.</p><pre># train discriminator model</pre><pre>def train_discriminator(model,n_epochs,n_batches=128):<br>  half_batches = int(n_batches/2)<br>  for i in range(n_epochs):<br>    X_real,y_real = gen_real_samples(half_batches)<br>    model.train_on_batch(X_real,y_real)</pre><pre>    X_fake,y_fake = gen_fake_samples(half_batches)<br>    model.train_on_batch(X_fake,y_fake)</pre><pre>    lossreal,acc_real = model.evaluate(X_real,y_real)</pre><pre>    lossfake,acc_fake = model.evaluate(X_fake,y_fake)</pre><pre>    print(i,acc_real,acc_fake)</pre><p>The discriminator model is trained for 300 epochs.</p><pre>train_discriminator(model,300)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*u-QFwSM35BZfdzECJCMv7g.png" /><figcaption>Training the model</figcaption></figure><p>The model is identifying the real samples with an accuracy of 100% where as around 85% for fake samples.</p><p><strong>Generator model</strong></p><p>The generator model takes an input from the latent space and generate a new sample. In our case the sample would be a vector of 2 elements (x and sin(x)). The latent space can be defined and becomes meaningful once the generator model updates the points in the space during the training. Once the training is completed, the points in the latent space would correspond to points in the output space. A standard Gaussian distribution has a mean of zero and a standard deviation of one can be used to generate new inputs.</p><p>The generator model would be simple like discriminator model and would not have any complex neural networks. The model will have only one hidden layer with 25 nodes and ReLU activation function along with HE weight initialization. The output layer will have 2 nodes and would be using linear activation function as we want to output a vector of real values. The generator model is not fit directly hence it is not compiled directly.</p><pre># generator model</pre><pre>def build_generator(latent_dim,n=2):<br>  model = Sequential()<br>  model.add(Dense(25,activation=&#39;relu&#39;,input_dim=latent_dim))<br>  model.add(Dense(n,activation=&#39;sigmoid&#39;))</pre><pre>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;adam&#39;,metrics=[&#39;accuracy&#39;])</pre><pre>  model.summary()</pre><pre>  return model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*MMSzG29WscvSlOvM5Et74w.png" /><figcaption>Generator model summary</figcaption></figure><p>We can define points in the latent space by using the randn function which generates random number from a standard gaussian distribution. We then reshape it into samples with n rows and five (our latent dimension in this article) elements per row.</p><pre>def generate_latent_space(latent_dim,n):<br>  X = randn(latent_dim*n)<br>  X = X.reshape(n,latent_dim)<br>  return X</pre><p>Generator model then generates new points using the inputs from the above method. The method generate_fake_samples implements it.</p><pre>def generate_fake_samples(model,latent_dim,n):<br>  X_input = generate_latent_space(latent_dim,n)<br>  X = model.predict(X_input)<br>  y = np.zeros((n,1))</pre><pre>  return X,y</pre><p>Setting the dimension for the latent space as 5 and generating some samples using the generator model.</p><pre>latent_dim = 5</pre><pre>model = build_generator(latent_dim)</pre><pre>X,y = generate_fake_samples(model,latent_dim,100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*B16hPzJ9IBkTrcrc_Osdbg.png" /><figcaption>Generator model summary</figcaption></figure><p>We can plot the generated samples which are random as the generator model is not trained yet.</p><pre>plt.scatter(X[:,0],X[:,1])</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*b21TaQHq20Qe1sPGuKiwAQ.png" /><figcaption>Generated points</figcaption></figure><p><strong>Generator model training</strong></p><p>When the discriminator model is relatively good at detecting fake samples then the generator model is updated more whereas when the discriminator model is poor at detecting fake samples, the weights of the generator model is updated less. A new GAN model can be defined which takes a random input, generate samples and provide it as input to the discriminator model and output of the discriminator model is used to update the weight of the generator model.</p><p>The discriminator can be trained on real and fake samples in a standalone manner whereas the generator gets updated according to the performance of the discriminator model on detecting fake samples. Therefore the discriminator which is part of the new GAN model is marked as not trainable. Also the generated samples from the generator model are marked as real so the discriminator would detect it as real or fake and give a probability using which during backpropagation process the weights of the generator model is updated to minimize the loss.</p><pre># building our gan model</pre><pre>def build_gan(generator,discriminator):<br>  discriminator.trainable = False<br>  model = Sequential()<br>  model.add(generator)<br>  model.add(discriminator)</pre><pre>  model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;adam&#39;)</pre><pre>  return model</pre><p>Model training would include first updating the discriminator model with real and fake samples, then the generator model in the composite model is updated.</p><pre># training our gan model</pre><pre>def train_gan(gen_model,disc_model,gan_model,latent_dim,n_epochs=100000,n_batch_size=128):</pre><pre>  half_batch = int(n_batch_size/2)</pre><pre>  for i in range(n_epochs):<br>    X_real,y_real = gen_real_samples(half_batch)<br>    disc_model.train_on_batch(X_real,y_real)<br>    <br>    X_fake,y_fake = generate_fake_samples(gen_model,latent_dim,half_batch)<br>    disc_model.train_on_batch(X_fake,y_fake)</pre><pre>    # input for gan model<br>    X_gan = generate_latent_space(latent_dim,n_batch_size)<br>    y_gan = np.ones((n_batch_size,1))<br>    gan_model.train_on_batch(X_gan,y_gan)</pre><pre>    if(i%10000 == 0):<br>      summarize_perf(generator,discriminator,latent_dim,100,i)</pre><p><strong>GAN Performance Evaluation</strong></p><p>We can evaluate the performance of our GAN model by first using the generated samples from the generator model and inspecting them relative to real samples.</p><pre>def summarize_perf(generator,discriminator,latent_dim,n,epoch):</pre><pre>  X_real,y_real = gen_real_samples(n)<br>  lossreal,acc_real = discriminator.evaluate(X_real,y_real)</pre><pre>  X_fake,y_fake = generate_fake_samples(generator,latent_dim,n)<br>  lossfake,acc_fake = discriminator.evaluate(X_fake,y_fake)</pre><pre>  print(epoch,acc_real,acc_fake)</pre><pre>  plt.scatter(X_fake[:,0],X_fake[:,1],color=&#39;red&#39;)</pre><pre>  plt.scatter(X_real[:,0],X_real[:,1],color=&#39;blue&#39;)</pre><pre>  plt.show()</pre><p>Training our GAN model for around 100,000 epochs and checking the performance of the model after every 10,000 epoch.</p><pre># size of the latent space<br>latent_dim = 5</pre><pre># create a discriminator<br>discriminator = build_discriminator(2)</pre><pre>#create a generator<br>generator = build_generator(latent_dim)</pre><pre>#create the gan<br>gan_model = build_gan(generator,discriminator)</pre><pre>#train the gan model<br>train_gan(generator,discriminator,gan_model,latent_dim)</pre><p>The blue points represent the real samples and the red points represents the fake samples generated by our generator model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*fEL-smueebWbljOra7sWsQ.png" /><figcaption>After 30,000 epochs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*mKTh6uWSW1n6p1kRxnMW7Q.png" /><figcaption>After 70,000 epochs</figcaption></figure><p>The model seems to generate plausible samples in the domain [0,1] adhering to the sin(x) relationship. Further improvements can be done by making the discriminator as well generator model more complex and having a more constrained domain space.</p><p><strong>Resources</strong></p><p><a href="https://machinelearningmastery.com/">Machine Learning Mastery</a></p><p><a href="https://keras.io/">Keras API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7ea81e99c37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>