<?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 Hayden LaBrie on Medium]]></title>
        <description><![CDATA[Stories by Hayden LaBrie on Medium]]></description>
        <link>https://medium.com/@generative?source=rss-c5d7259b5b23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EiSXdREc6HjVjJanlk9Agw@2x.jpeg</url>
            <title>Stories by Hayden LaBrie on Medium</title>
            <link>https://medium.com/@generative?source=rss-c5d7259b5b23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:13:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@generative/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[Understanding Autoencoders — Part IX: Training The Autoencoder]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-ix-training-the-autoencoder-cf2c4339783b?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf2c4339783b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 06:51:25 GMT</pubDate>
            <atom:updated>2023-09-01T16:22:28.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part IX: Training The Autoencoder</h3><p>We are finally at the last part of the autoencoder! Here we will show how to combine the encoder and decoder together in an auoencoder class. Then we will take the autoencoder and train it on the mnist dataset.</p><p>Please remember the complete python script can be found in my <a href="https://github.com/HaydenLaBrie/generative_deep_learning/blob/master/chapter_3/autoencoder/autoencoder.py">github repository</a>.</p><p>First lets look how we can make the autoencoder using the encoder and decoder defined in part <a href="https://medium.com/gopenai/understanding-autoencoders-part-vii-the-autoencoder-dd2eeedb46b0">VII</a> and <a href="https://medium.com/gopenai/understanding-autoencoders-part-viii-the-decoder-36687956f2cd">VIII</a>.</p><pre># combining encoder and decoder to make autoencoder<br>class Autoencoder(nn.Module):<br>    # initialize autoencoder with encoder and decoder objects<br>    def __init__(self, encoder, decoder):<br>        super().__init__()<br>        self.encoder = encoder<br>        self.decoder = decoder<br><br>    def forward(self, input_data):<br>        # first pass image to be decoded to latent space<br>        x = self.encoder(input_data)<br>        # decode image from latent space back to pixel space<br>        x = self.decoder(x)<br>        return x</pre><p>Here we define the initializer with an encoder and decoder. We need the encoder and decoder defined in the last parts in order to make the autoencoder. We also set the <strong>self.encoder = encoder </strong>and <strong>self.decoder = decoder</strong> so that we can call them throughout the autoencoder.</p><p>The forward function for the autoencoder is simple. We take the input_data, <strong>pass it through the autoencoders encoder</strong>, then <strong>pass it through the autoencoders decoder</strong>. The output will be the output of the decoder. Thus we can say the autoencoder passes the input through the encoder, then through the decoder. The encoder abstracts the data to the latent space. The decoder de abstracts the data back to the original space.</p><p>Now we need a train function:</p><pre>def train(model, num_epochs, trainloader, device):<br>    # lists to store loss and accuracy<br>    loss_hist = [0] * num_epochs<br>    accuracy_hist = [0] * num_epochs<br>    for epoch in range(num_epochs):<br>        for x_batch, y_batch in trainloader:<br>            # put the batches on the device<br>            # only need x batch for autoencoder training<br>            x_batch = x_batch.to(device)<br>            # pass through encoder, then decode back and get result as prediction<br>            pred = model(x_batch)<br>            # loss is bce between individual pixels and the decoded reconstruction individual pixels<br>            loss = loss_fn(pred, x_batch)<br>            # back propagation<br>            loss.backward()<br>            # adam optimization to adjust weights<br>            optimizer.step()<br>            # zero out gradients for next batch<br>            optimizer.zero_grad()<br>            # add to total loss for epoch<br>            # loss.item() finds loss average of the total batch<br>            # x_batch.size(0) gets the amount of samples in a batch<br>            # thus we multiply both to demonstrate avg total loss sum<br>            loss_hist[epoch] += loss.item() * x_batch.size(0)<br>        # divide total loss by length of dataset to get avg loss<br>        loss_hist[epoch] /= len(trainloader.dataset)<br>        print(f&#39;Epoch {epoch} loss:{loss_hist[epoch]}&#39;)<br>        print(&#39;-&#39; * 60)</pre><p>I have commented the code enough to where I believe you can figure out what is going on through studying it. PyTorch knowledge is somewhat assumed in this article, though you can still figure out what is going on by reading my comments and checking out the <a href="https://pytorch.org/docs/stable/index.html">PyTorch documentation</a>.</p><p>Here is my main function to train:</p><pre>if __name__ == &quot;__main__&quot;:<br>    # seeding to prevent randomization during different runs<br>    torch.manual_seed(1)<br>    torch.backends.cudnn.deterministic = True<br>    # checking if cuda is available<br>    if torch.cuda.is_available():<br>        device = &quot;cuda&quot;<br>    else:<br>        device = &quot;cpu&quot;<br>    print(f&quot;Using {device}&quot;)<br>    encoder = Encoder().to(device)<br>    decoder = Decoder().to(device)<br>    autoencoder = Autoencoder(encoder, decoder).to(device)<br>    summary(autoencoder, (1, 32, 32))<br>    # define loss function<br>    loss_fn = nn.BCELoss()<br>    # define optimizer<br>    learning_rate = 0.001<br>    optimizer = torch.optim.Adam(autoencoder.parameters(), lr=learning_rate)<br>    batch_size = 100<br>    num_epochs = 5<br>    # train model<br>    train(autoencoder, num_epochs, trainloader, device)<br>    # save model and then load back in, so I don&#39;t have to train everytime<br>    torch.save(autoencoder.state_dict(), &#39;autoencoder.pth&#39;)<br>    print(&#39;Saved model as autoencoder.pth&#39;)<br>    a = 1</pre><p>I would like to note some important things in the main function:</p><p>We are using binary cross entropy for the loss function<strong> loss_fn = nn.BCELoss()</strong>. Binary cross entropy will calculate the mean cross entropy loss between predicted and ground truth pixels for a batch of images. Basically, if a decoder makes an image close to the actual image than the loss will be smaller than a decoder which produces an inaccurate image.</p><p>Also we are using the adam optimizer, a very common optimizer for deep learning problems <strong>optimizer = torch.optim.Adam(autoencoder.parameters(), lr=learning_rate)</strong></p><p>This is it! I have finally explained everything one needs to know for creating autoencoders! I suggest taking this knowledge and experiment on different datasets, and altering the encoder and decoder to see what type of outcomes you can get! Feel free to grab my full implementation from <a href="https://github.com/HaydenLaBrie/generative_deep_learning/blob/master/chapter_3/autoencoder/autoencoder.py">github</a> and try it out yourself. I have also made other functions and files to explore the autoencoders results on mnist fashion dataset!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I3ml8jSVJyYz2uLv.jpg" /><figcaption>Finished! [<a href="https://www.si.com/olympics/2021/08/05/track-and-field-finish-line-dives-david-neville">Tokyo 2020</a>]</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2c4339783b" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-ix-training-the-autoencoder-cf2c4339783b">Understanding Autoencoders — Part IX: Training The Autoencoder</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part VIII: The Decoder]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-viii-the-decoder-36687956f2cd?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/36687956f2cd</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decoder]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 07:29:22 GMT</pubDate>
            <atom:updated>2023-09-01T16:22:34.876Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part VIII: The Decoder</h3><p>The decoder is the second main part of the autoencoder. The decoder, at a high level, takes the abstracted data produced from the encoder and de abstracts the data back to its original dimensionality.</p><p>Please note that the full implementation of the autoencoder can be viewed in my github repository: <a href="https://github.com/HaydenLaBrie/generative_deep_learning/blob/master/chapter_3/autoencoder/autoencoder.py">https://github.com/HaydenLaBrie/generative_deep_learning/blob/master/chapter_3/autoencoder/autoencoder.py</a></p><p>Also please note I have already written about the encoder in <a href="https://medium.com/gopenai/understanding-autoencoders-part-vii-the-autoencoder-dd2eeedb46b0">part VII</a></p><p>So lets dive into how the decoder portion! I am going to paste the decoder portion of the code, then analyze what is happening.</p><pre># decompresses a given embedding vector back to the original domain (e.g., back to an image)<br># takes the latent space z and decodes it back to the original pixel space<br>class Decoder(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        # take 2 nodes and fully connect to 2048 nodes<br>        self.fc1 = nn.Linear(2, 2048)<br>        # apply a reshape from a vector of 2048 to (128,4,4)<br>        # first transposed convolution<br>        self.tp1 = nn.Sequential(<br>            # take 128 channels and convert to 128 channels<br>            # here we get (128, 8, 8,), thus expanding channels my double<br>            nn.ConvTranspose2d(<br>                in_channels=128, out_channels=128,<br>                kernel_size=3, stride=2,<br>                padding=1, output_padding=1<br>            ),<br>            nn.ReLU()<br>        )<br>        # second transposed convolution<br>        self.tp2 = nn.Sequential(<br>            # take 128 channels and convert to 64 channels<br>            # here we get (64, 16, 16), thus we reduce channels by half and double channels width and length<br>            nn.ConvTranspose2d(<br>                in_channels=128, out_channels=64,<br>                kernel_size=3, stride=2,<br>                padding=1, output_padding=1<br>            ),<br>            nn.ReLU()<br>        )<br>        # third transposed convolution<br>        self.tp3 = nn.Sequential(<br>            # take 64 channels and convert to 32 channels<br>            # here we get (32, 32, 32), thus we reduce channels by half and double channels width and length<br>            nn.ConvTranspose2d(<br>                in_channels=64, out_channels=32,<br>                kernel_size=3, stride=2,<br>                padding=1, output_padding=1<br>            ),<br>            nn.ReLU()<br>        )<br>        # apply convolution<br>        # take 32 channels and convert to 1 channel (meant to represent the gray channel)<br>        # convolution will give (1, 32, 32)<br>        self.conv1 = nn.Sequential(<br>            nn.Conv2d(<br>                in_channels=32, out_channels=1,<br>                kernel_size=3, stride=1,<br>                padding=1<br>            ),<br>            # apply sigmoid activation to get a 0-1 pixel range<br>            nn.Sigmoid()<br>        )<br><br>    def forward(self, input_data):<br>        x = self.fc1(input_data)<br>        x = torch.reshape(x, (-1, 128, 4, 4))<br>        x = self.tp1(x)<br>        x = self.tp2(x)<br>        x = self.tp3(x)<br>        x = self.conv1(x)<br>        return x</pre><p>First I would like to say the overarching goal is to de abstract (to undo) what the encoder did. We want to get the abstracted data back to its original concrete form, a.k.a starting dimensionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*vOEQ9CYIM5eoz8svK9OBow.png" /><figcaption>Example 1.1 — The Encoder</figcaption></figure><p>Example 1.1 shows the encoder made in <a href="https://medium.com/gopenai/understanding-autoencoders-part-vii-the-autoencoder-dd2eeedb46b0">part VII</a>. We can think of the decoder as going the opposite direction of the encoder. When going the opposite way we are de abstracting and going back to the original input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*cheyKtl-bvepbu-_HoDb9g.png" /><figcaption>Example 1.2 — The Decoder goes the opposite direction of the encoder</figcaption></figure><p>The first layer we have a fully connected layer that takes the 2 input nodes and linearly scales to 2048 nodes. This is undoing the last part of the encoder that takes the 2048 nodes and converts them to 2 nodes.</p><p>After we get the 2048x1 shape we need to get it into the 128x4x4 shape, thus we use torch.reshape() in order to manipulate the vector tensor into a 3d tensor.</p><p>Then we have 3 2d transposed convolutions to undo the 3 convolutions in the encoder portion. Each transposed convolution is followed by a relu activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*saiTHBrNT1bRfFNX4_7znQ.png" /><figcaption>Example 1.3 — Decoders fully connected and transposed convolutions</figcaption></figure><p>As you can see the decoder is not a complete mirror of the encoder instead of going from 128x4x4 to 64x8x8, it goes 128x4x4 to 128x8x8 and etc... Thus the output after the last 2d transposed convolution is 32x32x32, not the 1x32x32 we want. We resolve this by attaching a convolution at the end to compress the 32 features into 1 feature.</p><p>Lastly, after we convolute the tensor we need to restrict the output to (0,1) via the sigmoid activation function. Remember that the pixels are represented in a range of [0,1], thus we can represent them in a (0,1) range with sigmoid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*z6q5Y8SwxLoLA9AzrenGJQ.png" /><figcaption>Example 1.4 — The Decoder</figcaption></figure><p>Now that is it for the decoder! Overall the objective of the decoder is to de abstract what the encoder has done to the original input. Once we de abstract the data we get back the original input if trained perfectly.</p><p>I did not go into the nitty gritty of all the parts of the decoder because I explained them in parts <a href="https://medium.com/@generative/list/understanding-autoencoders-8edcb1b80f3d">I-VI</a>. I highly suggest checking them out if you are new to deep learning or need a refresher on a certain idea used here!</p><p>My next article will be putting the encoder and decoder together, which will finally be the full implementation of the autoencoder. I will also show how to train the autoencoder on the mnist fashion dataset!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36687956f2cd" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-viii-the-decoder-36687956f2cd">Understanding Autoencoders — Part VIII: The Decoder</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part VII: The Autoencoder]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-vii-the-autoencoder-dd2eeedb46b0?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd2eeedb46b0</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 08:39:00 GMT</pubDate>
            <atom:updated>2023-08-25T14:56:32.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part VII: The Encoder</h3><p>I have written extensively on all the core components that the autoencoder possesses. Please check out <a href="https://medium.com/@generative/list/understanding-autoencoders-8edcb1b80f3d">Parts I-VI</a> if you are newer to deep learning or need a refresher on some component mentioned in this article. My objective in this article is to show how the autoencoder is built with code using pytorch. So lets dive in!</p><p>Please note that the full implementation of the autoencoder can be viewed in my github repository: <a href="https://github.com/HaydenLaBrie/generative_deep_learning/blob/master/chapter_3/autoencoder/autoencoder.py">https://github.com/HaydenLaBrie/generative_deep_learning/blob/master/chapter_3/autoencoder/autoencoder.py</a></p><p>Keep in mind I am training an autoencoder on the <a href="https://www.kaggle.com/datasets/zalando-research/fashionmnist">mnist-fashion </a>dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bSZB8TAI3t1va7Pl.png" /><figcaption>Samples from the mnist-fashion dataset [<a href="https://www.kaggle.com/datasets/zalando-research/fashionmnist">kaggle</a>]</figcaption></figure><p>I am going to paste in the full implementation of the encoder, then I will discuss what is happening.</p><pre># compresses high-dimensional input data such as an image into a lower-dimensional embedding vector<br># encodes to a latent space z<br># embedding space and latent space are the same thing<br>class Encoder(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        # first convolution<br>        self.conv1 = nn.Sequential(<br>            # taking a grayscale channel and converting it to 32 features<br>            # reducing the y*x dimension for each feature map by half<br>            nn.Conv2d(in_channels=1, out_channels=32,<br>                      kernel_size=3, stride=2,<br>                      padding=1),<br>            nn.ReLU()<br>        )<br>        # second convolution<br>        self.conv2 = nn.Sequential(<br>            # taking 32 feature maps and creating 64 feature maps out of it<br>            # reducing the y*x dimension for each feature map by half<br>            nn.Conv2d(in_channels=32, out_channels=64,<br>                      kernel_size=3, stride=2,<br>                      padding=1),<br>            nn.ReLU()<br>        )<br>        # third convolution<br>        self.conv3 = nn.Sequential(<br>            # taking 64 feature maps and creating 128 feature maps out of it<br>            # reducing the y*x dimension for each feature map by half<br>            nn.Conv2d(in_channels=64, out_channels=128,<br>                      kernel_size=3, stride=2,<br>                      padding=1),<br>            nn.ReLU()<br>        )<br>        # take flattened layer and map to 2 nodes to represent 2-dimensional latent space<br>        self.fc1 = nn.Linear(2048, 2)<br><br>    def forward(self, input_data):<br>        x = self.conv1(input_data)<br>        x = self.conv2(x)<br>        x = self.conv3(x)<br>        flatten = nn.Flatten()(x)<br>        x = self.fc1(flatten)<br>        return x</pre><p>First we have 3 convolutions to compress the image, each with a relu afterwards. The first convolutional layer is abstracting the data from pixels to vertical lines, horizontal lines, etc… Then it takes these these abstracted features and abstract them even more in the second layer and even more in the 3rd layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHCDGco6bx5fBt4_UigPcw.png" /><figcaption>Example 1.1 — Diagram of all 3 convolutions. Taking in a grayscale image of 1 channel by 32 width by 32 height. It gets transformed all the way to a 128 channel (a.k.a features) by 4 width by 4 height. Notice how the features go from no abstraction, being the concrete pixels, to high level abstraction like textures and shapes.</figcaption></figure><p>I would like to take to say that the mnist fashion dataset is actually 1x28x28, but I do zero padding of 2 before feeding it into the neural network; thus we get 2 additional pixels on each side making it 1x32x32. Here is my preprocessing code for the zero padding of 2 along with scaling the pixels to a range of [0,1].</p><pre># fashion mnist is a 28x28 grayscale collection of images<br># transform to 0-1 range of pixels and pad width and height by 2 on all sides,<br># thus 4 total more pixels for width and 4 more for height<br>transform = transforms.Compose([transforms.ToTensor(),<br>                                transforms.Pad(2)])</pre><p>After the 3 convolutions with relus we flatten the the final feature map. It is 128x4x4 = 2048. After we have a vector of nodes we do a fully connected layer to 2 nodes. We have 2 nodes because we want to represent the latent space in 2 dimensions; this will be a plane, a thing that is easy to visualize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*r0_pdl7EVIE6Id0aJ1_eUw.png" /><figcaption>Example 1.2 — Flatten layer and fully connected layer being applied to the abstract feature maps</figcaption></figure><p>This is really it! I am not going to describe the parameters in detail because I discussed these in high detail in <a href="https://medium.com/gopenai/understanding-autoencoders-part-ii-convolutions-252eb0e8af21">part II</a> for convolutions.</p><p>Thus, a high level overview of the encoder is taking a piece of highly dimensional data, extracting features via abstraction, then using these features to describe the the high dimensional data into a lower dimension called the latent space!</p><p>Next part will be the decoder, taking this latent space and de abstracting it back to its original dimensionality.</p><p>After discussing the decoder we will then discuss how we combine these 2 components together, and to train them. We need the encoder to learn how to properly express the high dimensional data into a latent space; we also need the decoder to learn how to take this latent space and synthesize it back to its original dimensionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2eeedb46b0" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-vii-the-autoencoder-dd2eeedb46b0">Understanding Autoencoders — Part VII: The Autoencoder</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part VI: The Sigmoid Activation Function and Wittgenstein’s Family…]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-vi-the-sigmoid-activation-function-and-wittgensteins-family-a03c863a9753?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03c863a9753</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[sigmoid-function]]></category>
            <category><![CDATA[decoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 08:03:57 GMT</pubDate>
            <atom:updated>2023-08-24T17:39:17.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part VI: The Sigmoid Activation Function and Wittgenstein’s Family Resemblance</h3><p>Finally, the last component we must understand before we can start putting everything together! Behold the sigmoid activation function!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*5a-aTSS9wx89ZKcZTCljpA.png" /><figcaption>Example 1.1 — Sigmoid function [<a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Sharma</a>]</figcaption></figure><p>Keep in mind “in the context of artificial neural networks, the term “sigmoid function” is used as an alias for the logistic function” [<a href="https://en.wikipedia.org/wiki/Sigmoid_function">wiki</a>]. To be more strict with our terminology, the sigmoid function is any function having an S shaped curve. Wikipedia lists other functions that are also classified as a sigmoid function such as arctan() and error(). In the realm of deep learning when you see the term sigmoid function pop up this can be taken to mean the logistic function.</p><p>Now lets dive into the detail of the sigmoid function, a.k.a the logistic function. So the first thing we notice is the range is from (0,1). We can say as x approaches negative infinity, s(x) approaches 0. Thus we can say it has a bottom limit of 0. We can also say as x approaches positive infinity, s(x) approaches 1. Thus we can say it has a top limit of 1. Thus we can say s(x) has a range of (0,1). Now in the graph above we see the variable is noted by z, but x or any other symbol can be used. We can also say x belongs to the set of all real numbers. This can by expressed mathematically as x∈ℝ.</p><p>Okay so now we know the domain being ℝ; thus, x∈ℝ. Also, we know the range is (0,1); R(x)∈(0,1). Now lets think of some general use cases where we would want to have some given input and transform it to a range of (0,1). The first thing that might of came to mind is probability. We can think of something being 1 as 100% odds of this being true, and 0 as 0% odds of this being true.</p><p>Probability is the most common usage to use the sigmoid function. When we want a neuron to display probability, then sigmoid is the way to go. Lets define a binary cnn classifier so that we can reference the model throughout the article.</p><p>Let there be a model that takes in images of cats and dog that we call a binary cnn classifier. The model has N hidden layers where each layer abstracts features by the convolution operation. Eventually we are left with K feature maps, where each feature map is a smaller dimension due to each hidden layer having a convolution with a stride&gt;1. Thus each feature map represents how much intensity of that feature. We have a flatten layer which flattens all K feature maps into a vector where each vector cell is a neuron. We fully connect this flatten layer to a single output neuron that has a sigmoid activation layer to represent probability of a cat being in the image. This model is represented in Example 1.2 which is below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWzI1zo-AuN1oLZY5AiEQw.png" /><figcaption>Example 1.2 — Binary Classifier, Note: The flatten layer flattens each feature map, thus in this example we assume the final feature map is 2x1 or 1x2, meaning that it has 2 neurons. This means that the feature quantity can be expressed in 2 locations. This is why we have a set of 2 per color to represent one feature map.</figcaption></figure><p>You might say “well what about multiple class probabilities?”. Like what if I want to predict if its a cat, dog, turtle, or rabbit. I can’t do this with a model that outputs a binary probability. A binary classification model is any model that outputs only one neuron probability. In the paragraph above I defined a binary classification model that will learn how to classify if a cat or not with odds. When the odds are below 50%, thus more likely not to be a cat, tells us only its not a cat. If we had more than 2 classes like the 4 classes we defined above (dog, cat, turtle, rabbit), then a binary classifier is not satisfactory; it does not tell us if its more likely to be a dog, or turtle, or rabbit. We would need a multiclass model, meaning multiple outputs with softmax. I don’t want to go into detail right now of multiclass modeling and the softmax activation function, though I do want to make it known.</p><p>So, I hope my above paragraphs persuaded you enough to understand that sigmoid is often used for probabilities. We can think of our output layer as the classification layer. We are trying to identify what class the object is (cat or dog). The image can be some in some family resemblance of a cat or dog.</p><p>A family resemblance is a philosophical idea used by Wittgenstein to note that there is not one thing we can point to that makes an object be what it is. He used the word “game” to show his philosophy in action. If we think of games we can not find some single essence, some sort of gameness property that all games posses; rather when we use the word game we are talking about some family resemblance that makes a game a game. I highly suggestion watching this video to understand Wittgenstein’s philosophy of family resemblance to understand the concept better.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ft0B4ObDmTi0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dt0B4ObDmTi0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ft0B4ObDmTi0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/241eefec9a7a4c4cad108c411273dff5/href">https://medium.com/media/241eefec9a7a4c4cad108c411273dff5/href</a></iframe><p>What am I trying to get at here? Well our neural network keeps doing abstractions at each layer. First it takes in some type of non abstract data such as instances of pixels in an image. Then, we can say the first layer abstracts verticalness and horizontalness, a measure of how vertical and horizontal an area is. Then it abstracts in the next layer, say triangleness and squareness. This keeps going and going and going. It uses these features to determine what class the object is in the image.</p><p>It takes all these learned feature maps, meaning learned features that are important for classifying a cat or dog, and weighs them together to determine which object is present. It does not rely on some “essence” that Plato was trying to find to classify an image. It relies on a multitude of features to determine if it is a cat or dog.</p><p>There is no essence to be found when we talk about a cat. Are the ears the essence of what it means for an object to be a cat? No, I can imagine a earless cat and still say its a cat. Is it the tail, paws, eyes, fur… No. I can’t seem to pinpoint one thing that is the essence. Rather it is some resemblance to each other. This set of objects has overlapping things in common, but does not fit nicely into some single essence I can point to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*bmaTTtfXbDPowueET4Nl-Q.jpeg" /><figcaption>Wittgenstein [<a href="https://eddington-cambridge.co.uk/whats-on/wittgenstein-abecedarian-film-screening">Eddington</a>]</figcaption></figure><p>Thus, we can say a CNN learns the family resemblance of what it means to be a certain class. We can’t rely on just one feature, because their is not one essential property that makes a cat a cat. We need multiple features to cover the range of resemblances that make a cat a cat.</p><p>The model when trained tries to minimize the cross entropy loss. This basically means that if we see a cat we should predict it as 100% odds and when we see a dog we should predict the dog as being 100% odds. In order to reduce the loss the model learns the correct feature weights along with what features it should be looking for.</p><p>This is one of the main reasons for the sigmoid activation function, when we want a neuron to represent probability; though not the only!<br> <br>Now why are we talking about sigmoid for autoencoders? Remember the decoder is about de-abstracting the latent space that the encoder embedded to. The output of the decoder should be the exact image of the input of encoder if trained perfectly. Also, remember that the images input channels (r,g,b) pixels are in a range of [0,1]. Yes, sigmoid range is (0,1), but we can get infinitely close to 0 and 1; thus, this is satisfactory. So we use the sigmoid function to get a range of (0,1) for the pixels.</p><p>Now we can generalize the usage and say that the sigmoid activation function is used when you want some neuron to output the range of (0,1). Not only do we need the sigmoid to restrict the output to (0,1), also we need it to leverage its non-linearity for complex modeling of reality.</p><p>So I could of explained the usage of sigmoid in autoencoders quite quickly, but I felt like it did not express the true nature of sigmoids capability. Sigmoid is a powerful activation function when you need to limit neurons output to (0,1), just like probability and pixel intensity!</p><p>Wow! Now I have covered all the major components of the autoencoder. My next steps are to demonstrate how the encoder, decoder, and combined into autoencoder are constructed in coded! This has been a long journey for our first model, but it is an important foundation for generative deep learning! I think I will be able to explain the the encoders, decoders, and autoencoders construction and code in 3 more articles. Now that you have the theory behind all the components, the construction and code should be fairly straight forward. We are done with all the theory, just need to put all the pieces together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03c863a9753" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-vi-the-sigmoid-activation-function-and-wittgensteins-family-a03c863a9753">Understanding Autoencoders — Part VI: The Sigmoid Activation Function and Wittgenstein’s Family…</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part V: The Transposed Convolution]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-v-the-transposed-convolution-8de0e17d22d?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/8de0e17d22d</guid>
            <category><![CDATA[decoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[transpose-convolution]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 07:14:21 GMT</pubDate>
            <atom:updated>2023-08-21T15:03:42.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part V: The Transposed Convolution</h3><p>We have talked about all the components that are apart of the encoder portion of the autoencoder. To summarize the encoder, I would say it compresses the high dimensionality which explains some type of object to a lower dimension. An example would be the high dimensionality of an image, which the dimension size of an image is the sum of pixels from each channel (a.k.a features). The encoder would compress this high dimensionality that explains an the image to a lower dimension.</p><p>If we have an rbg image 32 pixels height and 32 pixels width, then the total number of features would be 3*32*32 = 3072. Now instead of explaining that image using every single feature, the encoder will compress the data in a way that explains the image only using some defined dimension size when creating, say 2 or 3. So I can explain the whole set of images using just 2 or 3 variables now instead of 3072 variables! All of this is explained in part 1–4! Now after briefly summarizing what we have gone through so far, lets look at the decoder in detail.</p><p>Keep in mind I am explaining the autoencoder using the MNIST fashion dataset throughout the whole series, thus the data being used are images. Each pixel of an image is an individual feature of the image. We refer to data as the set of all features/pixels which describe an image. We refer to the dataset as all the data used to train or validate the model.</p><p>So after we have passed the data through the encoder, we now have a compressed version of explaining the image. When I mean a compressed version, I am saying the number of dimensions used to explain that object is reduced. Well the decoder’s goal is to take this compressed piece of data and decompress it back to its original dimensional shape.</p><p>Now how do we “undo” this decompression that the encoder is doing on the data; that is, how do we take the lower number of features that explain an image back to its original features that explained that image. If you remember, the abstraction of features is what is causing this dimension reduction. Feature abstraction is happening via the convolutions! So how do we reverse engineer these convolutions? Well luckily there is an operation that is able to reverse the convolutions performed on the tensor called transposed convolutions.</p><p>Now transposed convolutions might be best shown through example. Keep in mind that the same components that a convolution has apply to transposed convolutions such as kernel size, padding, and stride.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*zXV1-oenLPVLmvm1IuZajw.png" /><figcaption>Example 1.1 — Transposed convolution with kernel=2. [<a href="https://d2l.ai/chapter_computer-vision/transposed-conv.html">d2l</a>]</figcaption></figure><p>Here is an example of implementing the same transposed convolution using pytorch.</p><pre>import torch<br><br><br>def trans_conv(X, K):<br>    # set to height h and width w of kernel<br>    h, w = K.shape<br>    # initialize the output tensor Y as (input_height + kernel_height - 1) * (input_width + kernel_width -1)<br>    Y = torch.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1))<br>    # loop through input_height<br>    counter = 0<br>    for i in range(X.shape[0]):<br>        # loop through input_width<br>        for j in range(X.shape[1]):<br>            # set (i to i+h-1, j to j+w-1) of Y<br>            Y[i: i + h, j: j + w] += X[i, j] * K<br>            counter += 1<br>            print(f&#39;Part {counter} of Result:\n{X[i, j] * K}\n&#39; + &#39;.&#39; * 30)<br>    print(f&#39;Final Result:\n{Y}&#39;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    X = torch.tensor([[0.0, 1.0], [2.0, 3.0]])<br>    K = torch.tensor([[0.0, 1.0], [2.0, 3.0]])<br>    trans_conv(X, K)</pre><pre>Console output:<br><br>Part 1 of Result:<br>tensor([[0., 0.],<br>        [0., 0.]])<br>..............................<br>Part 2 of Result:<br>tensor([[0., 1.],<br>        [2., 3.]])<br>..............................<br>Part 3 of Result:<br>tensor([[0., 2.],<br>        [4., 6.]])<br>..............................<br>Part 4 of Result:<br>tensor([[0., 3.],<br>        [6., 9.]])<br>..............................<br>Final Result:<br>tensor([[ 0.,  0.,  1.],<br>        [ 0.,  4.,  6.],<br>        [ 4., 12.,  9.]])<br><br>Process finished with exit code 0</pre><p>As you can see, transposed convolutions expand the tensors height and width; this is exactly what we want to accomplish. This is the solution to “how do we decompress what the encoder did so we can get back the original image”.</p><p>As mentioned above, we have all the same parameters that convolutions have, being kernel_size, stride, padding. In example 1.1 we defined the kernel=2 , meaning make the kernel 2x2 and have the training learn the weights (a.k.a cell values).</p><p>Next we will look at stride, which is very much the same as regular convolutions. I believe an example explains best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*ltzD_XyfrW_erG18D4DJAQ.png" /><figcaption>Example 1.2 — Transposed convolution with kernel=2, stride=2 [<a href="https://d2l.ai/chapter_computer-vision/transposed-conv.html">d2l</a>]</figcaption></figure><p>Stride here is similar to the convolution explained early, thus I won’t go into more detail.</p><p>I would like to note that the default values is stride=1 and padding=0, but you must provide a kernel size via kernel parameter.</p><p>Lastly, lets examine padding. Now kernel and stride for transposed convolutions are similar to convolutions, but padding is a different story. Lets first look at an example, then I will dive deeper into what is happening.</p><p>First lets look an example with no padding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUFb3qnzsjDFUuU5sRxeEQ.png" /><figcaption>Example 1.3 — Transposed convolution with kernel=2, stride=1, padding=0</figcaption></figure><p>Now lets see what happens we introduce padding of 1 and keep everything else the same from example 1.3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9fEOeyFz1G5vmsPcG_rOA.png" /><figcaption>Example 1.4- Transposed convolution with kernel=2, stride=1, padding=1</figcaption></figure><p>Now in example 1.4 the output is the red matrix; I left the numbers of where the padding removes for demonstration purposes. Thus, you can see the essence of padding for 2d transposed convolutions is to remove n amount on each side where n is the parameter set for padding.</p><p>Also there is a bias that is learned as well along with kernel. Bias is a constant that gets added to 1 for each output. Lets now look at example 1.4 but with a bias now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOR7hDxRelSLBqxrX5GBWQ.png" /><figcaption>Example 1.5- Transposed convolution with kernel=2, stride=1, padding=1, bias=True</figcaption></figure><p>Output Size = (Input Size — 1) * Stride — 2 * Padding + Kernel Size</p><p>Output Size = (2–1) * 1–2*1+3</p><p>Output Size = 1*1–2*1+3 = 1–2+3= 2</p><p>As you can see there are different ways to “bake this cookie”. What do I mean? There are different combinations of stride, padding, and kernel size that can give the same output size for the upsampling. Understanding the nuances of parameter tuning is not the goal here, but understanding the fundamentals should be your goal at this point.</p><p>Lastly I must say this works the same way that a regular convolution works for multichannel input. We have a kernel for each channel and have the same transpose convolution parameters, then add them together element wise. If we have a 64 channel input, in order to get a 1 channel output we would need 1 kernel for each channel to perform a transposed convolution, making a total of 64 kernels. If we want 2 channel output, aka 2 feature maps, then we need 2 kernels for each input channel which would be a total of 128 kernels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFGX7_KwVw7qwDoap4k3cA.png" /><figcaption>Example 1.6 — Example of 3 channel input to 5 channel output using a convolution [<a href="https://github.com/rasbt/machine-learning-book/blob/main/ch14/ch14_part1.ipynb">Sebastian</a>]</figcaption></figure><p>In example 1.6 we can see that for a convolution on an input with 3 channels we must do a convolution on each input channel and do element wise summation to get a output channel, a.k.a feature map. Thus we can say that we need 5 groups of 3 to get 5 feature maps from the convolution. Each group creates one feature map where each kernel in the group does a convolution over 1 channel and then the convolution results are element wise summed to create the feature map. Remember that a feature map is dependent on all the input’s channels; this is why we do element wise addition to get one feature map.</p><p>This same principle explained above is applied to transposed convolutions. Generally transposed convolutions are not only trying to reduce the feature map dimension, but also its goal is to generally reduce the amount of channels. We might expand an image to a high amount of channels so that we can see many different types of features (like cat ears, eyes, teeth, etc…); though, when we want to translate an image back from this high channel view we need to reduce the channel amount back to its original 3 for rbg or 1 for grayscale.</p><p>Now the only thing we need to cover is the sigmoid activation function and then we will have the components needed to build both the encoder and decoder of the autoencoder. I will explain the sigmoid activation function next and then we will dive into building the encoder, decoder, and combining together to create the full blown autoencoder!</p><p>I would like to say the theory portion to understand autoencoders is pretty much over at this point. Implementing the autoencoder will require some explanation, but due to explaining all the theory before implementation makes it a smooth ride ahead!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8de0e17d22d" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-v-the-transposed-convolution-8de0e17d22d">Understanding Autoencoders — Part V: The Transposed Convolution</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part IV: The Fully Connected Layer and Flattening]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-iv-the-fully-connected-layer-and-flattening-566f246fa1a?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/566f246fa1a</guid>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 10:00:03 GMT</pubDate>
            <atom:updated>2023-08-15T15:40:34.912Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part IV: The Fully Connected Layer and Flattening</h3><p>Now once we finish part IV we will be done with all the knowledge to understand the encoder part of the autoencoder; though, we will still need to discuss some other concepts before we can understand the decoder and put it all together in a big picture.</p><p>Nvidia states that “Fully-connected layers, also known as linear layers, connect every input neuron to every output neuron and are commonly used in neural networks.” [<a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html">Nvidia</a>]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Kkh53aAeKDoJt25lIBTNrA.png" /><figcaption>Example 1.1 — “<em>Example of a small fully-connected layer with four input and eight output neurons.” [</em><a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html"><em>nvidia</em></a><em>]</em></figcaption></figure><p>We can demonstrate this fully connected layer as 3 major components, the input neurons as a vector matrix called X, the weight matrix W to calculate how each input node impacts the output node, and the constants B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXJkRUWBVKxfotexJKfUrg.png" /><figcaption>Example 1.2 — Visualization of mathematics behind the fully connected layer in example 1.1</figcaption></figure><p>In the drawing in Example 1.1 we have the input neurons, displayed as blue in example 1.2, and output neurons, displayed as red in example 1.2. The weights correspond to the lines in example 1.1. We can see that each output neuron combines all the input neurons together via some weight scaling. Basically each output neuron is based on some multiple of input neuron 1, neuron 2, neuron 3, and neuron 4, then added together. This is why it is called a fully connected layer; each resultant node is based off of all the input nodes. Thus, we can think of all input nodes being connected to all the output nodes. The drawing in example 1.1 leaves out the constant b, though its implied its there. The weights and constants are learned through training the model.</p><p>What is the output node really representing then? What is happening when doing this? Well in essence we can think of it as abstracting some type of feature that comes from combining the previous neurons together. What do I mean by this? We can think of a structured data situation easily. Lets pretend that we have structured data of animals (such as cats, dogs, foxes, etc…) with 3 features being length, height, and age. In a very simple sense we could do a 1 layer network to predict this, where the layer is a fully connected layer. We could have the inputs neurons be the length, height, and age. Lets say we are trying to train our model to predict based on 10 animals, thus we would have the fully connected layer have 10 output neurons. Now each neuron represents a “animalness feature” like catness or dogness or foxness. The number is arbitrary, thus we apply a sigmoid activation unit to derive more meaning out of it. We will get into sigmoid activation layer in a later article. We can say we have abstracted the input neurons features to create the abstract output neurons. Whatever “-ness” output neuron has the highest value will be considered the prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*94d_YXA4LKU7Z1fR--636A.png" /><figcaption>Example 1.3 — Fully connected layer abstracting features from input</figcaption></figure><p>This is a simplified version of how one could classify animal type based on 3 features from tabular data. In actuality just 3 variables to determine animal type is probably not enough. Also, having a single layer, or shallow neural network, would not do justice to most classification problems. Keep in mind this is simply a linear regression model being defined in a neural network setting. In order to get more complicated models, which most models need to be in order to approach close to reality, needs high nonlinearity. We could apply a non linear activation function on each output neuron, but this won’t add enough nonlinearity; we need a deeper network to capture the sophistication that the models need. For example, ReLU would simply set the neuron to 0 if the input is 0 or less, otherwise set the neuron as the given input received.</p><p>I also want to say that the abstracted features at each neuron is generally very hard to understand by humans. What the fully connected layer starts to develop during training is quite interesting. The same principle happens in convolutions, where abstraction is happening, but locality comes into play as well. This is the big difference between convolutions and fully connected layers, the use of locality. Convolutions are like mine workers getting abstract features based on location. If there is a line on the top left of the picture we want to remember where that line was. If we find a line and then throw it in the bag we can’t abstract more important features as easy. Simply put, location matters in images! When we are dealing with fully connected layers, location does not matter! In a convolution, by the nature of the operation, location of the neurons are extremely impactful!</p><p>We could define the use cases between these 2 as this: Use convolutions when locality matters, meaning if location of neurons have some type of meaning. In images this is the case, pixels (neurons) which are near each other are generally related in some way. 2 pixels close to each other may make part of an eye, the edge of a ear, a part of a piece of hair, etc… Use a a fully connected layer when locality does not matter, such as tabular data inputs and such.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*waB9rO50AZ6RBdx3.png" /><figcaption>Abstraction of convolutions. You can see the features first are detecting things such as edges, then more abstract like circles, until it becomes extremely abstract [<a href="https://towardsdatascience.com/applied-deep-learning-part-4-convolutional-neural-networks-584bc134c1e2">Dertat</a>]</figcaption></figure><p>The essence of fully connected layers and convolutions is abstraction. In in deep layers, the leverage of recursively abstracting. Recursively abstracting is about taking the previously abstracted features and combining them together to create an even more abstract piece of data.</p><p>Think about a cat, this is innately an abstraction. Now there are ton of philosophical implications of abstract objects that I wont get into right now, though I do want to write articles on realism and nominalism to discuss these implications. I think once you start to look at deep learning more, metaphysics naturally comes into play in its foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qBwB0Odn76d0vKB4.jpg" /><figcaption>First version of the <em>Symposium</em> by Feuerbach, 1869 [<a href="https://en.wikipedia.org/wiki/Symposium_%28Feuerbach%29">wiki</a>]</figcaption></figure><p>The last concept before we go to the decoder side is the idea of flattening. Think about a linear layer, its based on a transformation from a 1 dimension of neurons to a 1 dimension of neurons. Thus, the linear layer architecture requires a vector as input. Now tabular input has no issue with this as its in the form of (batch, num_features). Thus we feed the network (1, num_features) batch times, then update weights via backpropigation, then receive another batch. Rinse and repeat n number of epochs.</p><p>What about when we want to apply a linear layer to a multi dimension tensor? Okay before we talk about how to apply a linear layer on multi dimension tensors, lets talk about why you would want to.</p><p>Linear layer gives the power to map all the neurons to a selected amount of neurons. What do I mean by this? Remember that a fully connected layer maps all the input neurons to the given output neurons. We define how many output neurons we want. Lets say we want to predict the probability of 2 classes based on all the previous layers, well the linear layer will do that job. A fully connected layer is thus often used during the last layer for classification models due to the fact that we can linearly combine the highly abstracted feature and come up with an output for each class.</p><p>Now why would we want to apply linear layer to a mulidimensionality? Often times once we have extracted highly abstracted features from spatial data, such as images, we don’t care about locality of features anymore when applying the function to the input tensor. Let me give an example. Imagine we have 8 feature maps of size 4x4. Feature map 1 detects ears, feature map 2 detects whiskers, feature map 3 detects eyes, and so on… Now we have 2 possible targets in this universe, dog or cat. We flatten all the feature maps so that its 1 dimensional, a.k.a. a vector. Now you have all these different feature maps composed into one vector. Then we do a fully connected layer, mapping every neuron to both output neurons. The output of this fully connected layer now has lost its location based features.</p><p>Now I have kind of explained how flattening works already by explaining why one would want to use a linear layer to multidimensions. I think an image will give the most benefit to help understand how flattening works in 3 dimensions.</p><figure><img alt="https://cdn-images-1.medium.com/v2/resize:fit:483/1*9g4qz27omAxNE0zGOGTiBw.png" src="https://cdn-images-1.medium.com/proxy/1*9g4qz27omAxNE0zGOGTiBw.png" /><figcaption>Example of flattening a input of dimensions (feature_maps * height * width) [<a href="https://towardsai.net/p/machine-learning/beginner-guides-to-convolutional-neural-network-from-scratch-kuzushiji-mnist-75f42c175b21">Towards AI</a>]</figcaption></figure><p>Here the output is shown as (n,1) a.k.a column vector due to how the linear layer works; though, I would like to note that the actual dimensions are (batch_size * total_neurons), thus a row vector here. Note, when you perform a linear layer on this row vector it will transpose to a column vector to work properly.</p><p>This completes all the necessary fundamental concepts to understand the encoder. Now to move on to the fundamental concepts of the decoder before we put everything together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566f246fa1a" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-iv-the-fully-connected-layer-and-flattening-566f246fa1a">Understanding Autoencoders — Part IV: The Fully Connected Layer and Flattening</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part III: The ReLu Activation Function]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-iii-the-relu-activation-function-52b0647c6034?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b0647c6034</guid>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[relu]]></category>
            <category><![CDATA[autoencoder]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 03:31:02 GMT</pubDate>
            <atom:updated>2023-08-15T15:40:36.146Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part III: The ReLu Activation Function</h3><p>So far I have covered the high level overview of the autoencoder. The autoencoder is comprised of 2 major components, being the encoder and decoder. I have also covered convolutions, an important operation performed on tensors to extract higher level features. Now I am going to the next important knowledge step, the ReLu activation function.</p><p>First, what is an activation function? Wikipedia states “the activation function of a node defines the output of that node given an input or set of inputs” [<a href="https://en.wikipedia.org/wiki/Activation_function">wiki</a>]. Each node gets manipulated by the activation function and that value will be used for whatever the next step is in the neural network; this could be the next layer of the network, or the final output of the network.</p><p>There are various types of activation functions, but the one I will be focusing on in this article is the ReLu activation function. What is the definition of the ReLu activation function? Given a number x and ReLu function R, if x &gt; 0 then let R(x) = x, else R(x) = 0.</p><p>We could write this function using pythonic syntax easily.</p><pre>def relu(x):<br>    if x &gt; 0:<br>        return x<br>    else:<br>        return 0</pre><pre>print(relu(2))<br>2<br>print(relu(-5))<br>0<br>print(relu(0))<br>0</pre><p>If the input is positive, then the relu function will simply map to the identity of the input number. If the input is zero or negative, then the relu function will map to zero.</p><p>Now realize that this is done to all the neurons. If we think about feature maps, each element/number that represents a piece of the feature map is the neurons value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*jeL7Z9DqR0U1XfNG" /><figcaption>Example of a feature map getting mapped by the relu function [<a href="https://hashrocket.com/blog/posts/a-friendly-introduction-to-convolutional-neural-networks">Aniemeka</a>]</figcaption></figure><p>This is a nice image to help visualize what is happening. Also remember often there are multiple feature maps from the convolution, thus we need to apply the relu function to each feature map! In this example we have a (1,4,4) tensor, if we pretend there are 5 feature maps then we get (5,4,4) tensor! We will need to individually check each neuron, a total of 5*4*4 = 80.</p><p>Here is an implementation of how relu activation function works using ndarrays in numpy.</p><pre>import numpy as np<br><br><br>def relu(ndarray):<br>    for iz, iy, ix in np.ndindex(ndarray.shape):<br>        if ndarray[iz, iy, ix] &gt; 0:<br>            continue<br>        else:<br>            ndarray[iz, iy, ix] = 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    # sample from standard normal distribution, mean = 0 and std = 1<br>    # make a 3dimensional ndarray of 2, 5 height, and 4 width<br>    x = np.random.normal(0, 1, size=(2, 5, 4))<br>    # print original<br>    print(x)<br>    # relu activation<br>    relu(x)<br>    # print function output<br>    print(x)</pre><pre># print original<br>print(x)<br>[[[-0.82059295  1.18563113  1.62275354  0.82003972]<br>  [-0.39323953  0.67530923  1.18381198 -0.86540546]<br>  [-1.2222125   0.62743922  0.04277159  1.10858186]<br>  [ 1.25513424  1.34921543 -1.16688216  0.29262948]<br>  [-0.71729115  0.55870771 -0.9189962   1.07131639]]<br> [[ 0.20725983 -0.35120676 -0.69112784  0.50952223]<br>  [ 0.23425166 -0.57130208  0.78198422 -0.74479706]<br>  [-0.06699528 -0.1039494  -0.21938977  0.60149397]<br>  [ 1.01447275 -2.22628516 -0.41691551 -1.98755923]<br>  [ 0.59741333  0.03026711  0.02406445 -0.06009714]]]<br># relu activation<br>relu(x)<br># print function output<br>print(x)<br>[[[0.         1.18563113 1.62275354 0.82003972]<br>  [0.         0.67530923 1.18381198 0.        ]<br>  [0.         0.62743922 0.04277159 1.10858186]<br>  [1.25513424 1.34921543 0.         0.29262948]<br>  [0.         0.55870771 0.         1.07131639]]<br> [[0.20725983 0.         0.         0.50952223]<br>  [0.23425166 0.         0.78198422 0.        ]<br>  [0.         0.         0.         0.60149397]<br>  [1.01447275 0.         0.         0.        ]<br>  [0.59741333 0.03026711 0.02406445 0.        ]]]</pre><p>Now you probably have a decent grasp of the relu activation function, but why use this?</p><p>So any neural network layer can be summarized in a general sense as W*X+b where X is the input tensor, W are the weights, and b is the constant. We perform matrix multiplication and add the constant to get the output neurons value.</p><p>Now W*X+b is a linear equation, meaning whatever X is, the output will scale to that W multiple for the given cell. I&#39;m going to ignore b here, but remember b would be added after calculating W*X. In the example below if b=3, then the output would be [15,21,13].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0m45AHqvenNVcu8yPRZRg.png" /><figcaption>Example 1.1 - Input going through one layer. Green are weights, blue are neurons, red is output.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytwPLv6nOUOXL0RQ57xhkA.png" /><figcaption>Example 1.2 — First layers output being passed in as second layers input.</figcaption></figure><p>Now below I demonstrate some math to derive the weights necessary to combine the 2 layers into 1 layer.</p><pre>2(2)+3(2)+1(2)=12=n1<br>4(2)+2(2)+3(2)=18=n2<br>2(2)+2(2)+1(2)=10=n3<br>---------------------------------------------------------------<br>5(n1) + 2(n2) + 3(n3) = 126 = n4<br>5(2(2)+3(2)+1(2)) + 2(4(2)+2(2)+3(2)) + 3(2(2)+2(2)+1(2)) = n4<br>10(2)+15(2)+5(2) + 8(2)+4(2)+6(2) + 6(2)+6(2)+3(2) = n4<br>24(2) + 25(2) + 14(2) = n4<br><br>4(n1)+4(n2)+2(n3)=104=n5<br>4(2(2)+3(2)+1(2)) + 4(4(2)+2(2)+3(2)) + 2(2(2)+2(2)+1(2)) = n5<br>8(2)+12(2)+4(2) + 16(2)+8(2)+12(2) + 4(2)+4(2)+2(2) = n5<br>28(2) + 24(2) + 18(2) = n5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuUbU5VPcR8yCxKm1zKGTA.png" /><figcaption>Example 1.3 — The first 2 layers being combined into 1 layer.</figcaption></figure><p>What is being demonstrated is no matter how many layers we have, we can represent any number of layers as just one layer! Why? Because its linear! It will always be just a scaled version of the input!</p><p>So now that you understand the reasoning behind why layers in a neural network without an activation function will always be linear, we can see the importance of having a non linear activation function being applied to these neurons. In the simplest terms, we use ReLu and other non-linear activation functions to produce non linearity output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gXzXNkgy6hN0aagK.png" /><figcaption>ReLu function on the cartesian coordinate system [<a href="https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/">Brownlee</a>]</figcaption></figure><p>So now you understand the ReLu activation function, one of the most used activation functions currently used in deep learning! Next we will explorer the fully connected layer a.k.a linear layer, another important stepping stone to understand autoencoders!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b0647c6034" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-iii-the-relu-activation-function-52b0647c6034">Understanding Autoencoders — Part III: The ReLu Activation Function</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part II: Convolutions]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-ii-convolutions-252eb0e8af21?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/252eb0e8af21</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 04:07:52 GMT</pubDate>
            <atom:updated>2023-07-26T14:38:54.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Autoencoders — Part II: Convolutions</h3><p>Now that I have introduced the fundamental idea of the Autoencoder via the wardrobe analogy, I am going to dive deeper into the nitty gritty of the specifics of this generative deep learning architecture.</p><p>Hopefully you have read my previous post that describes the architecture through Foster’s analogy. If not, and new to autoencoders, I highly suggest sitting down and reading <a href="https://medium.com/@generative/understanding-autoencoders-part-i-introduction-and-latent-spaces-69cbe68b6fda">part 1</a>.</p><p>Now I left off at explaining that autoencoders have 2 main components, the encoder and decoder. At a high level view, the encoder takes high dimensional data and compresses it down into a lower dimensionality space. This lower dimensional space is often referred to as the latent space, and in various literature referred to as the original data’s embedding. Using the same terminology of the previous post, I will stick to the term latent space when talking about this lower dimesionality.</p><p>The other main component, the decoder, is the component which takes a sample from the lower dimensional latent space and converts this space back to the original higher dimesionality.</p><p>Foster summarizes the autoencoder well: “An autoencoder is simply a neural network that is trained to perform the task of encoding and decoding an item, such that the output from this process is as close to the original item as possible. Crucially, it can be used as a generative model, because we can decode any point in the 2D space that we want (in particular, those that are not embeddings of original items) to produce a novel item of clothing.” [<a href="https://www.oreilly.com/library/view/generative-deep-learning/9781098134174/">Foster</a>].</p><p>Let’s now look at convolutions, a key building to the autoencoder architecture.</p><p>Lets define in a general sense what a convolution is. A convolution is taking 1 tensor, grabbing another tensor, then performing something called the element wise product sum. The form of a convolution expression is input(x)kernel=output. Input is a tensor which the kernel will slide across. I think if I draw an example of how it works, it will become more clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ftg2b-1nPOp-Qjqe3U2Qg.jpeg" /></figure><p>First I would like to note that filter and kernel can be used interchangeably in this context. As you can see with this very simple example of a convolution we take the input and filter, do element wise multiplication, and then sum it up into a scalar. Note that kernel value represents the size of the kernel. Here the input size is 2x2 and the kernel=2 for a 2x2 kernel. I picked random numbers for the kernel, but note in train the numbers are learned, not assigned by the neural network engineer.</p><p>This example had an input size of 2 * 2 and filter size 2 * 2, thus we just get one number. What happens when we have different dimensions between input size and filter size?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*P7DJD9bKYYt_Jh9JjZlSdA.jpeg" /></figure><p>I introduced this new attribute called stride. Stride is how many steps the kernel moves for the next element wise calculation. A stride of 1 means the kernel slides right by 1 each time. Once the convolution can not go any more right, without causing a logical error, then we shift all the way back left and stride down 1. What do I mean by logical error here? If you stride the required amount of times and you find that some of the kernel matrix does not have an element on the input that can be multiplied by, then we are doing something logically impossible. Lets look at the same example above but with a stride of 2 to help you understand the concept better; the input will still be 3x3 and the kernel will still be 2x2, but the stride will now be 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ScYzhlfkjI0-1ud6ybJBLQ.jpeg" /></figure><p>We only get a scalar here! The stride is making it so that whenever we slide 2 to the right or 2 below we can not have a logically sound convolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*n_rEjDmnulp3XPlL.gif" /><figcaption>Example of a 5x5 tensor being convoluted. The kernel = 3 and the stride = 1 [<a href="https://developer.nvidia.com/discover/convolution">nvidia</a>]</figcaption></figure><p>Now when performing a convolution we get information loss. Looking at the convolution gif above we start to notice something interesting. The corners of the image only influence 1 calculation while the middle element is used for all 9 calculations! This means that the middle of the image has way more impact on the convolutions output compared to the corners! We notice that the closer the element is to the middle, the more impact the cell has to the overall convolutions output! This is what I mean by information loss. We are not equally considering the input tensor, thus we are loosing some of the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JncQgu4N4LHzpkw0.png" /><figcaption>Demonstration of how corner and Edge pixels have less impact on the convolution calculation compared to pixels more in the middle [<a href="https://www.geeksforgeeks.org/cnn-introduction-to-padding/#">geeksforgeeks</a>]</figcaption></figure><p>How can we combat this information loss? There is a technique called zero padding that can help reduce the tendency for convolutions to have “more middle” weightage. We will get into padding and zero padding next.</p><p>Padding in its simplest form is a technique used to increase the size of input tensor. How do we increase the the size of the tensor, well we need to add elements on the edges of the tensor. Well what value do we define the elements? Good question, generally we define the added elements on the edges of the tensor as all zeros. This is referred to as zero padding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*wl77zBkrZvHMXo9l.jpg" /><figcaption>Zero padding being applied to 6x6 tensor. Result is a 8x8 tensor [<a href="https://www.numpyninja.com/post/how-padding-helps-in-cnn">Numpy Ninja</a>]</figcaption></figure><p>When padding an image with padding=1, we actually increase the width and height by 2. We are applying zeroes all around the tensor; thus, zeros are being added on the left side and right side, top side and bottom side, which increases the width and height by 2 not 1!</p><p>Not only does padding have an effect on the information loss, it also impacts the size of the convolution output.</p><p>Lets see example 1.3 with the same stride and kernel attributes, but with padding = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*SLsVrNDAnoWeIkVsQKIJ_Q.jpeg" /></figure><p>To calculate the output tensor of a convolution here is a handy formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*1YhqIamIRp65h4lB.png" /><figcaption>Convolution output size formula [<a href="https://blog.mlreview.com/a-guide-to-receptive-field-arithmetic-for-convolutional-neural-networks-e0f514068807">Dang Ha</a>] Note: the brackets here mean the floor function</figcaption></figure><p>For example in 1.4 we have a input tensor of 3x3, a kernel of 2x2, padding of 1x1, and a stride of 2. We can find what the size of the output will be by using the formula: floor((3+2(1)-2)/2) + 1 = floor((3)/2) + 1= 1+1 = 2, which is correct!</p><p>Now we have looked at all the fundamental concepts of a convolution: input, kernel, stride, and padding. The last thing to understand about convolutions are performing them on multi channel inputs a.k.a 3d tensors.</p><p>There are 2 cases where we see multi channel inputs for a convolution. First we see them during rgb image inputs. Each color gets its own 2d tensor, thus we get a stack of 2d tensors in the form of (3,w,h).</p><p>The other case where we see a multi channel input is performing a convolution after a convolution. Some convolutions create multiple output channels by having multiple kernels go over the same input.</p><p>I would like to go back a little and think about what a feature is. As stated in <a href="https://medium.com/@generative/understanding-autoencoders-part-i-introduction-and-latent-spaces-69cbe68b6fda">part 1</a>, “an individual measurable property or characteristic of a phenomenon” is a feature [<a href="https://en.wikipedia.org/wiki/Feature_(computer_vision)">wiki</a>]. Now in grayscale images we simply can say that each pixel is a feature. The pixels not only have a intensity value, they also have a position value. What do I mean by this? Yes, a grayscale pixel fits the definition of “an individual measurable property”, but there is also a location attached to this measurable property. Thus, with this “individual measurable property” we can leverage location information to extract more information; this is exactly what a convolution is doing. A convolution is taking all of these pixels along with their location to find higher level features such as vertical or horizontal lines.</p><p>What happens when we have a multichannel input such as rgb? What is the feature in this condition? Simply put a grayscale measures the grayness at individual positions, thus each positions grayness is the feature. When we have rgb we are measuring the objects redness, greenness, and blueness at different positions. Thus each position of an object has 3 features being measured, not 1 like grayscale. Thus we can say that a 32x32 rgb image is 3x32x32 features = 3072 features.</p><p>How can we deal with convolutions on these multichannel inputs? We run a different kernel across each channel, get an intermediate output, and then add the tensors together. I believe an image will help paint a better picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/0*NCj2RQQUqhpVpN5O.jpeg" /><figcaption>Example of multi channel input being convoluted [<a href="https://medium.com/apache-mxnet/multi-channel-convolutions-explained-with-ms-excel-9bbf8eb77108">Lane</a>]</figcaption></figure><p>I highly suggest looking at this demo of a multichannel input outputting 2 feature maps <a href="https://cs231n.github.io/assets/conv-demo/index.html">https://cs231n.github.io/assets/conv-demo/index.html</a></p><p>Lastly, I would like to say that each convolution output is called a feature map. The result of early convolutions are extracted features from the input such as horizontal and vertical edges at first. Performing another convolution on these feature maps will extract more abstract features such as curves and simple shapes by combining the feature maps together via a kernel on each feature map and summing them up. If we want more than one feature map output we would need to provide multiple kernels for each channel. This process keeps continuing until we get extremely powerful detections like eyes, mouth, tail, etc…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*r4c2TBLy9LvNAVEPHZZ_0g.png" /><figcaption>High level overview of a convolution on an image [<a href="https://github.com/rasbt/machine-learning-book/blob/main/ch14/ch14_part1.ipynb">Sebastian</a>]</figcaption></figure><p>This covers convolutions. Convolutions are extremely powerful mathematical operations to extract more abstract features from already known features. Convolutions are used in convolutional neural networks, which is applied in the name! Convolutions are also use in autoencoders, the main reason why I am writing this article!</p><p>Next I will introduce the relu activation unit and fully connected layer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252eb0e8af21" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-ii-convolutions-252eb0e8af21">Understanding Autoencoders — Part II: Convolutions</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Autoencoders — Part I: Introduction and latent spaces]]></title>
            <link>https://blog.gopenai.com/understanding-autoencoders-part-i-introduction-and-latent-spaces-69cbe68b6fda?source=rss-c5d7259b5b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/69cbe68b6fda</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <dc:creator><![CDATA[Hayden LaBrie]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 05:28:51 GMT</pubDate>
            <atom:updated>2023-08-15T15:40:36.945Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding Autoencoders — Part I: Introduction and latent spaces</strong></h3><p>Generative Deep Learning is a fascinating field that I am discovering myself. During my journey I am going to be making posts here to help others learn generative deep learning neural network designs along with me. I hope I can teach through my writings, and most importantly share my passion across the globe. So let us dive into our first neural network architecture, the autoencoder!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*18jgic_wi9kR-MI0.jpg" /><figcaption>The School of Athens [<a href="https://en.wikipedia.org/wiki/The_School_of_Athens">wiki</a>]</figcaption></figure><p>David Foster just recently released his <a href="https://www.oreilly.com/library/view/generative-deep-learning/9781098134174/">2nd edition of Generative Deep Learning</a> and I believe his story telling to demonstrate difficult concepts in the deep learning field are excellent. I will most likely be borrowing his beautiful stories to help others learn. I hope he does not mind, because I don’t think I could come up with a better way of explaining these concepts.</p><p>David Foster’s Brian, the stitch, and the wardrobe summary:</p><p>Think of a scenario where you are with a stylist named Brian and he is becoming upset because its taking a long amount of time to find certain pieces of clothing you request due to everything on the floor in a huge pile. You could see how this is a problem for Brian the stylist! He is going to have to dig through a ton of stuff just to find the one pair of shoes or a certain shirt you want.</p><p>Now Brian comes up with a super cool plan, but it requires a little magic! Brian wants you to organize your clothes into a wardrobe, which is a standing closet to hold all your clothes. So Brian wants you to have your clothes organized in a standing closet, sure… But he wants the wardrobe to be infinitely high and wide (that&#39;s the magic)! Now once you organize your clothes into a wardrobe you can simply tell Brain the location, and he will sew the item from scratch! It would be like this: Hey Brian, I need you to sew [5,8], which happens to be my cool shirt, and boom its made from scratch! I would like to say it may not be perfect, especially during the first few tries because you two are both learning the ropes of this new ordeal! Actually expect it to be rough during the learning phase, but have a little faith in Brian!</p><p>“It soon becomes obvious that you will need to place similar items near to each other, so that Brian can accurately re-create each item given only its location” [<a href="https://www.oreilly.com/library/view/generative-deep-learning/9781098134174/">Foster</a>]. So imagine if the items in the wardrobe were mixed up and just had a lot of randomness in your wardrobe layout; how would he learn! Having like items next to each other will have him more likely to learn what types of items you want when requesting a certain area of the wardrobe. If you have it all mixed up Brian might make some pants when you wanted a hat! If you have all similar items together, Brian is more likely to learn and have a similar item at least!</p><p>So after some back and forth, you and Brian start to understand the wardrobe well. Brian can make pretty similar things on what you have requested. You have learned how to describe the wardrobe well by location and Brian has learned taking that location and remaking the item! Superb!</p><p>“This gives you an idea — what would happen if you gave Brian a wardrobe location that was empty? To your amazement, you ﬁnd that Brian is able to generate entirely new items of clothing that haven’t existed before! The process isn’t perfect, but you now have limitless options for generating new clothing, just by picking an empty location in the inﬁnite wardrobe and letting Brian work his magic with the sewing machine” [<a href="https://www.oreilly.com/library/view/generative-deep-learning/9781098134174/">Foster</a>]</p><p>Why can Brian make something at a place in the wardrobe where a piece of clothing does not exist? It is because Brian is learning the latent space of the wardrobe. What do I mean by latent space?</p><p>I am going to try to paint a picture here to help you understand what a latent space is. So imagine the set of all common canned food at grocery stores. This set would contain soup cans, bean cans, vegetable cans, tuna cans, pet food cans, etc… Soup cans are often shaped taller and thinner compared to tuna cans. All these different types of cans create a wide variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*377zApIBSxjDqN4c.jpg" /><figcaption>Image of canned food from [<a href="https://www.nytimes.com/2019/09/20/dining/canned-food-melissa-clark-recipes.html">NYT</a>]</figcaption></figure><p>Now if we are analyzing images of these cans, the dimensionality that all these cans are being described as our the sum of all the pixels. What do I mean by this? Well the cans are being described as images and these images are being the input of the neural network. The original dimensionality of the data is the sum of all the pixels because each pixels is describing a feature of the image. Just like how in tabular data each feature is a column, well in images a pixel is a feature. You can think of it like this, in tabular data if all the features are the same in different rows, then the rows are representing the same object; in images if all the pixels are the same then the image is representing the same object.</p><p>Also, I would like to note that features described above are about “an individual measurable property or characteristic of a phenomenon” [<a href="https://en.wikipedia.org/wiki/Feature_(computer_vision)">wiki</a>]. Some may be custom to more than one definition of features. The other definition of features that commonly is thrown around in the deep learning field is about feature extraction mapping. A common feature mapping technique you may be custom to are convolutions: “After passing through a convolutional layer, the image becomes abstracted to a feature map, also called an activation map” [<a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">wiki</a>].</p><p>Okay got side tracked a little on dimensionality, but this is important to understand as I try to continue my story on latent space. So think about how high the dimensionality is for images. If we have the images of these food cans as 3 * 32 * 32, meaning 32 width and 32 height and 3 of them to represent red, green, and blue, we get 3072 pixels. That is a extremely high dimensionality! We probably don’t want to work with this large of a dimensionality. Luckily this is where the concept of a latent space kicks in. Instead of describing the data by all the individual pixels, which is kinda weird, we can describe the image by lower dimensions.</p><p>Now how can I describe these collection of pixels that make up the food cans using smaller dimensions? Well when we think about it there are really 2 major features that effect the can, the width and height! Us humans can understand that we can describe most of the data of the cans by simply 2 features, width and height! A tuna can would have large width and small height while a soup can would have small width and large height.</p><p>We have really just imagined a latent space of these food cans, a space with just 2 variables (width and height). Instead of trying to describe the can using 3072 variables we can just use 2 variables and describe food cans pretty well. Now of course we lose some data during this transformation of 3072 variables to describe an image of cans to only 2. Probably the biggest abstracted feature that we are missing is all the colors on the can. This is a key thing to remember about the latent space of data is that there will be data loss due to abstraction. We are generalizing by dropping many of the variables via feature extraction to define the lower dimensional space. This is really what a latent space is, a way of describing data with less features than the original source.</p><p>Awesome, so we can describe data in lower dimensions, so what? This is where it gets cool! Now we said that we can describe these food cans by 2 dimensions in the latent space, right. Well imagine a 2d graph being width and height of the cans as the variables. We map the 2d graph and see there are plenty of missing spots. What is super cool is we can basically place a marker in a barren spot and then say “hey since you understand how to generate cans with just these 2 variables, set the variables as this and give me back the image” and this works! Its because we have some translator to take the compressed data and decompress it back to its original dimensionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3BFRAEBNQRHuJfSK.png" /><figcaption>Example of multi-dimensional animal latent space sampling [<a href="https://www.baeldung.com/cs/dl-latent-space">Antoniadis</a>]</figcaption></figure><p>Lastly, I would like to mention that in the stylist situation, you describing the clothes in a lower dimensionality, is called the encoder in autoencoders. The stylist, the thing which takes the lower dimensionality description of objects and turns them back to the original spacial dimension, is called the decoder. We will dive much more into the inner workings of how both parts work, and how to implement the autonecoder via pytorch in python. We will use the autoencoder on the mnist fashion dataset and do some analysis!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69cbe68b6fda" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/understanding-autoencoders-part-i-introduction-and-latent-spaces-69cbe68b6fda">Understanding Autoencoders — Part I: Introduction and latent spaces</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>