<?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 Yuanrui Dong on Medium]]></title>
        <description><![CDATA[Stories by Yuanrui Dong on Medium]]></description>
        <link>https://medium.com/@yuanrui.dong.bit?source=rss-32e5bb3fd6d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sdsOBnHB69ob3RX1.jpg</url>
            <title>Stories by Yuanrui Dong on Medium</title>
            <link>https://medium.com/@yuanrui.dong.bit?source=rss-32e5bb3fd6d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:55:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yuanrui.dong.bit/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[ResBlock — A trick to impove the model]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/resblock-a-trick-to-impove-the-model-8ba11891c52a?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba11891c52a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[theory]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Tue, 24 Sep 2019 01:53:05 GMT</pubDate>
            <atom:updated>2019-09-24T01:53:05.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>ResBlock — A simple fix helped make deep networks possible</h3><p>In deep learning, it’s common that the deeper network has stronger ability, and performance is better. However, the deeper network also brings out some problems, such as gradient disappearance and gradient explosion. There’s had many optimizing method, like Batchnormlization layer, Relu activations. Although it’s still limitedly optimized not until <strong>skip connection</strong> is widespread use.</p><p>In the paper 《Deep Residual Learning for Image Recognition》 by Kaiming He and colleagues at (then) Microsoft Research. They trained a 56-layer and a 20-layer. An interesting thing happened that the deeper network has higher training error, and thus test error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*cSmDknQ9cPm9g9gwZ2BpHg.png" /><figcaption>Fig 1. Training error(left) and test error(right) on CIFAR-10 with 20-layer and 56-layer networks.</figcaption></figure><p>Deep learning relies on the chain back propagation of errors to update parameters, after more times multiply, it may result in gradient diffusion. The 56 layer has more parameters, even got a bad performance than shallower one. To figure it out, Kaiming He take the 56-layer network and make a new version of it which is identical but has to be at least as good as the 20 layer network. The identity connection, which is also called a skip connection is shown in Fig 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*Cc3o7Hq7aMb0JPb9UuuxzA.png" /><figcaption>Fig 2.Residual learning: a building block</figcaption></figure><p>Skip connection is usually used in resnet. It’s a way to avoid gradient diffusion. It’s like the differential coefficient plus 1, even if the original one is small, the error can still be backpropagated.</p><p>Figure 2 is what we normally call a ResBlock. The input is x, the desired output is H(x). Through the “skip connections”, the output is H(x) = F(x) + x. Then the block is equivalent to changing the learning goal, no longer learning a complete output, but the difference between the target value H(x) and x, which is called residual F(x) = H(x) -x. In this paper, it made the 56-layer at least as well as 20 layer neural network, because it kind of contained 20-layer network.</p><p>Rachel, I, David, and Sylvain proposed a paper, which figured out how to visualize the loss surface. In Fig 3, it’s the 56-layer network loss surfaces with/without skip connections. The axis of x and y is the weight space, and z is the loss. We can observe that the loss without skip connections is very pumpy, which is covered with hills and valleys. The loss with skip connections is more smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*H4BVhP5huAfKfAG2TFyYXA.png" /><figcaption>Fig 3. The loss surfaces with/without skip connections</figcaption></figure><p>We can create a ResBlock in code. The function is shown like this:</p><p>Output = x +Conv2(Conv1(x))</p><p>It contains two conv layers (a conv_layer is Conv2d, ReLU, batch norm), so create two of those and then in forward we go conv1(x) and conv2 of that and then add x.</p><pre>class ResBlock(nn.Module):<br>    def __init__(self, nf):<br>        super().__init__()<br>        self.conv1 = conv_layer(nf,nf)<br>        self.conv2 = conv_layer(nf,nf)<br>        <br>    def forward(self, x): return x + self.conv2(self.conv1(x))</pre><p>In FastAI, there’s a function called res_block, we can create a network like this.</p><pre>model = nn.Sequential(<br>    conv2(1, 8),<br>    res_block(8),<br>    conv2(8, 16),<br>    res_block(16),<br>    conv2(16, 32),<br>    res_block(32),<br>    conv2(32, 16),<br>    res_block(16),<br>    conv2(16, 10),<br>    Flatten()</pre><p>In our models, it’s a trick to replace the convolutional path with a bunch of ResBlocks, and it may get better results faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba11891c52a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/resblock-a-trick-to-impove-the-model-8ba11891c52a">ResBlock — A trick to impove the model</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dropout]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/understanding-dropout-18f6312a5a42?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f6312a5a42</guid>
            <category><![CDATA[theory]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 07:17:51 GMT</pubDate>
            <atom:updated>2019-09-20T07:17:51.885Z</atom:updated>
            <content:encoded><![CDATA[<p>When training deep neural networks, we always encounter two major shortcomings:</p><p>(1) easy overfitting</p><p>(2) time-consuming</p><p>Dropout can effectively alleviate the occurrence of overfitting and achieve the regularization effect to a certain extent.</p><p>Dropout net model is described in the paper《Dropout: A Simple Way to Prevent Neural Networks from Overfitting》, which is shown in Fig 1. On the left, it’s a normal fully connected neural net, and dropout net is on the right. In neural net, there’re two types of variation, parameters (also called weights) and activations. In Fig 1, the line is a multiplication of an activation times weights, and the activation is the sum of all of these inputs times all of these activations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*JqlhnxZZe2pOkZxkw8JLkg.png" /><figcaption>Fig 1. Dropout Neural Net Model</figcaption></figure><p>For dropout, we throw away some percentage of the activations randomly, so all of the weights that were connected to it are also gone. In Fig 1, the activations in the input layer and hidden layer are deleted randomly, but normally, we only delete activations in the hidden layer.</p><p>When training a neural net, there’s training time and test time. In training time, weight updates and backpropagation, and dropout worked well. At test time, we turn off dropout. If the P-value is 0.5 in training test, it means half of the activations are removed, so in the test time, the activations will be twice than it used to be. In the paper, it suggested multiplying all of your weights at test time by p, which is shown in Fig 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*eh5QKZatGvFrA1TiBN6S3Q.png" /><figcaption>Fig 2. weights difference</figcaption></figure><p>In each training batch, overfitting can be significantly reduced by ignoring some of the activations, and then the next mini-batch, putting them back and throw away some different ones. The dropout percentage depended on the probability p, which usually is 0.5. The reason is that dropout generates the most random network structures at 0.5. This approach can reduce the interaction between activations, which means that some activations rely on other activations to function.</p><p>There’re two reasons that dropout works well.</p><p>(1) Reduces complex interaction between neurons. Because dropout made two neurons do not always appear in a dropout network. In this way, weight updating is no longer dependent on the joint action of implicit nodes with fixed relations, which prevents some features from being effective only under other specific features. Forcing the network to learn more robust features that also exist in random subsets of other neurons. Dropout is a bit like L1, L2 regularization, and reduction of weight makes the network more robust to the loss of specific neuron connections.</p><p>(2) The average effect. Dropout different hidden neurons are similar to training different networks. The random deletion of half of the hidden neurons results in different network structures. The whole dropout process is equivalent to averaging many different neural networks.</p><p>It also should be noticed that too much dropout is reducing the capacity of the model, and it would result in underfitting. It’s necessary to place different dropout values for each layer. In code, you can pass in a list, and it will be applied in each layer. In CNN, it’s a little different, if you pass an int, it will use that for the last layer and half of that value for the earlier layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f6312a5a42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/understanding-dropout-18f6312a5a42">Understanding Dropout</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWD-LSTM]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/awd-lstm-6b2744e809c5?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b2744e809c5</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 02:30:40 GMT</pubDate>
            <atom:updated>2019-09-09T02:30:40.280Z</atom:updated>
            <content:encoded><![CDATA[<p>AWD-LSTM (ASGD Weight-Dropped LSTM) is one of the most popular language models. It has been used in many top papers, and its performance in the character-level model is also excellent. It uses DropConnect and the average random gradient descent method, and several other regularization strategies.</p><p>Long Short-Term Memory (LSTM) is a kind of time Recurrent Neural Network (RNN), which is suitable for processing and predicting sequential sequences, especially for natural language processing.</p><p>It’s rather than just doing a matrix multiply as RNN layer. LSTM cell structure consists of four component, which is a forgotten gate, input gate, output gate and cell state. The architecture is shown as Fig 1, σ represents a sigmoid function, tanh represents a tanh function, X(t) represents the input, h(t-1) means some hidden state, C(t) is the state of the cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*Mr9zEA72R-LdAHtnXyZ0Eg.png" /><figcaption>Fig 1. LSTM cell structure</figcaption></figure><p>(1) Forget gate controls whether to forget. In LSTM, it controls whether to forget the hidden cell state of the upper layer with a certain probability. The input in the figure has the hidden state h(t−1) of the previous sequence and the data X(t) of the sequence. Through an activation function, usually sigmoid, the output of the forget gate is obtained. Since the sigmoid output f(t) is between [0,1], the output represents the probability of forgetting the previous hidden cell state.</p><p>(2) Input gate handles the input of the current sequence position. The Input gate is composed of two parts: the first part is processed with the sigmoid activation function; the second part is processed with the tanh activation function. The results of both two are multiplied later to update the cell state.</p><p>(3) Cell state of LSTM. The results of both the Forget gate and the Input gate act on the cell state C(t).Let’s see how we get C(t) from the cell state C(t−1). Cell state C(t) consists of two parts. The first part is the product of C(t−1) and the Forget gate output f(t), and the second part is the product of Input gate’s output and the output of the hidden state h(t−1) of the previous sequence and the data X(t) of the sequence which are processed with tanh function.</p><p>(4) Output gate. The update of the hidden state h(t) consists of two parts. The first part is sigmoid(cell), which is obtained from the hidden state h(t−1) of the previous sequence, the data X(t) of the sequence, and the activation function sigmoid. The second part is composed of the hidden state C(t) and the tanh activation function.</p><p>LSTM Cell is implemented by PyTorch, which is shown in Fig 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*zH6zyU7LIJEHH7NDFq7egg.png" /><figcaption>Fig 2. LSTM cell implementation</figcaption></figure><p>In AWD-LATM, it proposed the variantSGD — ASGD. ASGD algorithm uses the same gradient update step as SGD algorithm but does not return the weight calculated in the current iteration, instead that it considers the weight of previous iterations and returns an average value.</p><p>LSTM loop connections may results in overfitting. To figure it out, WeightDropout is proposed. WeightDropout is called drop connect in computer vision. It is applied to the weight matrix between hidden states. Traditional Dropout goes to zero for a randomly selected subset of activation at each layer. WeightDropout returns to zero not with activation, but with a randomly selected subset of weights. Therefore, each cell receives input from the random subset of the previous layer. The overfitting of LSTM loop connections can be prevented by discarding partial information of the weight matrix between the hidden states.</p><p>L2 regularization is often used on weights to alleviate overfitting. L2 regularization can also be applied to single-cell activation. Activation regularization penalizes significantly too much activation.</p><p>The main model of AWD LSTM is a regular LSTM with several layers, but using kinds of dropouts. The implementation of AWD LSTM with PyTorch is shown in Fig 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*taWGfyj_cxFyANPp9TA2UA.png" /><figcaption>Fig 3. AWD LSTM implementation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b2744e809c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/awd-lstm-6b2744e809c5">AWD-LSTM</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyper Parameter—Momentum]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/hyper-parameter-momentum-dc7a7336166e?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc7a7336166e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[theory]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 02:19:10 GMT</pubDate>
            <atom:updated>2019-09-09T02:19:10.144Z</atom:updated>
            <content:encoded><![CDATA[<p>When we use the SGD (stochastic mini-batch gradient descent, commonly known as SGD in deep learning) to train parameters, sometimes it decreases very slowly and may fall into the local minimum value, or even zero, as shown in Fig 1 (the picture is from li hongyi, 《one day understanding deep learning》). But it is not always what you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ybWxvtXX1jXvAGVg0h6mSg.png" /><figcaption>Fig 1. SGD without momentum</figcaption></figure><p>There are three places where this pseudo-optimal solution occurs:</p><ol><li>Plateau;</li><li>Saddle point;</li><li>Local minima.</li></ol><p>Momentum is introduced to speed up the learning process, especially for the gradient with high curvature, small but consistent, which can accelerate the learning process. The main idea of momentum is to accumulate the moving average of previous gradients decaying exponentially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZASXdJV80xN7ntdINFEgIQ.jpeg" /><figcaption>Fig 2. SGD with momentumn</figcaption></figure><p>It doesn’t necessarily mean that it’s going to be optimal using momentum. To illustrate these points in Fig 2 (the picture is from li hongyi, 《one day understanding deep learning》), in which red represents the direction of gradient descent, dotted green represents the direction of momentum, and blue represents the direction of actual movement :</p><p>For the first point. The direction of the gradient descent is to the right, but since we set it, there is no momentum at the beginning, so the actual direction of movement is the direction of the gradient descent.</p><p>For the second point. The gradient is going down to the right, but now the ball has a momentum that is moving to the right, which causes the ball to continue moving to the right.</p><p>For the third point. Since it is a local minimum, the gradient value is 0. If it’s normal gradient descent, it’s going to get stuck here. But we also have an impulse to the right, so using momentum, it’s actually moving to the right.</p><p>For the fourth point. Now our gradient descent is going to the left, and we can assume that if the impulse here is bigger than the gradient is going to be. At this point, the ball will continue in the direction of momentum, and it can even get out of the mountain, and get out of the local minima.</p><p>To better understanding momentumn, we create a random signal, and plot the figure when betas are 0.5,0.7,0.9,0.99.</p><p>&gt;&gt;&gt; x = torch.linspace(-4, 4, 200)<br>&gt;&gt;&gt; y = torch.randn(200) + 0.3<br>&gt;&gt;&gt; betas = [0.5, 0.7, 0.9, 0.99]</p><p>The regular momentum function is shown below:</p><p>res = beta*avg+yi</p><p>Including that res represents the result, beta is the value of momentumn, avg is 0.3 in the axample, and yi is the ith number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*DysgnE8WBdQ0BC18s_pfKQ.png" /><figcaption>Fig 3. Random result with regular momentum function</figcaption></figure><p>The result is shown in Fig 3. When the beta is small, it gets a little bumpy. When beta is 0.99, the answer is totally wrong. The reason is that if the momentum is high, the basics you’re away from where you need to be in weight space. It’s literally biased to end up being a higher gradient than the actual gradient.</p><p>So we can fix that with modifying the momentum function:</p><p>res = beta*v1 + (1-beta)*v2.</p><p>It’s quite an exponentially weighted moving average as we know. It dampens the thing that we’re adding in. We can see the result is shown in Fig 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*JqXAfnX9GQVO1pYbY1DquA.png" /><figcaption>Fig 4. Random result with the modified momentumn function</figcaption></figure><p>We can see it gets to a zero-constant when the data is purely random.</p><p>But in fact, we always deal with the signal that is specific, does that work well? To find out it, we create a new function here. The momentum is res = beta*v1 + (1-beta)*v2.</p><p>&gt;&gt;&gt; y = 1 — (x/3) ** 2 + torch.randn(200) * 0.1<br>&gt;&gt;&gt; y[0]=0.5</p><p>At the start, we add an outlier. The result is shown in Fig 5, it shows we’ve got in trouble. When beta is 0.99, in the momentum function, item number two is 0.99 times item number one plus 0.01 times item number two. The number one is massively biasing this data, it takes a very long time to close to the number.</p><p>There is also a problem that we’re always running a bit behind where we should be because we always only taking point one times a new thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*bhcck7Q8dm3CvOMf6J2gTw.png" /><figcaption>Fig 5. Function result with momentum</figcaption></figure><p>To get a better result, we can use debiasing. Debiasing is to correct the wrong information we may have in the very first batch.</p><p>And the function is:</p><p>res = avg/(1-beta**(i+1))</p><p>The result is shown in Fig 6. It’s pretty good, debiasing is very quickly even if you have a bad starting point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*1YNEw7otEVb_vNKjsIVh1A.png" /><figcaption>Fig 6. Function result with debiasing</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc7a7336166e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/hyper-parameter-momentum-dc7a7336166e">Hyper Parameter—Momentum</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using softmax carefully]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/using-softmax-carefully-a4c8f292a841?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c8f292a841</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[softmax]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 06:04:34 GMT</pubDate>
            <atom:updated>2019-09-02T06:08:03.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3ledLHTfW8Ys4SdRv4msA.jpeg" /></figure><p>In deep learning, softmax is a very common and important function, especially in multi-classification image recognition. Originally, it’s performed well in ImageNet. It mapped some inputs to numbers between 0 and 1, and normalized them to ensure that the sum was 1, so that the sum of the probabilities of multiple classifications was exactly 1.</p><p>We take an example. There’re two images. In Fig 1, there’re five categories. We can see outputs of fish and building are also positive. So it’s difficult to figure out what it is. So we used softmax to calculate the probabilities of classes. And the fish’s softmax value is the highest, so the net would classify it as fish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*CGiCCfdKX2v9OtccpnjSMA.png" /><figcaption>Fig 1. Image 1 discription</figcaption></figure><p>In Fig 2, according to the outputs of Image 2, only the fish class is positive. So it’s clear that Image 2 if fish. When we calculate the softmax value of classes, the fish softmax is as same as Image 1 softmax value. Actually the output value of the two images are not same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*owvIj9vCu3K_xXq6nWkQAQ.png" /><figcaption>Fig 2. Image 2 discription</figcaption></figure><p>In two images, it’s maybe going to tell you with high probability that it has one of those things even if it has more than one of them, it’ll just pick one of them and tell you it’s pretty sure it’s got one. Softmax is a terrible idea unless you know that every one of yours when you’re doing image recognition.</p><p>So softmax works in these strict rules:</p><ol><li>only one class</li><li>must belong to one of the classes</li></ol><p>If softmax doesn’t work well. There are two ways to deal with image recognition.</p><p>1. Create another category called background or null or missing. So in the example, there’s 6 categories cat, dog, plane, fish, building or missing.</p><p>A lot of researchers does it, but it doesn’t work some times. The reason why is that if you want to predict a missing category, the penultimate layer activations have to have the features in it. We can clearly distinguish which class it is. But there’s no set of features that when they are all high clearly is not cat,dog, plan, fish, building. That’s not kind of object. It’s hard to classify which class it doesn’t belong to. So lots of well-regarded academic papers make this mistake.</p><p>2. Use binomial regular, which is the result of exp/(1+exp). It’s exactly the same as softmax if your two categories have the thing and doesn’t have the thing. In Fig 3, you can see how the numbers are different from softmax value. Image 1, which looks like there might be a cat, a fish and a building in it. But in image 2, there’s maybe a fish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*mhWgJQ-DrlpVgGkhdCDXbw.png" /><figcaption>Fig 3. Binomial</figcaption></figure><p>Therefore, when you deal with image recognition, probably most of the time you don’t need softmax. If a paper used softmax, it’s necessary for you to think does that actually work with softmax. Maybe the answer’s no. Try replicating it without softmax, maybe you can get a better result.</p><p>In fact, softmax is good for language modeling. Because it’s definitely at least one word and just one word.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c8f292a841" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/using-softmax-carefully-a4c8f292a841">Using softmax carefully</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Initializing a Neural Network is Important!]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/why-initializing-a-neural-network-is-important-5f6268cacc44?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6268cacc44</guid>
            <category><![CDATA[theory]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 02:51:39 GMT</pubDate>
            <atom:updated>2019-08-20T02:51:39.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*Lt5nLfRio3MOK20D-1wXqg.jpeg" /></figure><p>Generally, neural network models rely on stochastic gradient descent for model training and parameter updating. The final performance of the network is directly related to the optimal solution obtained by convergence, and the convergence result actually depends largely on the initialization of network parameters.</p><p>The ideal initialization of network parameters makes the model training get less efforts. On the contrary, the poor initialization scheme will not only affect the network convergence but also lead to gradient dispersion or explosion. So initilization is important in a neural network.</p><p>Here, we take an example: matrix multiplications. Let’s take a vector x, and a matrix a which is initiliazed randomly,</p><pre>&gt;&gt;&gt; x = torch.randn(512)<br>&gt;&gt;&gt; a = torch.randn(512,512)</pre><p>Then multiply them 100 times,</p><pre>&gt;&gt;&gt; for i in range(100): x = a @ x if x.std() != x.std(): break<br>&gt;&gt;&gt; x.mean(),x.std()<br> (tensor(nan), tensor(nan))</pre><p>To explore what happened in the loop, let’s check why it’s not a number.</p><pre>&gt;&gt;&gt; for i in range(100): <br>        x = a @ x<br>        if x.std() != x.std(): break<br>&gt;&gt;&gt; i <br>28</pre><p>The outcome was only 28 iterations before it ended. It shows that when you multiplied by a matrix lots of times you explode out to the point that your computer can’t even keep track.</p><pre>&gt;&gt;&gt; x = torch.randn(512)<br>&gt;&gt;&gt; a = torch.randn(512,512) * 0.01<br>&gt;&gt;&gt; for i in range(100): x = a @ x<br>&gt;&gt;&gt; x.mean(),x.std()<br>(tensor(0.), tensor(0.))</pre><p>If we start set of weights like 0.01 or 1 , it can’t learn anything. Because there are no gradients, the gradients are dispersion or explosion. So it needs to have a reasonable starting point, and this is why for decades people weren’t able to train deep neural network. Thus it’s critical to initialize the network.</p><p>There’s lots of initialization approaches that we can use have been shown in some papers. These papers are shown in Fig 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*8Ev3dF7FSOhVyIHmG0_aVQ.png" /><figcaption>Fig 1. Initialization approaches</figcaption></figure><ol><li>《Understanding the difficulty of training deep feedforward neural networks》. Using Xavier initialization, activation values are well distributed at each layer of the deep network.</li><li>《Delving Deep into Rectifiers》Kaiming_He initialization is proposed by taking ReLU/PReLU into account.</li></ol><p>3. 《All You Need is a Good Init》which describes how you can kind of iteratively go through your network and set one layer of weights at a time to like literally doing a little optimize to find out which set of parameters gets a unit variance at every point。</p><p>4. 《Exact solutions to the nonlinear dynamics of learning in deep linear neural networks》 In this paper the Orthogonal initialization is proposed.</p><p>5. 《Fixup Initialization》 and 《Self-Normalizing Neural Networks》 describe how to try to set a combination of kind of activation functions and in it such that you’re guaranteed a unit variance as deep as you like . And both of those two papers went to something like a thousand layers deep and trained them successfully. In both cases we can get rid of batch norm. But It’s very unlikely be true, because the formula is so long and the caculation is a huge job.</p><p>In PyTorch, variety of parameter initialization functions are provided.</p><ul><li>torch.nn.init.constant(tensor, val)</li><li>torch.nn.init.normal(tensor, mean=0, std=1)</li><li>torch.nn.init.xavier_uniform(tensor, gain=1)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6268cacc44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/why-initializing-a-neural-network-is-important-5f6268cacc44">Why Initializing a Neural Network is Important!</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Broadcasting Application]]></title>
            <link>https://medium.com/ai%C2%B3-theory-practice-business/broadcasting-application-4b777d45974e?source=rss-32e5bb3fd6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b777d45974e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Yuanrui Dong]]></dc:creator>
            <pubDate>Mon, 19 Aug 2019 07:36:58 GMT</pubDate>
            <atom:updated>2019-08-19T07:36:58.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*3sl8MVe-GwvIbr3wqGxIng.jpeg" /><figcaption>url: <a href="http://www.sohu.com/a/228731477_281328">http://www.sohu.com/a/228731477_281328</a></figcaption></figure><p>For the fastai Part 2 courses, it focuses on how to rewrite the pytorch library. Therefore, We know how the library works, and we can apply it more smoothly.</p><p>Broadcasting means how two arrays of different sizes should be handled in an operation. Normally, a smaller array will be broadcast to a larger one to keep the size consistent. The loop operation in the Broadcasting process is carried out at the bottom of C, so the speed is relatively fast. But sometimes broadcasting may lead to performance degradation.</p><p><strong>Broadcasting with a scalar</strong></p><pre>&gt;&gt;&gt; a = tensor([10., 6, -4])<br>&gt;&gt;&gt; a + 1<br>tensor([11., 7., -3.])</pre><p>In this example, the value 1 is broadcast three times, and it does an element-wise sum. So every time you’re broadcasting a scaler to a tensor. This is the simplest kind of broadcasting. And in the process, it’s not operating at python speed. Actually, it’s operating at C or CUDA speed.</p><p><strong>Broadcasting a vector to a matrix</strong></p><pre>&gt;&gt;&gt; c = tensor([10.,20,30]); <br>&gt;&gt;&gt; m = tensor([[1., 2., 3.],<br>        [4., 5., 6.],<br>        [7., 8., 9.]])<br>&gt;&gt;&gt; m.shape,c.shape<br>(torch.Size([3, 3]), torch.Size([3]))<br>&gt;&gt;&gt; m + c<br>tensor([[11., 22., 33.],<br>        [14., 25., 36.],<br>        [17., 28., 39.]])</pre><p>In this example, we’re broadcasting a vector to a matrix. It’s broadcasting the row of c across each row of the matrix m.</p><p><strong>Matrix multiplication</strong></p><p>Here’s two matrices, we multiplied two matrix which is shown in Fig 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*wyDO9ERRu-iXMWoROLHL7g.png" /><figcaption>Fig 1. two matrix multiplication</figcaption></figure><p>The first element of the result is the first row of Rank 1 matrix multiplied with the first column of Rank 2 matrix, and sum them up, then we get the first element is 22. The result is shown in Fig 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*W2RzvKW3RV0VT6qDI0nP9g.png" /><figcaption>Fig 2. the first out element</figcaption></figure><p>The rest can be done in the same manner, then we can calculate the final result in Fig 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*H1263JtPj2wbo2309EJh4w.png" /><figcaption>Fig 3. matrix multiplication out matrix</figcaption></figure><p>We translate it by using code. The code is showing below.</p><pre><strong>def</strong> matmul(a,b):<br>    ar,ac = a.shape <em># n_rows * n_cols</em><br>    br,bc = b.shape<br>    <strong>assert</strong> ac==br<br>    c = torch.zeros(ar, bc)<br>    <strong>for</strong> i <strong>in</strong> range(ar):<br>        <strong>for</strong> j <strong>in</strong> range(bc):<br>            <strong>for</strong> k <strong>in</strong> range(ac): <em># or br</em><br>                c[i,j] += a[i,k] * b[k,j]<br>    <strong>return</strong> c</pre><p>Here, we have three loops. c[i,j] += a[i,k] * b[k,j] is the basic step.This is the vast majority of what’s going to do in deep learning. It’s a huge work and cost time. So we apply the broadcasting in matrix multiplication.</p><h4>Matmul with broadcasting</h4><pre><strong>def</strong> matmul(a,b):<br>    ar,ac = a.shape<br>    br,bc = b.shape<br>    <strong>assert</strong> ac==br<br>    c = torch.zeros(ar, bc)<br>    <strong>for</strong> i <strong>in</strong> range(ar):<br>        c[i]   = (a[i  ].unsqueeze(-1) * b).sum(dim=0)<br>    <strong>return</strong> c</pre><p>Here, c[i] = (a[i ].unsqueeze(-1) * b).sum(dim=0), this is get broadcast so that we can get rid of going through each of range bc. By doing so, not only getting rid of several loops, but also reduce a lot of errors.</p><p>When operating on two arrays/tensors, Numpy/PyTorch compares their shapes element-wise. It starts with the trailing dimensions and works its way forward. The tensors can only be used for broadcasting operation under the two following conditions:</p><ul><li>they are equal, or</li><li>one of them is 1, in which case that dimension is broadcasted to make it the same size.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b777d45974e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai%C2%B3-theory-practice-business/broadcasting-application-4b777d45974e">Broadcasting Application</a> was originally published in <a href="https://medium.com/ai%C2%B3-theory-practice-business">AI³ | Theory, Practice, Business</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>