text
stringlengths
81
47k
source
stringlengths
59
147
Question: <p>I came across the hinge loss function for training a neural network model, but I did not know the analytical form for the same.</p> <p>I can write the mean squared error loss function (which is more often used for regression) as</p> <p><span class="math-container">$$\sum\limits_{i=1}^{N}(y_i - \hat{y_i})^2$$</span></p> <p>where <span class="math-container">$y_i$</span> is the desired output in the dataset, <span class="math-container">$\hat{y_i}$</span> is the actual output by the model, and <span class="math-container">$N$</span> is the total number of instances in our dataset.</p> <p>Similarly, what is the (basic) expression for hinge loss function?</p> Answer: <p>The hinge loss/error function is the typical loss function used for <strong>binary classification</strong> (but it can also be extended to multi-class classification) in the context of <strong>support vector machines</strong>, although it can also be used in the context of neural networks, as described <a href="https://machinelearningmastery.com/how-to-choose-loss-functions-when-training-deep-learning-neural-networks/" rel="nofollow noreferrer">here</a>.</p> <p>The hinge loss function is defined as follows</p> <p><span class="math-container">$$ \ell(y) = \max(0, 1-t \cdot y) \tag{1}\label{1}, $$</span> where</p> <ul> <li><span class="math-container">$t = \{-1, 1\}$</span> is the label (so, if your labels are in the set <span class="math-container">$\{0, 1 \}$</span>, you will have to first map them to <span class="math-container">$\{-1, 1\}$</span>)</li> <li><span class="math-container">$y$</span> is the output of the classifier (e.g. in the context of the linear SVM, <span class="math-container">$y=\mathbf{w} \cdot \mathbf{x}+b$</span>, where <span class="math-container">$\mathbf{w}$</span> and <span class="math-container">$b$</span> are the parameter of the hyper-plane)</li> </ul> <p>This means that the loss in equation \ref{1} is always non-negative. If you're familiar with the <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)" rel="nofollow noreferrer">ReLU</a>, this loss should look familiar to you. In fact, their plots are very similar.</p> <p>For more details, you probably should start with <a href="https://en.wikipedia.org/wiki/Hinge_loss" rel="nofollow noreferrer">the related Wikipedia article</a>, then maybe one of the many machine learning books that covers support vector machines, for example, <a href="http://users.isr.ist.utl.pt/%7Ewurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf#page=345" rel="nofollow noreferrer">Pattern Recognition and Machine Learning</a> (2006) by Christopher Bishop, chapter 7 (page 325).</p>
https://ai.stackexchange.com/questions/26330/what-is-the-definition-of-the-hinge-loss-function
Question: <p>In this <a href="https://www.deeplearning.ai/ai-notes/optimization/" rel="nofollow noreferrer">AI note</a> from <a href="https://deeplearning.ai" rel="nofollow noreferrer">https://deeplearning.ai</a>, the loss function below is used for a regression problem. However, I don't know how to interpret this loss function.</p> <p><a href="https://i.sstatic.net/28SBx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/28SBx.png" alt="loss function" /></a></p> <p>First, does the author take the square of the difference between y-hat (prediction) and y (ground truth), so that positive and negative numbers don't cancel each other out? If so, why do we take the norm or distance, as well? Isn't the norm positive anyway? Or does he take the square so that it's more convenient to calculate the derivative?</p> <p>Second, what does the other 2 in subscript mean? It's not explained in the note and I was also not able to derive it from the context. All I know is that y ∈ R.</p> <p>It seems like I find it difficult to read mathematical notations. If you know a resource that explains these notations, please let me know.</p> Answer: <p>This is the sum of squared residuals, and it uses notation from the mathematical subfield of linear algebra (arguably functional analysis).</p> <p>The double vertical bars indicate that we use the mathematical operation of a <a href="https://en.wikipedia.org/wiki/Norm_(mathematics)" rel="nofollow noreferrer">norm</a>, which is a special kind of measure of distance that holds familiar properties.</p> <p>The subscript <span class="math-container">$2$</span> means that it is the <span class="math-container">$L_2$</span> norm. Until you know this notation, there’s no way to know that, but it’s so common that it’s worth remembering what an <span class="math-container">$L_p$</span> norm means. Let <span class="math-container">$x=(x_1,\dots,x_n)\in\mathbb R^n$</span> be a vector of real numbers.</p> <p><span class="math-container">$$ \vert \vert x \vert\vert_p = \left( \sum_{i=1}^n\vert x_i\vert^p \right)^{1/p} $$</span></p> <p>For the <span class="math-container">$2$</span>-norm in your equation, this is just the usual Euclidean distance.</p> <p>The <span class="math-container">$2$</span> superscript has its usual meaning, that you square the <span class="math-container">$L_2$</span> norm once you calculate it.</p> <p>Finally, <span class="math-container">$y-\hat y$</span> means that you take the vector of true <span class="math-container">$y$</span>-values and subtract the vector of predicted <span class="math-container">$y$</span>-values, denoted by <span class="math-container">$\hat y$</span>.</p> <p>In total:</p> <ol> <li><p>Take the difference between the true and predicted values.</p> </li> <li><p>Square each component of that difference.</p> </li> <li><p>Add up all of those squared differences.</p> </li> <li><p>Take the square root of that sum.</p> </li> <li><p>Square that square root.</p> </li> </ol> <p>As the last step undoes the fourth step to get you back to the third step, you can stop at step <span class="math-container">$3$</span>.</p> <p><strong>EDIT</strong></p> <p>It is common to refer to the residuals as errors. From a statistical standpoint, this is not quite correct, though it seems to be a reasonable slang that does not cause confusion among experienced practitioners.</p>
https://ai.stackexchange.com/questions/36709/how-do-i-interpret-this-loss-function
Question: <p>For imbalanced datasets (either in the context of computer vision or NLP), from what I learned, it is good to use a weighted log loss. However, in competitions, the people who are in top positions are not using weighted loss functions, but treating the classification problem as a regression problem, and using MSE as the loss function. I want to know which one should I use for imbalanced datasets? Or maybe should I combine both?</p> <pre><code>the weighted loss I am talking is:: neg_weights=[] pos_weights=[] for i in tqdm(range(5)):##range(num_classes) neg_weights.append(np.sum(y_train[:,i],axis=0)/y_train.shape[0]) pos_weights.append(np.sum(1-y_train[:,i],axis=0)/y_train.shape[0]) def customloss(y_true,y_pred): y_true=tf.cast(y_true,dtype=y_pred.dtype) loss=0.0 loss_pos=0.0 loss_neg=0.0 for i in range(5): loss_pos+=-1*(K.mean(pos_weights[i]*y_true[:,i]*K.log(y_pred[:,i]+1e-8))) loss_neg+=-1*(K.mean(neg_weights[i]*(1-y_true[:,i])*K.log(1-y_pred[:,i]+1e-8))) loss=loss_pos+loss_neg return loss </code></pre> <p>the competition I was talking about is <a href="https://www.kaggle.com/c/aptos2019-blindness-detection/discussion/109594" rel="nofollow noreferrer">https://www.kaggle.com/c/aptos2019-blindness-detection/discussion/109594</a></p> Answer:
https://ai.stackexchange.com/questions/23653/which-loss-function-to-choose-for-imbalanced-datasets
Question: <p>I've been studying NNs with tensorflow and decided to code a simple NN from scratch to get a better idea on hwo they work.</p> <p>It my understanding that the cost is used in backpropagation, so basically you calculate the error between prediction and actual and backpropagate from there.</p> <p>However, in all the examples I read online, even the ones doing classification, just use:</p> <p>error=actual-prediction instead of: error=mse(actual-prediction) or: error=cross_entropy(actual-prediction)</p> <p>And they leave mae/rmse etc just as a metric, as per my understanding (probably wrong) understanding, these should/could be used to calculate the error as well. On the other hand, while working with tensorflow, the loss function I use, does change the output and its not just a metric.</p> <p>What's my error in here?</p> <p>In other words, isn't the loss function same as the error function?</p> <p>Example code (taken from: machinelearninggeek.com/backpropagation-neural-network-using-python/):</p> <p>Note how the MSE is used as metric only, while backpropagation only uses pred-outputs. (E1 = A2 - y_train)</p> <pre><code>for itr in range(iterations): # feedforward propagation # on hidden layer Z1 = np.dot(x_train, W1) A1 = sigmoid(Z1) # on output layer Z2 = np.dot(A1, W2) A2 = sigmoid(Z2) # Calculating error mse = mean_squared_error(A2, y_train) acc = accuracy(A2, y_train) results=results.append({&quot;mse&quot;:mse, &quot;accuracy&quot;:acc},ignore_index=True ) # backpropagation E1 = A2 - y_train dW1 = E1 * A2 * (1 - A2) E2 = np.dot(dW1, W2.T) dW2 = E2 * A1 * (1 - A1) # weight updates W2_update = np.dot(A1.T, dW1) / N W1_update = np.dot(x_train.T, dW2) / N W2 = W2 - learning_rate * W2_update W1 = W1 - learning_rate * W1_update <span class="math-container">```</span> </code></pre> Answer: <p>I think you are confused about the terms <em>error</em>, <em>loss function</em> and <em>metric</em>.</p> <p>To summarize:</p> <ol> <li>Error (vector) tells us how off each prediction is.</li> <li>Loss function maps the error (vector) to a single number (loss).</li> <li>Loss and metric (scalar) describes overall how well the predictions are, serving as direction towards which the model should improve.</li> </ol> <p>Note these terms are general and do not apply only to neural networks.</p> <p><strong>TL;DR</strong></p> <p>Let's take a regression problem as example. Suppose we have a regression model which predicts [-4, 3, 0, 7] where the ground truth is [0, 1, 2, 3]. Clearly, some predictions are off. But by how far? Intuitively, we can get the &quot;off&quot; part by subtraction:</p> <p>prediction - actual = [-4, 3, 0, 7] - [0, 1, 2, 3] = <strong>[-4, 2, 2, 4]</strong></p> <p>which is what we call the <strong>error (vector)</strong>.</p> <p>Now we show the error to the model and say, &quot;hey, those are the wrongs you made, do better next round&quot;, to which the model replies, &quot;sure, which one do you prefer?&quot; and hands you 2 new predictions:</p> <ol> <li>[-2, 3, 0, 5]</li> <li>[0, 1, 2, 10]</li> </ol> <p>Which one is better? Well, it depends on you goal: if you want &quot;as close to the truth as possible on average&quot;, then 1) may be better; or if you say &quot;no prediction should be below the truth&quot;, then 2) is the only choice. Regardless, you have to tell the model <em>which one direction it should improve towards</em> - and this is what <strong>loss function</strong> is for.</p> <p>Let's say we decide to use mean-squared error (MSE) as loss function. Computing gives:</p> <p>Loss_1 = Mean(Square(error vector)) = Mean(Square([-2,3,0,5] - [0,1,2,3])) = Mean(Square([-2,2,-2,2])) = Mean([4,4,4,4]) = <strong>4</strong></p> <p>Loss_2 = Mean(Square(error vector)) = Mean(Square([0,1,2,10] - [0,1,2,3])) = Mean(Square([0,0,0,7])) = Mean([0,0,0,49]) = <strong>12.25</strong></p> <p>We call the result of loss function <strong>loss (scalar)</strong>. We want the loss to be small (minimize), so we tell the model, &quot;1) is the better way to go&quot;. Notice that the loss is <strong>a scalar</strong>, and is an indicator of <em>goodness of prediction</em>. In real, a model improves its prediction ('learn') by repeating</p> <p>make predictions -&gt; compute error vector -&gt; compute loss -&gt; feed to optimization algorithm -&gt; update model parameters -&gt; make new predictions</p> <p>(Often you would see the terms <em>loss</em> and <em>metric</em> used interchangeably; in brief, metric is the ultimate goal you want to achieve, a number you want to maximize; however for practical reason the optimization process prefers differentiable function, but metric may not be. In this case we usually choose a loss function which is both differentiable and 'close' to the metric. Since MSE is differentiable, it can serve as loss and metric.)</p> <p><strong>Update</strong></p> <p>In the code quoted, the computation of loss is hidden in the line <code>dW1 = E1 * A2 * (1 - A2)</code> (and similarly in the upcoming <code>E2</code> and <code>dW2</code> lines). Here, back-propagation is applied which implicitly assumes a squared loss is used. Through some maths tricks and simplification, we arrive at the <code>E1</code> formula. You may find the full derivation <a href="https://en.wikipedia.org/wiki/Backpropagation#Finding_the_derivative_of_the_error" rel="nofollow noreferrer">here</a>.</p>
https://ai.stackexchange.com/questions/38905/what-is-loss-function-in-neural-networks
Question: <p>We need to use a loss function for training the neural networks.</p> <p>In general, the loss function depends only on the desired output <span class="math-container">$y$</span> and actual output <span class="math-container">$\hat{y}$</span> and is represented as <span class="math-container">$L(y, \hat{y})$</span>.</p> <p>As per my current understanding,</p> <blockquote> <p>Regularization is nothing but using a new loss function <span class="math-container">$L'(y,\hat{y})$</span> which must contain a <span class="math-container">$\lambda$</span> term (formally called as regularization term) for training a neural network and can be represented as</p> <p><span class="math-container">$$L'(y,\hat{y}) = L(y, \hat{y}) + \lambda \ell(.) $$</span></p> <p>where <span class="math-container">$\ell(.)$</span> is called regularization function. Based on the definition of function <span class="math-container">$\ell$</span> there can be different regularization methods.</p> </blockquote> <p>Is my current understanding complete? Or is there any other technique in machine learning that is also considered a regularization technique? If yes, where can I read about that regularization?</p> Answer: <p>Regularization is not limited to methods like L1/L2 regularization which are specific versions of what you showed.</p> <p>Regularization is any technique that would prevent network from overfitting and help network to be more generalizable to unseen data. Some other techniques are Dropout, Early Stopping, Data Augmentation, limiting the capacity of network by reducing number of trainable parameters.</p>
https://ai.stackexchange.com/questions/28855/does-regularization-just-mean-using-an-augmented-loss-function
Question: <p>I was trying to implement the loss function of <a href="https://yanweifu.github.io/papers/hairstyle_v_14_weidong.pdf" rel="nofollow noreferrer">H-GAN</a>. Here is my <a href="http://codepad.org/9C3Vac25" rel="nofollow noreferrer">code </a>. But it seem somethings wrong, maybe is recognition loss on z (EQ 9). I used the EQ 5 on <a href="https://arxiv.org/pdf/1902.03938.pdf" rel="nofollow noreferrer">MISO</a> to calculate it. Here is my code: </p> <pre><code>def recognition_loss_on_z(self,latent_code, r_cont_mu, r_cont_var): eplison = (r_cont_mu - latent_code) / (r_cont_var+1e-8) return -tf.reduce_mean(tf.reduce_sum(-0.5*tf.log(2*np.pi*r_cont_var+1e-8)-0.5*tf.square(eplison), axis=1))/(config.batch_size * config.latent_dim) </code></pre> <p>And I calculated loss function: </p> <pre><code> self.z_mean, self.z_sigm = self.Encode(self.images) self.z_x = tf.add(self.z_mean, tf.sqrt(tf.exp(self.z_sigm))*self.ep) self.D_pro_logits, self.l_x_real, self.Q_y_style_given_x_real, continuous_mu_real, continuous_var_real = self.discriminator(self.images, training=True, reuse=False) self.De_pro_tilde, self.l_x_tilde, self.Q_y_style_given_x_tidle, continuous_mu_tidle, continuous_var_tidle= self.discriminator(self.x_tilde, training=True, reuse = True) self.G_pro_logits, self.l_x_fake, self.Q_y_style_given_x_fake, continuous_mu_fake, continuous_var_fake = self.discriminator(self.x_p, training=True, reuse=True) tidle_latent_loss = self.recognition_loss_on_z(self.z_x, continuous_mu_tidle,continuous_var_tidle) real_latent_loss = self.recognition_loss_on_z(self.z_x, continuous_mu_real,continuous_var_real) fake_latent_loss = self.recognition_loss_on_z(self.zp, continuous_mu_fake,continuous_var_fake) </code></pre> <p>And discriminator: </p> <pre><code> def discriminator(self, x_var,training=False, reuse=False): with tf.variable_scope("discriminator_recongnizer") as scope: if reuse==True: scope.reuse_variables() conv1 = tf.nn.leaky_relu(batch_normalization(conv2d(x_var, output_dim = 64 , kernel_size=6, name='dis_R_conv1'),training = training,name='dis_bn1', reuse = reuse), alpha =0.2) conv2 = tf.nn.leaky_relu(batch_normalization(conv2d(conv1, output_dim = 128 , kernel_size=4, name='dis_R_conv2'),training = training ,name='dis_bn2', reuse = reuse), alpha =0.2) conv3 = tf.nn.leaky_relu(batch_normalization(conv2d(conv2, output_dim = 128 , kernel_size=4, name='dis_R_conv3'),training = training,name='dis_bn3', reuse = reuse), alpha =0.2) conv4 = conv2d(conv3, output_dim = 256 , kernel_size=4, name='dis_R_conv4') lth_layer = conv4 conv4 = tf.nn.leaky_relu(batch_normalization(conv4, training=training, name='dis_bn4', reuse = reuse),alpha =0.2) conv4 = tf.reshape(conv4,[-1, 256*8*8]) #Discriminator with tf.variable_scope('discriminator'): d_output = fully_connect(conv4, output_size=1, scope='dr_dense_2') with tf.variable_scope('dis_q'): fc_r = tf.nn.leaky_relu(batch_normalization(fully_connect(conv4, output_size=256 + config.style_classes, scope='dis_dr_dense_3'), training=training, name='dis_bn_fc_r', reuse=reuse), alpha=0.2) continuous_mu = fully_connect(fc_r, output_size=256, scope='dis_dr_dense_mu') continuous_var = tf.exp(fully_connect(fc_r, output_size=256, scope='dis_dr_dense_logvar')) style_predict = fully_connect(fc_r, output_size=config.style_classes, scope='dis_dr_dense_y_style') return d_output,lth_layer,style_predict,continuous_mu,continuous_var </code></pre> <p>Does anyone have experience with that, please tell me where I was wrong. Thanks you so much, I really appreciate that!</p> Answer:
https://ai.stackexchange.com/questions/16101/how-to-implement-loss-function-of-h-gan-model
Question: <p>I have a binary classification problem, where there are multiple correct predictions, however, I would consider the prediction to be correct if the highest confidence prediction of a 1 is correct.</p> <p>I have had limited success with a CNN using the Hinge loss function. I think the reason is that, this loss function is calculating the loss between every element in y_true and y_pred.</p> <p>Example:</p> <p>I want my model to confidently predict one of these cells as a 1. There probably isn't enough information in the input data to accurate predict every 1, especially in the areas far from input cells with a positive value, therefore I would be happy if the model is conservative and predicts a 0 where it is unsure.</p> <p><strong>input_data</strong></p> <p><a href="https://i.sstatic.net/Hd9pc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Hd9pc.png" alt="enter image description here" /></a></p> <p><strong>y_pred:</strong></p> <p><a href="https://i.sstatic.net/Io3Xg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Io3Xg.png" alt="enter image description here" /></a></p> <p>I believe the model is being optimized to classify as many cells correctly as possible.</p> <p>It's not possible to correctly predict the cell in the bottom right corner in this example. Therefore the model should take the conservative approach and predict a 0.</p> <p><strong>y_true</strong></p> <p><a href="https://i.sstatic.net/dspWT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dspWT.png" alt="enter image description here" /></a></p> <p>A perfect loss function in my mind would:</p> <ul> <li><p>Heavily penalize the case where (y_true, y_pred) = (0,1) (false positive)</p> </li> <li><p>Heavily reward the case where (y_true, y_pred) = (1,1) (true<br /> positive)</p> </li> <li><p>Moderately penalize the cases where (y_true, y_pred) = (1,0) (false<br /> negative)</p> </li> <li><p>Moderately reward the cases where (y_true, y_pred) = (0,0) (true<br /> negative)</p> </li> </ul> <p>Or</p> <p>Calculate the loss only on the cell with the highest value in y_pred Can anybody suggest a suitable loss function?</p> <p>Let me know if I have omitted any required detail</p> Answer:
https://ai.stackexchange.com/questions/37453/loss-function-for-binary-classification-with-multiple-correct-choices
Question: <p>Loss functions are useful in calculating loss and then we can update the weights of a neural network. The loss function is thus useful in training neural networks.</p> <p>Consider the following excerpt from <a href="https://ai.stackexchange.com/questions/28877/what-are-the-necessary-mathematical-properties-to-be-a-loss-function-in-gradient">this</a> answer</p> <blockquote> <p>In principle, differentiability is sufficient to run gradient descent. <strong>That said, unless <span class="math-container">$L$</span> is convex, gradient descent offers no guarantees of convergence to a global minimiser</strong>. In practice, neural network loss functions are rarely convex anyway.</p> </blockquote> <p>It implies that the convexity property of loss functions is useful in ensuring the convergence, if we are using the gradient descent algorithm. There is <a href="https://ai.stackexchange.com/questions/28288/in-logistic-regression-why-is-the-binary-cross-entropy-loss-function-convex">another narrowed version of this question</a> dealing with cross-entropy loss. But, this question is, in fact, a general question and is not restricted to a particular loss function.</p> <p>How to know whether a loss function is convex or not? Is there any algorithm to check it?</p> Answer: <p>It is the same as other functions. You can use Theorem 2 in <a href="https://www.princeton.edu/%7Eaaa/Public/Teaching/ORF523/S16/ORF523_S16_Lec7_gh.pdf" rel="nofollow noreferrer">this lecture</a> (from Princeton University):</p> <p><a href="https://i.sstatic.net/AL3yc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AL3yc.png" alt="enter image description here" /></a></p> <p>(ii) condition is about the first-order condition for convexity and (iii) is the second-order. You can also find more detail in chapter 3 of <a href="https://stanford.edu/%7Eboyd/cvxbook/bv_cvxbook.pdf" rel="nofollow noreferrer">this book</a> (&quot;Convex Optimization&quot; by Stephen Boyd and Lieven Vandenberghe).</p>
https://ai.stackexchange.com/questions/29963/how-to-check-whether-my-loss-function-is-convex-or-not
Question: <p>I am trying make an ANN model that takes a constant m (will be changed later but now it is just a constant, let's say 0) as an input and generate 5 non-integer numbers (a1,a2..a5) after some layers like relu, linear,relu ... and then these 5 numbers enter to the loss function layer along with an additional 5 numbers (b1,b2..b5) given by hand directly into the same loss function. In the loss function, S=a1xb1+...+a5xb5 will be calculated and the model should use mean square error with this S and S0, which is given by hand again to tune the 5 numbers generated after the NN layers.</p> <p>For a dummy like me, this looks like a totally different model than the examples online. I'd really appreciate any guidance here like the model I should use, examples etc. I can't even know where to start even though I believe I understand the generic NN examples that one can find online.</p> <p>Thanks</p> Answer:
https://ai.stackexchange.com/questions/17473/generating-5-numbers-with-1-input-before-loss-function
Question: <p>What loss function is most appropriate when training a model with target values that are probabilities? For example, I have a 3-output model. I want to train it with a feature vector <span class="math-container">$x=[x_1, x_2, \dots, x_N]$</span> and a target <span class="math-container">$y=[0.2, 0.3, 0.5]$</span>. </p> <p>It seems like something like cross-entropy doesn't make sense here since it assumes that a single target is the correct label.</p> <p>Would something like MSE (after applying softmax) make sense, or is there a better loss function?</p> Answer: <p>Actually, the <a href="https://en.wikipedia.org/wiki/Cross_entropy" rel="noreferrer">cross-entropy</a> loss function would be appropriate here, since it measures the &quot;distance&quot; between a distribution <span class="math-container">$q$</span> and the &quot;true&quot; distribution <span class="math-container">$p$</span>.</p> <p>You are right, though, that using a loss function called &quot;cross_entropy&quot; in many APIs would be a mistake. This is because these functions, as you said, assume a one-hot label. You would need to use the general cross-entropy function,</p> <p><span class="math-container">$$H(p,q)=-\sum_{x\in X} p(x) \log q(x).$$</span> <span class="math-container">$ $</span></p> <p>Note that one-hot labels would mean that <span class="math-container">$$ p(x) = \begin{cases} 1 &amp; \text{if }x \text{ is the true label}\\ 0 &amp; \text{otherwise} \end{cases}$$</span></p> <p>which causes the cross-entropy <span class="math-container">$H(p,q)$</span> to reduce to the form you're familiar with:</p> <p><span class="math-container">$$H(p,q) = -\log q(x_{label})$$</span></p>
https://ai.stackexchange.com/questions/11816/what-loss-function-to-use-when-labels-are-probabilities
Question: <p>Loss_Function/Maximize_Function/Score_Function, CustomLoss, pytorch. Using Custom Loss for Maximizing Score in PyTorch</p> <p>I'm using a PyTorch model with an LSTM input layer, a linear hidden layer, and 3 neurons in the output layer with a softmax activation function.</p> <p>Instead of using a loss function (such as nn.MSELoss()) and passing the model's prediction and its target (loss = criterion(predictions, target)), I would like to use a custom scoring function that I've created. This scoring function is represented as score = get_score(predictions), which implies a concept similar to maximizing (predictions, score).</p> <p>However, since I don't possess a target for each input value of the model, the model would be evaluated based on its score (which is a single number). It appears that considering a single value as a basis for assessing a set of predictions across the entire dataset might not be valid.</p> <p>Is something like this possible? The times I've attempted it, I often encounter an error during the 'loss'.backward() phase, as it fails to trace the necessary gradients for backpropagation.</p> <p>I didn't put the code because it's a very big code, but I'll make a simple example.</p> <pre><code>class Model_123(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(10, 3) def forward(self, x): out = self.linear1(x) out = F.softmax(out, dim=1) return out dataset = torch.randn(10, 10) model = Model_123() custom_loss_score = CustomLoss_Score() # This is what I want to figure out for epoch in range(epochs): model.train() optimizer.zero_grad() predictions = model(dataset) score = random.uniform(0, 100) # Random score just for demonstration, but it would be calculated based on the model's actions. # Using torch.argmax on the predictions made by the model for that input value. # This gives me a success rate, where correctly predicting action 0 or action 1 gets +1, # while action 2 means doing nothing. In a situation where the model correctly predicts only one action, # between actions 0 and 1, and everything else is action 2, leading to a 100% success rate. # This scenario is not good as there's no criteria; it just guessed one action and got 100% score. # It would be better if the model correctly predicted 80% of actions with a 70% operation rate, # which would be a better outcome. So, based on the success rate, I create another function # to calculate the score, a relation between the success rate and the number of operations performed. # This is a much larger code that I haven't included here. loss_score = custom_loss_score(predictions, score) # Maximize the score loss_score.backward() optimizer.step() </code></pre> <p>This scoring mechanism, represented as score, would ideally be maximized by adjusting the model's parameters. However, I'm unsure about how to define the CustomLoss_Score() function that would achieve this.</p> <p>The score is generated based on the model's actions, and it's calculated using a relationship between the accuracy rate and the number of operations performed. The intention is to maximize this score rather than minimizing a traditional loss function.</p> <p>The reason I'm not using Reinforcement Learning is that in this case, I would have to loop through all states (or input data), which takes more time. On the other hand, with supervised learning, I can approach it in a vectorized manner. I'm following this strategy because I'm also utilizing training based on genetic algorithms, which involve multiple individuals (sets of model weights) making predictions on the data. If I were to use Reinforcement Learning, each individual would have to loop through the states, and this would be quite time-consuming, especially with a population size of, for example, 300 individuals.</p> <p>Hence, I'm employing a training approach based on gradient descent, along with training using genetic algorithms and artificial selection.</p> <p>When the model seems to be stuck in a particular place, I take the weights from that model and generate a population of individuals. Genetic algorithms can guide the weights to places where gradient descent might struggle, and vice versa. When one approach isn't yielding improvements, I switch to the other approach.</p> Answer: <p>I suspect you could be reinventing the wheel a little bit here, because some of the description of what this task is <em>for</em> appears to match to a Reinforcement Learning (RL) scenario. You may find if you research approaches using neural networks to solve RL problems, that you get a lot of insight into things that could help with your problem.</p> <p>However, there is also a general answer using the approach from RL <em>Policy Gradients</em>, assuming your NN output layer is a multiclass classifier for which action to take.</p> <ol> <li>You need to store inputs to the NN used to generate actions (let's call them <span class="math-container">$S_t$</span>), until you have the associated score function results. Let's call the score function value <span class="math-container">$G$</span>, and it will be the same for consecutive samples of <span class="math-container">$S_t$</span> - each group that ends with a known score is an &quot;episode&quot;.</li> <li>Along with those inputs, you need to store the <em>actual</em> action taken when that input was supplied, let's call that <span class="math-container">$A_t$</span>. This action <em>can</em> be different to the argmax choice from the classifier. You should be sampling actions according to the probabilities from the classifier (a different sampling approach is possible in general, but won't work well with the rest of the instructions here, because we rely on seeing the different scores in correct ratios).</li> <li>Once you have some results with score functions - ideally from several runs to reduce correlation between inputs - then you can use them to construct a minibatch for supervised learning. Retrospectively set a bunch of <span class="math-container">$G_t$</span> to match the <span class="math-container">$S_t$</span> and <span class="math-container">$A_t$</span> values.</li> <li>Calculate the &quot;ground truth&quot; for each input <span class="math-container">$S_t$</span> as the action that was taken <span class="math-container">$A_t$</span>. It doesn't matter whether the action was the best or correct one to take, it matters that it was the one that was actually taken, and as above, ideally sampled according to your classifier probabilities.</li> <li>Calculate the parameter gradient for each input, output combination as normal for your neural network for supervised learning and multiclass cross-entropy loss . . . but</li> <li>Before you add to the total gradient for the minibatch, multiply the weights gradient by a normalised <span class="math-container">$G_t$</span>. You can change the normalisation parameters over time - typically you subtract some average <span class="math-container">$\bar{G}$</span> seen so far (e.g. running average of results from last 100 episodes) and maybe multiply by some value to put into an easy to handle range, so <span class="math-container">$\nabla_{\theta, t} \leftarrow \beta(G_t - \bar{G})\nabla_{\theta, t}$</span>. This is the &quot;trick&quot; from policy gradients that means the neural network will learn to avoid low total scores and find high total scores on average across many updates. The offset is not required, but makes the learning process faster and more stable. The multiplication is not required either, provided you are happy to try different learning rates instead. So the absolute bare bones version is <span class="math-container">$\nabla_{\theta, t} \leftarrow G_t\nabla_{\theta, t}$</span></li> <li>Complete the minibatch by taking a positive gradient step on the mean gradient (perhaps multiplied by some learning rate, or modified with an optimiser like Adam)</li> </ol> <p>This is pretty much <em>REINFORCE with baseline</em>, a policy gradient method from RL, as applied to discrete action space and a softmax action classifier. It can in theory be applied in scenarios which are not technically setup as RL problems, as long as you can follow the procedure, and it reliably means something to generate a &quot;good&quot; sequence of output choices based on available inputs, by some measure (your score in this case).</p>
https://ai.stackexchange.com/questions/41933/how-to-transform-a-loss-function-into-a-score-function
Question: <p>Recently I developed a custom training algorithm for deep learning models, based on evolutionary algorithms. Details are not important, except that it also uses decreasing regular cross entropy loss as its fitness function.</p> <p>What I observed is that it very well decreases the loss function but the classification metrics such as accuracy, precision or recall also decrease along the training. This got me confused, as I was sure that decreasing loss such as cross entropy should always increase these metrics. After researching I found out this is possible due to fact that cross entropy can decrease in case where confidence on few samples is greatly increasing, but many other samples are meanwhile getting incorrect scores, but the profit from these few correct ones are dominant over many incorrect ones: <a href="https://www.quora.com/What-is-the-matter-when-loss-decreases-and-accuracy-decreases-too-on-training-neural-network?top_ans=238980470" rel="nofollow noreferrer">https://www.quora.com/What-is-the-matter-when-loss-decreases-and-accuracy-decreases-too-on-training-neural-network?top_ans=238980470</a></p> <p>So my question is: is there a loss function that when decreasing will always be increasing classification metrics?</p> Answer: <p>Different metrics measure different quantities, so there is no reason to expect different metrics to move together unless one is a function of the other (such as MSE and RMSE).</p> <p>Further, metrics like accuracy use thresholds that can prove problematic, versus evaluating the probability outputs directly. This is discussed extensively on the statistics Stack, Cross Validated. I will leave a few links.</p> <p><a href="https://stats.stackexchange.com/a/312787/247274">https://stats.stackexchange.com/a/312787/247274</a></p> <p><a href="https://stats.stackexchange.com/a/359936/247274">https://stats.stackexchange.com/a/359936/247274</a></p> <p><a href="https://stats.stackexchange.com/a/312124/247274">https://stats.stackexchange.com/a/312124/247274</a></p> <p>However, even strictly proper scoring rules do not have to move together. Since, for instance, Brier score and log loss (both of which are examples of the strictly proper scoring rules discussed in the first link) are measures of different quantities, this is desirable. Depending on what we value, we might prefer one over the other.</p>
https://ai.stackexchange.com/questions/37176/what-loss-function-will-be-correlated-with-classification-metrics
Question: <p>I have a Deep Feedforward Neural Network <span class="math-container">$F: W \times \mathbb{R}^d \rightarrow \mathbb{R}^k$</span> (where <span class="math-container">$W$</span> is the space of the weights) with <span class="math-container">$L$</span> hidden layers, <span class="math-container">$m$</span> neurones per layer and ReLu activation. The output layer has a softmax activation function.</p> <p>I can consider two different loss functions: </p> <p><span class="math-container">$L_1 = \frac{1}{2} \sum_i || F(W,x_i) - y||^2$</span> <span class="math-container">$ \ \ \ $</span> and <span class="math-container">$\ \ \ L_2 = -\sum_i log(F(w,x_i)_{y_i})$</span></p> <p>where the first one is the classic quadratic loss and the second one is cross entropy loss. </p> <p>I'd like to study the norm of the derivative of the loss function and see how the two are related, which means: </p> <p>1) Let's assume I know that <span class="math-container">$|| \frac{\partial L_2(W, x_i)}{\partial W}|| &gt; r$</span>, where <span class="math-container">$r$</span> is a small constant. What can I assume about <span class="math-container">$|| \frac{\partial L_1(W, x_i)}{\partial W}||$</span> ?</p> <p>2) Are there any result which tell you that, under some hypothesis (even strict ones) such as a specific random initialisation, <span class="math-container">$|| \frac{\partial L_1(W, x_i)}{\partial W}||$</span> doesn't go to zero during training?</p> <p>Thank you</p> Answer: <p>Let's first express a network of arbitrary topology and heterogeneous or homogeneous cell type arrangements as</p> <p><span class="math-container">$$ N(T, H, s) := \, \big[\, \mathcal{Y} = F(P_s, \, \mathcal{X}) \,\big] \\ s \in \mathbb{C} \; \land \; s \le S \; \text{,} $$</span></p> <p>where <span class="math-container">$S$</span> is the number of learning states or rounds, <span class="math-container">$N$</span> is the network of <span class="math-container">$T$</span> topology and <span class="math-container">$H$</span> hyper-parameter structure and values that at stage <span class="math-container">$s$</span> produces a <span class="math-container">$P$</span> parameterized function <span class="math-container">$f$</span> of <span class="math-container">$\mathcal{X}$</span> resulting in <span class="math-container">$\mathcal{Y}$</span>. In supervised learning, the goal is that <span class="math-container">$F(P_s)$</span> approaches a conceptually ideal function <span class="math-container">$F_i$</span> as <span class="math-container">$s \rightarrow S$</span>.</p> <p>The popular loss aggregation norms are not quite as the question defines them. The below more canonically expresses the level 1 and 2 norms, which systematically aggregate multidimensional disparity between an intermediate result at some stage (epoch and example index) of training and the conceptual ideal toward which the network in training is intended to converge.</p> <p><span class="math-container">$$ {||F-\mathcal{Y}||}_1 = \sum{|F_i - y_i|} \\ {||F-\mathcal{Y}||}_2 = \sqrt{\sum{(F_i - y_i)}^2} $$</span></p> <p>These equations have been mutated by various authors to make various points, but those mutations have obscured the obviousness of their original relationship. The first is where distance can be aggregated through only orthogonal vector displacements. The second is where aggregation uses the minimum Cartesian distance by extending the Pythagorean theorem.</p> <p>Note that <em>quadratic loss</em> is a term with some ambiguity. These are all broadly describable as quadratic expressions of loss.</p> <ul> <li>Distance as described in the second expression above</li> <li>RMS where the sum is divided by the number of dimensions <span class="math-container">$\text{count}(i)$</span></li> <li>Just the sum of squared difference by itself</li> </ul> <p>Cross entropy is an extension of Claude Shannon's information theory concepts based on the work of Bohr, Boltzmann, Gibbs, Maxwell, von Neumann, Frisch, Fermi, and others who were interested in quanta and the thermodynamic concept of entropy as a universal principle running through mater, energy, and knowledge.</p> <p><span class="math-container">$$ S = k_B \log{\Omega} \\ H(X) = - \sum_i p(x_i) \, \log_2{\, p(x_i)} \\ H(p, \, q) = -\sum_{x \in \mathcal{X}} \, p(x) \, \log_2{\, q(x)} $$</span></p> <p>In this progression of theory, we begin with a fundamental postulate in quantum physics, where <span class="math-container">$k_B$</span> is Boltzmann's constant and <span class="math-container">$\Omega$</span> are the number of microstates for the quanta. The next relation is Shannon's adaptation for information, where <span class="math-container">$H$</span> is the entropy in bits, thus the <span class="math-container">$\log_2$</span> instead of a natural logarithm. The third relation above expresses cross-entropy in bits for features <span class="math-container">$\mathcal{X}$</span> is based on the Kullback-Leibler divergence. the p-attenuated sum of bits of q-information in .</p> <p>Notice that <span class="math-container">$p$</span> and <span class="math-container">$q$</span> are probabilities, not <span class="math-container">$F$</span> or <span class="math-container">$\mathcal{Y}$</span> values, so one cannot substitute labels and outputs of a network into them and retain the meaning of cross entropy. Therefore level 1 and 2 norms are closely related, but cross-entropy is not a norm; it is the dispersion of one thing Cartesian distance aggregation scheme like them. Cross-entropy is remotely related but is statistically more sophisticated. To produce a cross-entropy loss function of form</p> <p><span class="math-container">$$ {||F-\mathcal{Y}||}_H = \mathcal{P}(F, y) \; \text{,} $$</span></p> <p>one must derive the probabilistic function <span class="math-container">$\mathcal{P}$</span> that represents the cross entropy for two distributions in some way that is theoretically sound on the basis of both information theory and convergence resource conservation. It is not clear that the interpretation of cross entropy in the context of gradient descent and back propagation has caught up with the concepts of entropy in quantum theory. That's an area needing further research and deeper theoretical consideration.</p> <p>In the question, the cross-entropy expression is not properly characterized, most evident in the fact that the expression is independent of the labels <span class="math-container">$\mathcal{Y}$</span>, which would be fine if for unsupervised learning except that no other basis for evaluation is represented in the expression. For the term cross-entropy to be valid, the basis for evaluation must include two distributions, a target one and one that represents the current state of learning.</p> <p>The derivatives of the three norms (assuming the cross entropy is properly characterized) can be studied for the case of <span class="math-container">$\ell$</span> ReLU layers by generalizing the chain rule (from differential calculus) as applied to ReLU and the loss function developed by applying each of the three norms to aggregate measures of disparity from optimal.</p> <p>Regarding the inference in sub-question (1) nothing of particular value can be assumed about the Jacobians of level 2 norms from level 1 norms, both with respect to parameters <span class="math-container">$P$</span> or vice versa, except the retention of sign. This is because we cannot determine much about the correlation between the output channels of the network.</p> <p>There is no doubt, regarding sub-question (2), that some constraint, set of constraints, stochastic distribution applied to initialization, hyper-parameter settings, or data set features, labels, or number of examples have implications for the reliability and accuracy of convergence. The PAC (probably approximately correct) learning framework is one system of theory that approaches this question with mathematical rigor. One of its practical uses, among others, is to derive inequalities that predict feasibility in some cases and produce more lucid approaches to learning system projects.</p>
https://ai.stackexchange.com/questions/10025/comparing-and-studying-loss-functions
Question: <p>I'm training a Tensorflow model that receives an image and segments the image into foreground and background. That is, if the input image is <code>w x h x 3</code>, then the neural network outputs a <code>w x h x 1</code> image of <code>0</code>'s and <code>1</code>'s, where <code>0</code> represents background and <code>1</code> represents foreground.</p> <p>I've computed that about 75% of the true mask is background, so the neural network simply trains a model that outputs all <code>0</code>'s and gets a 75% accuracy.</p> <p>To solve this, I'm thinking of implementing a custom loss function that checks if there are more than a certain percentage of <code>0</code>'s, and if so, to add a very large number to the loss to disincentivize the all <code>0</code>'s strategy.</p> <p>The issue is that this loss function becomes non-differentiable.</p> <p>Where should I go from here?</p> Answer: <p>The background being an unbalance class is a well known problem in image segmentation. Before digging into custom losses you should take a look to existing ones that address this specific issue like the <a href="https://pycad.co/the-difference-between-dice-and-dice-loss/" rel="nofollow noreferrer">Dice Loss</a> or <a href="https://medium.com/swlh/understanding-focal-loss-for-pixel-level-classification-in-convolutional-neural-networks-720f19f431b1" rel="nofollow noreferrer">Focal Loss</a>, the latter being more tunable having a extra hyper parameter that can be optimized. You can easily find on github tensorflow implementations of both.<br /> For a more detailed comparison and reference to other similar losses you can also check this <a href="https://arxiv.org/pdf/2006.14822.pdf" rel="nofollow noreferrer">paper</a>.</p>
https://ai.stackexchange.com/questions/33924/custom-tensorflow-loss-function-that-disincentivizes-all-black-pixels
Question: <p>I have two convex, smooth loss functions to minimise. During the training (a very simple model) using batch SGD (with tuned optimal learning rate for each loss function), I observe that the (log) loss curve of the loss 2 converges much faster and is much more smooth than that of the loss 2, as shown in the figure.</p> <p>What can I say more about the properties of the two loss functions, for example in terms of smoothness, convexity, etc?</p> <p><a href="https://i.sstatic.net/vjD9R.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vjD9R.jpg" alt="enter image description here"></a></p> Answer:
https://ai.stackexchange.com/questions/17376/deduce-properties-of-the-loss-functions-from-the-training-loss-curves
Question: <p>I am looking at a problem which can be distilled as follows: I have a phenomenon which can be modeled as a probability density function which is "messy" in that it sums to unity over its support but is somewhat jagged and spiky, and does not correspond to any particular textbook function. It takes considerable amounts of time to generate these experimental density functions, along with conditional data for machine learning, but I have them. I also have a crude model which runs quickly but performs poorly, i.e., generates poor quality density functions.</p> <p>I would like to train a neural network to transform the crude estimated pdfs to something closer to the experimentally generated pdfs, if possible.</p> <p>To investigate this, I've further reduced this to the most toy-like toy problem I can think of: Feeding a narrow, smooth (relatively narrow) normal curve into a 1D convolutional neural network, and trying to transform it to a similar narrow curve with a different mean. Both input and output have fine enough support (101 points) to be considered as a smooth pdf.</p> <p>Here is the crux of the problem I think I have: <em>I do not know what a good loss function is for this problem.</em></p> <p>L1, L2 and similar losses are useless, given that once the non-zero parts of the pdfs are non-overlapping, it doesn't matter how far apart the means are, the loss remains the same. </p> <p>I have been experimenting with <a href="https://www.kernel-operations.io/geomloss/api/pytorch-api.html" rel="nofollow noreferrer">Sinkhorn approximations</a> to optimal transport, to properly capture the intuition of "distance" but somewhat surprisingly these have not been helpful either. I think part of the problem may be an (unavoidable?) numerical stability issue related to the support, but I would not stake hard money on that assumption. </p> <p>(If support is at percentiles on the [0,1] it is quite instructive (and dismaying) to look at the sinkhorn loss for normal functions with the mean directly on a point of support, vs normal functions with the mean directly between two points of support.)</p> <p>For a problem in this vein, are there any recommended loss functions (preferably supported by or easily implement in PyTorch) which might work better?</p> Answer:
https://ai.stackexchange.com/questions/13251/which-loss-functions-for-transforming-a-density-function-to-another-density-func
Question: <p>I am training Deep Learning models to predict the Remaining Useful Life (RUL) of certain devices. The RUL is an estimate of the time remaining until the device is expected to fail. Accurate predictions are especially critical when the RUL is low, as you have little time of reaction to plan maintenance or mitigate potential damages.</p> <p>One limitation of traditional loss functions is that they penalize the magnitude of the prediction error uniformly, regardless of the actual RUL value. For example, the cases <span class="math-container">$(y,\hat y) = (90, 100)$</span> and <span class="math-container">$(y,\hat y) = (0, 10)$</span> would both result in an identical Mean Absolute Error (MAE) of 10. However, the latter case is far more critical and should be penalized more heavily.</p> <p>To address this, I attempted to use the relative error as a loss function:</p> <p><span class="math-container">$$L=\frac{\mathrm{abs}(y-\hat{y})}{y+\epsilon},$$</span></p> <p>where <span class="math-container">$\epsilon &gt; 0$</span> is a small value to avoid division by zero. Despite this modification, the results were not satisfactory, and the model did not perform as expected.</p> <p>Therefore, are there more effective ways to design a loss function that emphasizes errors at low RUL values?</p> <p>(I am posting this question also <a href="https://stats.stackexchange.com/q/659013/427964">here</a>)</p> Answer: <p>Taking the logarithm of the RUL is a possibility. That puts the interpretation in terms of percent. Then missing by one at a low value is a large percentage miss, while missing by one at a high value is a small percentage miss that will not be penalized as severely by square loss or absolute loss.</p> <p>Note that this means taking the logarithm of the data through a command like <code>y_log = np.log(y)</code> and using <code>y_log</code> as the outcome/dependent variable in your model, not relying on a particular activation function in the output node.</p>
https://ai.stackexchange.com/questions/47698/loss-function-that-penalizes-errors-more-at-low-values
Question: <p>I am working on a segmentation of MRI images of the thigh. I am trying to segment the fascia, there is a slight imbalance between the background and the mask. I have about 1400 images from 30 patients for training and 200 for validation. I am working with keras. The loss function is combination of weighted cross entropy and dice loss (smooth factor of dice loss = 2)</p> <pre><code>def combo_loss(y_true, y_pred,alpha=0.6, beta=0.6): # beta before 0.4 return alpha*tf.nn.weighted_cross_entropy_with_logits(y_true, y_pred, pos_weight=beta)+((1-alpha)*dice_coefficient_loss(y_true, y_pred)) </code></pre> <p>When I use a value alpha greater thatn 0.5 (the weighted cross entropy) the loss rapidly decreases during the first epoch. Afterwards if slowly decreases in a linear manner. <a href="https://i.sstatic.net/Zsy2y.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Zsy2y.png" alt="Alpha = 0.6" /></a> Why is this happening? What would be a good approach reasonable approach to choose the values of alpha and beta?</p> Answer:
https://ai.stackexchange.com/questions/24674/loss-function-decays-linearly-in-segmentation-mri-fascia
Question: <p>I have a rather large ML framework that takes multiple conditional probability terms that are computed via classifiers/neural networks. This arbitrary loss function is computed via a function:</p> <pre><code>loss_value = arbitrary_loss(probability1, probability2, ..., P(Y|Z)) </code></pre> <p>I wish to have an <strong>end-to-end framework</strong> that computes everything and trains everything together. So I do not want to have an independently trained classifier. Say at some point I develop some intermediate values (embeddings) Z from the input samples X. I wish to model the conditional probability P(Y|Z) via an MLP softmax layer.</p> <p>This term P(Y|Z) is then estimated and plugged into the final loss which is the sum and product of other probabilities.</p> <pre><code>P(Y|Z) = MLP(input_Z) #probability given input Z over labels </code></pre> <p>My issue is that if I simply take the value of the softmax layer to estimate this probability and plug it in, <strong>at no point are the true labels taken into account for a supervised machine learning problem.</strong></p> <p>How can I fix this without modifying the final loss function?</p> <p>TLDR: I need a probability term P(Y|Z) modeled via an MLP softmax layer to be used in a complex arbitrary loss function. How do i ensure this term is accurate via the true label values, so that it can be used in the final loss?</p> Answer: <p>your question is rather vague. A trained classifier should already estimate conditional probability of Y given input Z.</p> <p>if your question is how to train such a classifier the answer is via CrossEntropy loss. so you have the output probability from your (untrained) classifier network and also the grountruth. CrossEntropy(prediction,grountruth) would be your loss. Here you can find more explanation <a href="https://medium.com/swlh/cross-entropy-loss-in-pytorch-c010faf97bab" rel="nofollow noreferrer">https://medium.com/swlh/cross-entropy-loss-in-pytorch-c010faf97bab</a></p> <p>if you have a different question please edit your question.</p>
https://ai.stackexchange.com/questions/46182/using-conditional-probability-as-an-estimate-in-a-loss-function
Question: <p>I am reading article <a href="https://allenai.org/paper-appendix/emnlp2017-wt/" rel="nofollow noreferrer">https://allenai.org/paper-appendix/emnlp2017-wt/</a> <a href="http://ai2-website.s3.amazonaws.com/publications/wikitables.pdf" rel="nofollow noreferrer">http://ai2-website.s3.amazonaws.com/publications/wikitables.pdf</a> about training neural network and the loss function is mentioned on page 6 chapter 3.4 - this loss function <code>O(theta)</code> is expressed as marginal loglikelihood objective function. I simply does not understand this. The neural network generates logical expression (query) from some question in natural language. The network is trained using question-answer pairs. One could expect that simple sum of correct-1/incorrect=0 result could be good loss function. But there is strange expression that involves <code>P(l|qi, Ti; theta)</code> that is not mentioned in the article. What is meant by this <code>P</code> function? As I understand, then many logical forms <code>l</code> are generated externally for some question <code>qi</code>. But further I can not understand this. The mentioned article largely builds on other article <a href="http://www.aclweb.org/anthology/P16-1003" rel="nofollow noreferrer">http://www.aclweb.org/anthology/P16-1003</a> from which it borrows some terms and ideas.</p> <p>It is said that <code>l</code> is treated as latent variable and <code>P</code> seems to be some kind of probability. Of course, we should assign the greated probability to the right logical form <code>l</code>, but where can I find this assignment. Does training/supervision data should contain this probability function for training/supervision data?</p> Answer: <p>I cannot answer your question but I am stuck in a similar rabbit hole so hopefully these references can help you.</p> <p>The loss function you are describing would be 0-1 loss. However, 0 would be the if our output matches and 1 would be if it does not. This function is not smooth and not convex. Thus we often replace it with a surrogate loss function such as log likelihood.</p> <p>You can read more about surrogate loss function on pg 269 of Deep Learning by Ian Goodfellow available here: <a href="https://www.deeplearningbook.org/" rel="nofollow noreferrer">https://www.deeplearningbook.org/</a></p> <p>or here : <a href="https://en.wikipedia.org/wiki/Loss_functions_for_classification" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Loss_functions_for_classification</a></p> <p>I did not have time to read the article, but the reason that you are seeing a probability is that they are using a Bayesian framework for neural networks. This was first described in <em>A Practical Bayesian Framework for Backpropagation networks</em> by McKay 1992.</p> <p>It is explained very well in a video series by Hinton on youtube here: <a href="https://www.youtube.com/watch?v=YcwZFNd3UvI" rel="nofollow noreferrer">https://www.youtube.com/watch?v=YcwZFNd3UvI</a></p> <p>Hopefully these references help you I wish I could explain in greater detail.</p>
https://ai.stackexchange.com/questions/8487/how-to-understand-marginal-loglikelihood-objective-function-as-loss-function-ex
Question: <p>I am training a deep learning model, the loss function of which is of the form</p> <p><span class="math-container">$$ \cal{L} = \cal{L_1} + \cal{L_2} $$</span></p> <p>where <span class="math-container">$\cal{L_1}$</span> and <span class="math-container">$\cal{L_2}$</span> are of very different orders. WLOG, let's assume the order of <span class="math-container">$\cal{L_1}$</span> is much higher than the order of <span class="math-container">$\cal{L_2}$</span>.</p> <p>During the first several epochs of training, the model will attempt to minimize <span class="math-container">$\cal{L_1}$</span> largely. However, after a certain number of epochs, the value of <span class="math-container">$\cal{L_1}$</span> will converge.</p> <p>My question is, what will happen now? Specifically, I have three questions:</p> <ul> <li><p>Does the convergence of <span class="math-container">$\cal{L_1}$</span> imply the convergence of <span class="math-container">$\cal{L}$</span>, which means the training is over and the loss function behaved as if it was essentially <span class="math-container">$\cal{L} = \cal{L_1}$</span>?</p> </li> <li><p>Since <span class="math-container">$\cal{L_1}$</span> has now converged, does that imply <span class="math-container">$\frac{\partial{\cal{L_1}}}{\partial{\theta}} \approx 0$</span>? (where <span class="math-container">$\theta$</span> are the model parameters)</p> </li> <li><p>If the above point is true, then since the model parameters are updated based on <span class="math-container">$\frac{\partial{\cal{L}}}{\partial \theta}$</span>, does that imply that the model will now start minimizing <span class="math-container">$\cal{L_2}$</span> (since <span class="math-container">$\frac{\partial{\cal{L}}}{\partial \theta} \approx \frac{\partial \cal{L_2}}{\partial \theta}$</span>)?</p> </li> </ul> Answer: <ol> <li>not generally, consider a case where <span class="math-container">$L_2 = 1/L_1$</span>, if one converges to 0, the other one diverges</li> <li>Yes, that's the usual definition of convergence, though the &quot;<span class="math-container">$\approx$</span>&quot; is not really well defined usually</li> <li>exactly, however, after one update, most likely you will have that <span class="math-container">$\frac{dL_1}{d\theta}$</span> won't be 0 anymore</li> </ol>
https://ai.stackexchange.com/questions/43522/impact-of-scaling-in-loss-terms-when-loss-function-is-a-composition-of-multiple
Question: <p>I'm trying to train a neural net to choose a subset from some list of objects. The input is a list of objects <span class="math-container">$(a,b,c,d,e,f)$</span> and for each list of objects the label is a list composed of 0/1 - 1 for every object that is in the subset, for example <span class="math-container">$(1,1,0,1,0,1)$</span> represents choosing <span class="math-container">$a,b,d,f$</span>. I thought about using MSE loss to train the net but that seemed like a naive approach, is there some better loss function to use in this case?</p> Answer: <p>The choice of the loss function depends primarily on the type of task you're tackling: classification or regression. Your problem is clearly a classification one since you have classes to which a given input can either belong or not. More specifically, what you're trying to do is multi-label classification, which is different from multi-class classification. The difference is important to stress out and it consists in the format of the target labels.</p> <pre><code># Multi-class --&gt; one-hot encoded labels, only 1 label is correct [1,0,0], [0,1,0], [0,0,1] # Multi-label --&gt; multiple labels can be correct [1,0,0], [1,1,0], [1,1,1], [0,1,0], [0,1,1], [0,0,1] </code></pre> <p>MSE is used when continuous values are predicted for some given inputs, therefore it belongs to the loss functions suitable for regression and it should not be used for your problem.</p> <p>Two loss functions that you could apply are <em><strong>Categorical Cross Entropy</strong></em> or <em><strong>Binary Cross Entropy</strong></em>. Despite being both based on cross-entropy, there is an important difference between them, consisting of the activation function they require.</p> <blockquote> <p><em><strong>Binary Cross Entropy</strong></em></p> </blockquote> <p><span class="math-container">$$L(y, \hat{y})=-\frac{1}{N} \sum_{i=0}^{N}\left(y * \log \left(\hat{y}_{i}\right)+(1-y) * \log \left(1-\hat{y}_{i}\right)\right)$$</span></p> <p>Despite the name that suggests this loss should be used only for binary classification, this is not strictly true and actually, this is the loss function that conceptually is best suited for multi-label tasks.</p> <p>Let's start with the binary classification case. We have a model that returns a single output score, to which the <em>sigmoid</em> function is applied in order to constrain the value between 0 and 1. Since we have a single score, the resulting value can be interpreted as a probability of belonging to one of the two classes, and the probability of being to the other class can be computed as 1 - value.</p> <p>What if we have multiple output scores, for example, 3 nodes for 3 classes? In this case, we still could apply the sigmoid function, ending up with three scores between 0 and 1.</p> <p><a href="https://i.sstatic.net/4Acyy.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4Acyy.jpg" alt="enter image description here" /></a></p> <p>The important aspect to capture is that since the sigmoid treat each output node independently, the 3 scores would not sum up to 1, so they will represent 3 different probability distributions rather than a unique one. This means that each score after the sigmoid represents a distinct probability of belonging to that specific class. In the example above, for example, the prediction would be true for the two labels with a score higher than 0.5 and false for the remaining label. This also means that 3 different loss have to be computed, one for each possible output. In practice, what you'll be doing is to solve n binary classification problems where n is the number of possible labels.</p> <blockquote> <p><em><strong>Categorical Cross Entropy</strong></em></p> </blockquote> <p><span class="math-container">$$L(y, \hat{y})=-\sum_{j=0}^{M} \sum_{i=0}^{N}\left(y_{i j} * \log \left(\hat{y}_{i j}\right)\right)$$</span></p> <p>In categorical cross-entropy we apply the <em>softmax</em> function to the output scores of our model, to constrain them between 0 and 1 and to turn them into a probability distribution (they all sum to 1). The important thing to notice is that in this case, we end up with a unique distribution because, unlike the sigmoid function, the softmax consider all output scores together (they are summed in the denominator).</p> <p><a href="https://i.sstatic.net/Zbnvr.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Zbnvr.jpg" alt="enter image description here" /></a></p> <p>This implies that categorical cross-entropy is best suited for multi-class tasks, in which we end up with a single true prediction for each input instance. Nevertheless, this loss can also be applied also for multi-label tasks, as done in this <a href="https://research.fb.com/wp-content/uploads/2018/05/exploring_the_limits_of_weakly_supervised_pretraining.pdf?" rel="nofollow noreferrer">paper</a>. To do so, the authors turned each target vector into a uniform probability distribution, which means that the values of the true labels are not 1 but 1/k, with k being the total number of true labels.</p> <pre><code># Example of target vector tuned into uniform probability distribution [0, 1, 1] --&gt; [0, .5, .5] [1, 1, 1] --&gt; [.33, .33, .33] </code></pre> <p>Note also that in the above-mentioned paper the authors found that categorical cross-entropy outperformed binary cross-entropy, even this is not a result that holds in general.</p> <p>Lastly, the are other loss that you could try which differ functions rather than cross-entropy, for example:</p> <blockquote> <p><em><strong>Hamming-Loss</strong></em></p> </blockquote> <p>It computes the fraction of wrong predicted labels</p> <p><span class="math-container">$$\frac{1}{|N| \cdot|L|} \sum_{i=1}^{|N|} \sum_{j=1}^{|L|} \operatorname{xor}\left(y_{i, j}, z_{i, j}\right)$$</span></p> <blockquote> <p><em><strong>Exact Match Ratio</strong></em></p> </blockquote> <p>Only predictions for which all target labels were correctly classified are considered correct.</p> <p><span class="math-container">$$ExactMatchRatio,\space M R=\frac{1}{n} \sum_{i=1}^{n} I\left(Y_{i}=Z_{i}\right)$$</span></p>
https://ai.stackexchange.com/questions/20531/loss-function-for-choosing-a-subset-of-objects
Question: <p>How do I interpret a large variance of a loss function?</p> <p>I am currently training a transformer network (using the software, but not the model from GPT-2) from scratch and my loss function looks like this: <a href="https://i.sstatic.net/LvhRs.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LvhRs.png" alt="a plot of the loss function"></a></p> <p>The green dots are the loss averaged over 100 epochs and the purple dots are the loss for each epoch.</p> <p>(You can ignore the missing part, I just did not save the loss values for these epochs)</p> <p>Is such a large variance a bad sign? And what are my options for tuning to get it to converge faster? Is the network to large or too small for my training data? Should I have a look at batch size?</p> <ul> <li>Learning rate parameter: 2.5e-4</li> <li>Training data size: 395 MB</li> </ul> <p>GPT-2 parameters:</p> <pre><code>{ "n_vocab": 50000, "n_ctx": 1024, "n_embd": 768, "n_head": 12, "n_layer": 12 } </code></pre> Answer:
https://ai.stackexchange.com/questions/13862/how-to-interpret-a-large-variance-of-the-loss-function
Question: <p>I am studying logistic regression for binary classification.</p> <p>The loss function used is <strong>cross-entropy</strong>. For a given input <span class="math-container">$x$</span>, if our model outputs <span class="math-container">$\hat{y}$</span> instead of <span class="math-container">$y$</span>, the loss is given by <span class="math-container">$$\text{L}_{\text{CE}}(y,\hat{y}) = -[y \log \hat{y} + (1 - y) (\log{1 - \hat{y}})]$$</span></p> <p>Suppose there are <span class="math-container">$m$</span> such training examples, then the overall total loss function <span class="math-container">$\text{TL}_{\text{CE}}$</span> is given by</p> <p><span class="math-container">$$\text{TL}_{\text{CE}} = \dfrac{1}{m} \sum\limits_{i = 1}^{m} \text{L}_{\text{CE}} (y_i , \hat{y_i}) $$</span></p> <p>It is said that <strong>the loss function is convex</strong>. That is, If I draw a graph between the loss values wrt the corresponding weights then the curve will be convex. The <a href="https://web.stanford.edu/%7Ejurafsky/slp3/5.pdf" rel="nofollow noreferrer">material from textbook</a> did not give any explanation regarding the convex nature of the cross-entropy loss function. You can observe it from the following passage.</p> <blockquote> <p>For logistic regression, <strong>this (cross-entropy) loss function is conveniently convex</strong>. A convex function has just one minimum; there are no local minima to get stuck in, so gradient descent starting from any point is guaranteed to find the minimum. (By contrast, the loss for multi-layer neural networks is non-convex, and gradient descent may get stuck in local minima for neural network training and never find the global optimum.)</p> </blockquote> <p>How did they conclude conveniently that the loss function is convex? Is it by plotting or some other means?</p> Answer: <p>The <span class="math-container">$L_{CE}$</span> that you provided is binary cross-entropy, the factor <span class="math-container">$y$</span> and <span class="math-container">$(1-y)$</span> is because <span class="math-container">$y$</span> is binary <span class="math-container">$({0,1})$</span>, careful with the name next time. The cross-entropy loss should have form:</p> <p><span class="math-container">$$L_{CE}=-\displaystyle\sum_{i=1}^C y_i\log(\hat{y_i})$$</span></p> <p>Where <span class="math-container">$C$</span> is the number of classes. Normally, the <span class="math-container">$y_i$</span> factor only is 1 when <span class="math-container">$i$</span> is the index of the correct class. Therefore, with each class, the function is just:</p> <p><span class="math-container">$$f(x)=-log(x)$$</span></p> <p>Now, to prove this one is convex, we have multiple ways, but my favorite one is computing the derivative and second derivative.</p> <p><span class="math-container">$$\frac{\partial L}{\partial x}=-\frac{1}{x}\Rightarrow \frac{\partial^2 L}{\partial x^2}=\frac{1}{x^2}&gt;0 \text{ for all }x\in(0,1]$$</span></p> <p>This proves that <span class="math-container">$f(x) = -\log(x)$</span> is convex, given that, if the second derivative of a function is positive, then the function is convex (more info and an example <a href="https://www.hec.ca/en/cams/help/topics/The_second_derivative.pdf" rel="nofollow noreferrer">here</a>).</p> <p>For the case of multiple samples, we also need to prove that the sum of a convex function is a convex function.</p> <p>Based on <a href="https://en.wikipedia.org/wiki/Convex_function" rel="nofollow noreferrer">the definition of convex function</a>, a function <span class="math-container">$f:X\rightarrow \mathbb{R}$</span> will be convex if: <span class="math-container">$$f(tx_1+(1-t)x_2) \le tf(x_1) + (1-t)f(x_2)$$</span> where <span class="math-container">$0&lt;t&lt;1$</span> and <span class="math-container">$x_1,x_2\in X$</span>.</p> <p>Now, let's assume <span class="math-container">$h(x) = f(x) + g(x)$</span> where both <span class="math-container">$f$</span> and <span class="math-container">$g$</span> are convex. We have: <span class="math-container">$$f(tx_1+(1-t)x_2) \le tf(x_1) + (1-t)f(x_2)$$</span> <span class="math-container">$$g(tx_1+(1-t)x_2) \le tg(x_1) + (1-t)g(x_2)$$</span> <span class="math-container">$$\Rightarrow f(tx_1+(1-t)x_2) + g(tx_1+(1-t)x_2) \le tf(x_1) + (1-t)f(x_2) + tg(x_1) + (1-t)g(x_2)$$</span> <span class="math-container">$$\Rightarrow f(tx_1+(1-t)x_2) + g(tx_1+(1-t)x_2) \le t(f(x_1)+g(x_1)) + (1-t)(f(x_2)+g(x_2))$$</span> <span class="math-container">$$\Rightarrow h(tx_1+(1-t)x_2) \le th(x_1) + (1-t)h(x_2)$$</span> <span class="math-container">$\Rightarrow h$</span> is the convex function <span class="math-container">$\Rightarrow$</span> the summation of convex functions is a convex function.</p>
https://ai.stackexchange.com/questions/28288/in-logistic-regression-why-is-the-binary-cross-entropy-loss-function-convex
Question: <p>I want to use deep learning to estimate the value of a function based on some data. However, the loss function would be neither convex nor concave. Can I know if it is a big deal in deep learning? Is training a deep network, when loss function is convex, the same as optimizing a convex problem or not? I would be thankful if any paper has addressed this issue. </p> Answer: <p><strong>Optimization</strong></p> <p>In optimization, the loss function (sometimes called the error function) is a function that aggregates the disparity between actual and ideal behavioral states in multiple dimensions and over a sequence of input cases. In re-entrant (reinforced) learning, a feedback scalar or vector acts as a corrective signal that can replace or further aggregate with the loss function and additionally impact the training back-propagation.</p> <p><strong>Convergence</strong></p> <p>In any of these architectures, including systems without NN components but attempt to adapt by converging on an optimal static or moving target behavior, one generality can be made. As the goal state is approached, the probability of successful convergence increases if the size of each incremental estimation decreases. The estimation is nothing more than an informed guess.</p> <p>Decreasing the learning rate as the detected convergence value improves is one strategy being used experimentally if not in production, but that strategy has drawbacks when used alone. Involving the loss function in slowing down as the destination approaches is a best practice.</p> <p><strong>Biology Analogy</strong></p> <p>A biological system of a similar nature is the human subjective experience of pain. As the pain level goes down, the human brain cares less about the pain, therefore the steps taken to reduce it decrease and eventually vanish. Evolution has proven such to be advantageous for the same reason.</p> <p><strong>The Mathematics Involved</strong></p> <p>Maximizing the probability of an unknown function to be learned adequately to perform well is done in NNs by convergence. The term gradient descent is often used to describe the iterative process intended to converge on some ideal characterized by labeled data, a concept built into the network, or some fitness signal. The likelihood of converging on at least a local minima (which may or may not be the global minima) is much higher if the slope decreases as the minima is approached in successive approximation scenarios. This is when <i>d</i><sup>2</sup>E / <i>d</i>t<sup>2</sup> is positive.</p> <p>The geometric idea of convexity is correlated to the calculus concept of the second derivative of a line or surface with respect to time or some other measure of forward progress. In successive approximation, the independent variable that measures forward progress could be time, computing cycles, the index of the training sample, iteration number, or some aggregation of these. The second derivative is the rate of the rate of change.</p> <p>Convergence is more likely if the rate of change decreases as the disparity between what is perceived as optimal behavior and what is the actual current behavior. In other terms, the relationship between risk in making the next adjustment to circuit (NN) behavior should approach zero as proximity to the optimal behavior approaches zero. (If one senses they have worked there way to close proximity of their desired state, it makes no sense to make wild guesses.)</p> <p><strong>An Easy to Visualize Analogy</strong></p> <p>If you drop a rubber ball into a rigid cone, it will take time to reach thermodynamic rest, at the bottom. A lossless ball (considered impossible) will bounce forever. A paraboloid (parabolic in two dimensions like a solar reflector) will produce faster convergence with the same rubber ball because the ball drops in energy (the sum of kinetic and potential energy) with each bounce. The trajectory does not overshoot the bottom nearly as much or as frequently. This analogy is not perfect, but it provides a visual image without a diagram.</p> <p>If you aggregate your disparity between your target trained behavior and the current in-training behavior in a way where the second derivative is negative (concave loss function with respect to distance) on either side of the targeted ideal, convergence is much less likely. In the analogy, the rubber ball is likely to bounce out of the flared cone altogether. A lossless ball will always bounce out eventually.</p> <p>A more provincial analogy is that it would be like trying to catch a baseball with the back of a baseball glove.</p> <p><strong>Concave, Convex, or Zero Second Derivative</strong></p> <p>Whether continuous or discrete, convex functions converge much more frequently and usually with less time and computing resource than concave ones. A second derivative of zero is in the middle. The word linear is actually incorrect for this zero acceleration case. The correct term is first degree polynomial.</p> <p>Sum of squares over the dimensions of the domain (inputs) and over the sequence of input cases will perform well in many cases. If you were to sum the square roots of the absolute value of error instead, your NN will rarely converge at all.</p> <p><strong>Executive Summary</strong></p> <p>The following three things are more likely to be favorable if you find a way to aggregate your disparity between ideal and actual current behaviors in a way where the second derivative is greater than zero.</p> <ul> <li>Reliability of eventual convergence</li> <li>Speed of convergence</li> <li>Response time in the case of re-entrant (reinforced) learning</li> <li>Savings of computing cycles</li> <li>Reduction in the complexity of introspection</li> <li>Conservation of computational memory (RAM or SDD)</li> <li>Conservation of space needed for persistance and archiving</li> <li>Reduction of project cost to the business</li> </ul>
https://ai.stackexchange.com/questions/4271/non-convex-loss-function-in-deep-learning-is-a-big-deal
Question: <p>With reference to the research paper entitled <a href="https://ieeexplore.ieee.org/document/7296633" rel="nofollow noreferrer">Sentiment Embeddings with Applications to Sentiment Analysis</a>, I am trying to implement its sentiment ranking model in Python, for which I am required to optimize the following hinge loss function: </p> <p><span class="math-container">$$\operatorname{loss}_{\text {sRank}}=\sum_{t}^{T} \max \left(0,1-\delta_{s}(t) f_{0}^{\text {rank}}(t)+\delta_{s}(t) f_{1}^{\text {rank}}(t)\right)$$</span></p> <p>Unlike the usual mean square error, I cannot find its gradient to perform backpropagation.</p> <p>How do I calculate the gradient of this loss function?</p> Answer: <p>Hinge loss is difficult to work with when the derivative is needed because the derivative will be a piece-wise function. <code>max</code> has one non-differentiable point in its solution, and thus the derivative has the same. This was a very prominent issue with non-separable cases of SVM (and a good reason to use ridge regression).</p> <p>Here's a slide (Original source from <a href="https://sites.google.com/site/ucsdfall2018cogs118a/calendar-notes" rel="nofollow noreferrer">Zhuowen Tu</a>, apologies for the title typo): <a href="https://i.sstatic.net/hoaGW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hoaGW.png" alt="SVM Hinge Loss equation and derivative"></a></p> <p>Where hinge loss is defined as <code>max(0, 1-v)</code> and <code>v</code> is the decision boundary of the SVM classifier. More can be found on <a href="https://en.wikipedia.org/wiki/Hinge_loss" rel="nofollow noreferrer">the Hinge Loss Wikipedia</a>.</p> <p>As for your equation: you can easily pick out the <code>v</code> of the equation, however without more context of those functions it's hard to say how to derive. Unfortunately I don't have access to the paper and cannot guide you any further...</p>
https://ai.stackexchange.com/questions/8281/how-do-i-calculate-the-gradient-of-the-hinge-loss-function
Question: <p>Suppose I have an image segmentation model with an output of <code>[ 128, 128, 2 ]</code>, segmenting an input image into 2 parts.</p> <p>Commonly, loss functions have the sigmoid or softmax needed to produce a probability distribution in the loss function itself, for example:</p> <pre><code>tf.nn.sigmoid_cross_entropy_with_logits tf.nn.softmax_cross_entropy_with_logits </code></pre> <p>Alternatively, one could include the <code>softmax</code> or <code>sigmoid</code> call in the last layer fo a model:</p> <pre><code>model = tf.keras.Sequential([ # ... tf.keras.layers.Conv2D(2, kernel_size=1, padding=&quot;same&quot;, activation=&quot;softmax&quot;) ]) </code></pre> <p>My question is this: Why could you keep the <code>softmax</code> / <code>sigmoid</code> in the loss function instead of in the last layer of the model?</p> <p>Wouldn't putting it in the last layer of the model ensure that the output of the model is constrained, enabling the model to more effectively learn the boundaries of the given input as smaller gradients would be needed for the model to change its mind on a given pixel?</p> Answer: <p>Mathematically it does not matter at all. The results will be the same. However there is a strong reason to prefer it being in the loss function: numeric stability.</p> <p>Because the loss function knows more information (ie what the loss is), it can compute the softmax and loss together using some tricks to improve numeric stability.</p>
https://ai.stackexchange.com/questions/39648/should-softmax-be-in-the-model-or-in-the-loss-function
Question: <p>I plan to create a neural network using Python, Keras, and TensorFlow. All the tutorials I have seen so far are concerned with image recognition. However, the goal of my program would be to take in 10+ inputs and calculate a binary output (true/false) instead.</p> <p>Which loss function should I use for my task?</p> Answer: <p>There are several loss functions that you can use for binary classification. For example, you could use the <a href="https://en.wikipedia.org/wiki/Cross_entropy" rel="nofollow noreferrer"><strong>binary cross-entropy</strong></a> or the <a href="https://en.wikipedia.org/wiki/Hinge_loss" rel="nofollow noreferrer"><strong>hinge</strong></a> loss functions.</p> <p>See, for example, the tutorials <a href="https://machinelearningmastery.com/binary-classification-tutorial-with-the-keras-deep-learning-library/" rel="nofollow noreferrer">Binary Classification Tutorial with the Keras Deep Learning Library</a> (2016) and <a href="https://machinelearningmastery.com/how-to-choose-loss-functions-when-training-deep-learning-neural-networks/" rel="nofollow noreferrer">How to Choose Loss Functions When Training Deep Learning Neural Networks</a> (2019) by Jason Brownlee. Have also a look at Keras <a href="https://keras.io/losses/" rel="nofollow noreferrer">documentation of its available loss functions</a>.</p>
https://ai.stackexchange.com/questions/13256/which-loss-function-should-i-use-for-binary-classification
Question: <p>In Deep Q Learning algorithm the convergence is generally achieved using smart tricks like the target network and the replay buffer.</p> <p>However there is one thing which is not clear to me. When the Q network is trained through SGD, the loss function is an expectation over all possible states, which is approximated stochastically using samples from the replay buffer. But the replay buffer itself is not constructed from a unique stationary distribution: the behaviour policy used to collect state transitions typically changes during the overall training procedure (it typically becomes more greedy as new data are collected).</p> <p>As a result, we draw sample transitions from the replay buffer hoping to obtain a useful stochastic approximation of some stationary distribution, but those data were not actually drawn from a stationary distribution.</p> <p>Why isn't this an issue for the SGD procedure?</p> Answer: <p>DQN is a off-policy method, this means that you are fine (apart from some variance factor) with sampling data from another distribution</p> <p>However, Replay Buffer have a state distribution that is different from the new policy one, which might create some problem</p> <p>SGD on the other hand, with such method, has the problem of the fact that its convergence guarantees assumes that the samples are IID, which is not true in case of replay buffer (and generally, in most RL scenarios)</p>
https://ai.stackexchange.com/questions/42239/dqn-loss-function-doubt-about-stochastic-approximation
Question: <p>I'm having the following problem: `</p> <p>I'm training a multi-output CNN and using the relative values of the outputs in my loss function. The net is learning well, but as the absolute values of the outputs are not regularized in anyway in the loss function, the values of the outputs keep rising. This causes a situation where the result I need (values of the outputs relative to each other) are quite right, but the huge absolute values produce underflow resulting NaN values at some point of the training. Is there some way to constrain these absolute values (perhaps elsewhere than the loss function?)</p> <p>I'm using a custom loss function implementing a recovery angular error metric, so the loss function is somewhat complex. A weighed mean of the net outputs is fed to this function, so using both the net outputs and the weighed mean would lead to some quite problematic gradient derivation. Would it be maybe possible to constrain the value range of the net outputs in the net structure itself?</p> Answer: <p>You can limit the absolute values of the outputs by "punishing" large values in the loss function. This is done by adding an extra term to the loss function. </p> <p>For example, if your existing loss function is <em>L(yhat, y)</em> where <em>yhat</em> is the output and <em>y</em> the correct value, create a new loss function </p> <p><em>L'(yhat, y) = L(yhat,y) + max(0, ||yhat||<sub>1</sub> - k)</em> </p> <p>When the outputs are "small" the L<sub>1</sub> norm of your output <em>yhat</em> is less than <em>k</em> and imposes no extra loss (keeping everything as before). However once the norm grows above <em>k</em> it starts to impose a loss that guides the training to reduce the absolute values of the outputs values.</p> <p>You can also limit the values in the network itself by selecting a bounded activation function for the output, for example <em>tanh</em> or <em>sigmoid</em>. However, you need to pick an activation function that suits your problem.</p>
https://ai.stackexchange.com/questions/4398/constraining-the-output-value-range-of-a-cnn-independent-of-the-loss-function
Question: <p>I'm using a neural network to solve a multi regression problem because I'm trying to predict continuous values. To be more specific, I'm making a tracking algorithm to track the position of an object, I'm trying to predict two values, the latitude and longitude of an object.</p> <p>Now, to calculate the loss of the model, there are some common functions, like mean squared error or mean absolute error, etc., but I'm wondering if I can use some custom function, like <a href="https://en.wikipedia.org/wiki/Haversine_formula" rel="nofollow noreferrer">this</a>, to calculate the distance between the two longitude and latitude values, and then the loss would be the difference between the real distance (calculated from the real longitude and latitude) and the predicted distance (calculated from the predicted longitude and latitude). These are some thoughts from me, so I'm wondering if such an idea would make sense?</p> <p>Would this work in my case better than using the mean squared error as a loss function?</p> <p>I had another question in mind. In my case, I'm predicting two values (longitude and latitude), but is there a way to transform these two target values to only one value so that my neural network can learn better and faster? If yes, which method should I use? Should I calculate the summation of the two and make that as a new target? Does this make sense?</p> Answer: <p>Using two value and using MSE is probably a better approach. I'd you combine the value to one value, like the case of summation, the network may fits to output 0 on one axis and the value on the other. The method you propose also have the same issue. There are many combination to the real distance, but only one is correct. For a neural network to learn faster, one value will not help it learn faster. Instead, accuracy is often increased if the predicted value is a one hot vector of labels instead of a single value. Hope this can help you.</p>
https://ai.stackexchange.com/questions/16022/when-should-i-create-a-custom-loss-function
Question: <p>I am trying to predict noise (random gaussian) with the help of a neural network. I am implementing a L2 loss (torch.nn.function.mse_loss) for computing the loss function between the prediction distribution and input distribution (random gaussian). Any suggestions on what I may do to correct this?</p> <p><strong>1. For epoch 1 : Train loss 1.0933226346969604</strong></p> <p><a href="https://i.sstatic.net/QRQFT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QRQFT.png" alt="enter image description here" /></a></p> <p><strong>2. For epoch 200 : Train loss 1.000555157661438</strong></p> <p><a href="https://i.sstatic.net/nCm9g.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nCm9g.png" alt="enter image description here" /></a></p> <p><strong>3. For epoch 400 : Train loss: 1.174836277961731</strong></p> <p><a href="https://i.sstatic.net/G1ssU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/G1ssU.png" alt="enter image description here" /></a></p> Answer: <p>Gaussian noise is usually 0-mean, meaning that <em>it cancels out</em> on average especially with a squared loss (e.g. MSE): so your approach won't work.</p> <p>I think that you should instead <em>predict the mean and variance</em> of such noise distribution: in such a way you could handle noises that are not 0-centered too!</p> <p>In practice, I guess you can get inspiration from variational autoencoders. I mean, you set-up a neural net to predict the mean and log-variance. Then the loss function will be the KL divergence between the predicted Gaussian distribution (the one parametrized by mean and <code>exp(log_var)</code>) and the Gaussian prior, which corresponds to the distribution that describes the noise: <span class="math-container">$\mathcal{N}(0, 1)$</span>, in your case.</p> <p>In principle, with such approach you can learn also non-Gaussian noise distributions.</p>
https://ai.stackexchange.com/questions/40482/loss-function-not-able-to-capture-the-maxima-of-probability-distribution
Question: <p>I'm trying to get my toy network to learn a sine wave.</p> <p>I output (via tanh) a number between -1 and 1, and I want the network to minimise the following loss, where <code>self(x)</code> are the predictions.</p> <pre><code>loss = -torch.mean(self(x)*y) </code></pre> <p>This should be equivalent to trading a stock with a sinusoidal price.</p> <p>The issue I'm having is that the network doesn't learn anything. It <em>does</em> work if I change the loss function to be <code>torch.mean((self(x)-y)**2)</code> (MSE), but this isn't what I want. I'm trying to focus the network on 'making a profit', not making a prediction.</p> <p>I think the issue may be related to the convexity of the loss function, but I'm not sure, and I'm not certain how to proceed. I've experimented with differing learning rates, but alas nothing works.</p> <p>What should I be thinking about?</p> <p>Actual code:</p> <pre><code>%load_ext tensorboard import matplotlib.pyplot as plt; plt.rcParams[&quot;figure.figsize&quot;] = (30,8) import torch;from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F;import pytorch_lightning as pl from torch import nn, tensor def piecewise(x): return 2*(x&gt;0)-1 class TsDs(torch.utils.data.Dataset): def __init__(self, s, l=5): super().__init__();self.l,self.s=l,s def __len__(self): return self.s.shape[0] - 1 - self.l def __getitem__(self, i): return self.s[i:i+self.l], torch.log(self.s[i+self.l+1]/self.s[i+self.l]) def plt(self): plt.plot(self.s) class TsDm(pl.LightningDataModule): def __init__(self, length=5000, batch_size=1000): super().__init__();self.batch_size=batch_size;self.s = torch.sin(torch.arange(length)*0.2) + 5 + 0*torch.rand(length) def train_dataloader(self): return DataLoader(TsDs(self.s[:3999]), batch_size=self.batch_size, shuffle=True) def val_dataloader(self): return DataLoader(TsDs(self.s[4000:]), batch_size=self.batch_size) dm = TsDm() class MyModel(pl.LightningModule): def __init__(self, learning_rate=0.01): super().__init__();self.learning_rate = learning_rate super().__init__();self.learning_rate = learning_rate self.conv1 = nn.Conv1d(1,5,2) self.lin1 = nn.Linear(20,3);self.lin2 = nn.Linear(3,1) # self.network = nn.Sequential(nn.Conv1d(1,5,2),nn.ReLU(),nn.Linear(20,3),nn.ReLU(),nn.Linear(3,1), nn.Tanh()) # self.network = nn.Sequential(nn.Linear(5,5),nn.ReLU(),nn.Linear(5,3),nn.ReLU(),nn.Linear(3,1), nn.Tanh()) def forward(self, x): out = x.unsqueeze(1) out = self.conv1(out) out = out.reshape(-1,20) out = nn.ReLU()(out) out = self.lin1(out) out = nn.ReLU()(out) out = self.lin2(out) return nn.Tanh()(out) def step(self, batch, batch_idx, stage): x, y = batch loss = -torch.mean(self(x)*y) # loss = torch.mean((self(x)-y)**2) print(loss) self.log(&quot;loss&quot;, loss, prog_bar=True) return loss def training_step(self, batch, batch_idx): return self.step(batch, batch_idx, &quot;train&quot;) def validation_step(self, batch, batch_idx): return self.step(batch, batch_idx, &quot;val&quot;) def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=self.learning_rate) #logger = pl.loggers.TensorBoardLogger(save_dir=&quot;/content/&quot;) mm = MyModel(0.1);trainer = pl.Trainer(max_epochs=10) # trainer.tune(mm, dm) trainer.fit(mm, datamodule=dm) # </code></pre> Answer: <p>It doesn't matter that your loss is not convex. As a matter of fact, the loss function of a neural network is in general neither convex nor concave (<a href="https://stats.stackexchange.com/questions/106334/cost-function-of-neural-network-is-non-convex">reference</a>).</p> <p>As ImotVoksim points out, the issue is that the loss function you've defined has nothing to do with the problem you're trying to solve.</p> <p>For example, a stock price of zero is going to give you a loss of zero and hence no gradients at all: the neural network is allowed to output arbitrary values whenever the stock price is zero.</p> <p>You want to &quot;make a profit&quot;. I'm not sure why the MSE is not good in this case: if your neural network outputs the correct price of the stock for the next time period, you can use this information to make the trade which will maximize your profit.</p> <p>Or do you want to predict the price further in the future? In that case you could use an MSE of the form</p> <pre><code>torch.mean((self(x_t)-y_{t+n})**2) </code></pre> <p>where <code>x_t</code> is the input at time period <code>t</code> and <code>y_{t+n}</code> the price of the stock at time period <code>t+n</code>, <code>n</code> a number you choose.</p>
https://ai.stackexchange.com/questions/35850/what-should-i-think-about-when-designing-a-custom-loss-function
Question: <p>Loss functions are used in training neural networks.</p> <p>I am interested in knowing the mathematical properties that are necessary for a loss function to <strong>participate in gradient descent optimization</strong>.</p> <p>I know some <em>possible</em> candidates that may decide whether a function can be a loss function or not. They include</p> <ol> <li>Continuous at every point in <span class="math-container">$\mathbb{R}$</span></li> <li>Differentiable at every point in <span class="math-container">$\mathbb{R}$</span></li> </ol> <p>But, I am not sure whether these two properties are necessary for a function to become a loss function.</p> <p>Are these two properties <strong>necessary</strong>? Are there any <strong>other mathematical properties that are necessary</strong> for a function to become a loss function to participate in gradient descent optimization?</p> <p>Note that this question is not asking for recommended properties for a loss function. Asking only the mandatory properties in a given context.</p> Answer: <p><strong>Summary:</strong> the loss needs to be differentiable, with some caveats.</p> <hr /> <p>I will introduce some notation, which I hope is clear: if not I am happy to clarify.</p> <p>Consider a neural network with parameters <span class="math-container">$\theta \in \mathbb{R}^d$</span>, which is usually a vector of weights and biases. The gradient descent algorithm seeks to find parameters <span class="math-container">$\theta_\mathrm{min}$</span> which minimise the loss function <span class="math-container">$$\mathcal{L} \colon \mathbb{R}^d \to \mathbb{R}.$$</span></p> <hr /> <p>If this seems abstract, suppose <span class="math-container">$f(x; \theta)$</span> is the neural network and <span class="math-container">$S = \{(x_i, y_i)\}_{i = 1}^n$</span> is the training set. In binary classification we could have the loss function</p> <p><span class="math-container">$$\mathcal{L}(\theta) = \sum_{i = 1}^n \mathbb{1} \{f(x_i; \theta) \ne y_i\} $$</span> where <span class="math-container">$\mathbb{1}$</span> is the indicator function which is <span class="math-container">$1$</span> if the condition is satisfied and zero otherwise. I consider the loss function to be a function of the <em>parameters</em> and not the data, which is fixed.</p> <hr /> <p>Gradient descent is performed by the update rule <span class="math-container">$$ \theta_n \leftarrow \theta_{n - 1} - \gamma \nabla \mathcal{L}(\theta_{n - 1}),$$</span> yielding new parameters <span class="math-container">$\theta_n$</span> which should give a smaller loss <span class="math-container">$\mathcal{L}(\theta_n)$</span>. The quantity <span class="math-container">$\gamma$</span> is the familiar <em>learning rate</em>.</p> <p>The gradient descent rule requires the <em>gradient</em> <span class="math-container">$\nabla \mathcal{L}(\theta_{n - 1})$</span> to be defined, so the loss function must be differentiable. In most texts on calculus or mathematical analysis you'll find the result that if a function is differentiable at a point <span class="math-container">$x$</span>, it is also continuous at <span class="math-container">$x$</span>. Obviously there is no hope that we could perform this procedure without knowing the gradient!</p> <p>In principle, differentiability is sufficient to run gradient descent. That said, unless <span class="math-container">$\mathcal{L}$</span> is convex, gradient descent offers no guarantees of convergence to a global minimiser. In practice, neural network loss functions are rarely convex anyway.</p> <p>I have omitted discussion on stochastic gradient descent, but it does not change the requirements for the loss function. There are alternative techniques such as the <a href="https://en.wikipedia.org/wiki/Proximal_gradient_method" rel="nofollow noreferrer">proximal gradient method</a> for non-differentiable functions.</p> <p>An unfortunate technicality I have to mention is that, strictly speaking, if you use the <span class="math-container">$\mathrm{ReLU}$</span> activation function, the neural network function <span class="math-container">$f$</span> becomes non-differentiable. I discuss this further in <a href="https://ai.stackexchange.com/a/28588/44413">this answer</a>. In practice we can assign a value and &quot;pretend&quot; <span class="math-container">$\mathrm{ReLU}$</span> is differentiable everywhere.</p>
https://ai.stackexchange.com/questions/28877/what-are-the-necessary-mathematical-properties-to-be-a-loss-function-in-gradient
Question: <p>The purpose of training neural networks is to minimize a loss function, in this process we usually use gradient descent method.</p> <p>But in Calculus, if we want to find the global minimum of a multivariable function, we usually first calculate the partial derivatives of this function with respect to its variables, and then set these partial derivatives to zeros, and then find the solutions of these equations. Usually we get a bunch of points. We can use the second derivative method(involving Hesse Matrix) to determine whether these points give local minimum values, or we can directly evaluate the values of the function at these points and compare them to find the minimum.</p> <p>So, I'm curious why don't we use this classical method in Calculus to find the global minimum value of the loss function and instead using gradient descent? Is it hard to for computer to find zeros of multivariable equations?</p> Answer: <blockquote> <p>and then set these partial derivatives to zeros</p> </blockquote> <p>but how do you do that? This is analytically possible in very simple cases, such as least squares on linear regression. In that case, it's possible to invert the function and explicitly build the weight matrix and the biases.</p> <p>But in maths, the vast majority of equations is not analytically solvable, and needs iterative approximation methods that lead you to a numerical solution. This is what gradient descent does.</p> <p>To convince yourself of this, I suggest you try: write a simple function representing a neural network with 2 layers, then see if you can do as you say. This will give you a better understanding of why it doesn't work.</p>
https://ai.stackexchange.com/questions/36195/why-do-we-use-gradient-descent-to-minimize-the-loss-function
Question: <p>I have a multi label classification problem, where I was initially using a binary cross entropy loss and my labels are one hot encoded. I found a paper similar to my application and have used contrastive loss function, but I am not sure how to use it in my code. I came across an implementation of supervised contrastive loss, but I didn't understand what are the inputs to the function. One of the input is the labels and the other is 'projection'. What is projection in my case?</p> <pre><code>import torch import torch.nn as nn from math import log class SupervisedContrastiveLoss(nn.Module): def __init__(self, temperature=0.07): &quot;&quot;&quot; Implementation of the loss described in the paper Supervised Contrastive Learning : https://arxiv.org/abs/2004.11362 :param temperature: int &quot;&quot;&quot; super(SupervisedContrastiveLoss, self).__init__() self.temperature = temperature def forward(self, projections, targets): &quot;&quot;&quot; :param projections: torch.Tensor, shape [batch_size, projection_dim] :param targets: torch.Tensor, shape [batch_size] :return: torch.Tensor, scalar &quot;&quot;&quot; device = torch.device(&quot;cuda&quot;) if projections.is_cuda else torch.device(&quot;cpu&quot;) dot_product_tempered = torch.mm(projections, projections.T) / self.temperature # Minus max for numerical stability with exponential. Same done in cross entropy. Epsilon added to avoid log(0) exp_dot_tempered = ( torch.exp(dot_product_tempered - torch.max(dot_product_tempered, dim=1, keepdim=True)[0]) + 1e-5 ) mask_similar_class = (targets.unsqueeze(1).repeat(1, targets.shape[0]) == targets).to(device) mask_anchor_out = (1 - torch.eye(exp_dot_tempered.shape[0])).to(device) mask_combined = mask_similar_class * mask_anchor_out cardinality_per_samples = torch.sum(mask_combined, dim=1) log_prob = -torch.log(exp_dot_tempered / (torch.sum(exp_dot_tempered * mask_anchor_out, dim=1, keepdim=True))) supervised_contrastive_loss_per_sample = torch.sum(log_prob * mask_combined, dim=1) / cardinality_per_samples supervised_contrastive_loss = torch.mean(supervised_contrastive_loss_per_sample) return supervised_contrastive_loss </code></pre> <p>This is the model I have used</p> <pre><code>class CV_CNN_Net(nn.Module): def __init__(self,device): super(CV_CNN_Net, self).__init__() self.device = device self.nn = nn.Sequential( ComplexConv2d(1, 128, kernel_size = (3, 3),stride = (2, 2),padding=(1,1)), ComplexBatchNorm2d(128), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexConv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), ComplexBatchNorm2d(128), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexConv2d(128, 128, kernel_size=(2, 2), stride=(1, 1)), ComplexBatchNorm2d(128), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexConv2d(128, 128, kernel_size=(2, 2), stride=(1, 1)), ComplexBatchNorm2d(128), # ComplexReLU(), C_CSELU(), # ZReLU(), nn.Flatten(), ComplexLinear(4608,2048), ##ComplexLinear(12800,1024), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexDropout(p=0.3,device = self.device), ComplexLinear(2048, 1024), ##ComplexLinear(1024, 512), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexDropout(p=0.3,device = self.device), ComplexLinear(1024, 512), ##ComplexLinear(1024, 512), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexDropout(p=0.3,device = self.device), ComplexLinear(512,20), ##ComplexLinear(512, 181), # ComplexReLU(), C_CSELU(), # ZReLU(), ComplexDropout(p=0.5, device=self.device), ) self.FNN = nn.Sequential( ##nn.Linear(2048, 181 * 181, bias=False), nn.Linear(40, 20, bias=False), nn.Sigmoid() ) #self.output_layer = nn.Linear(2048, 180 * 180) def forward(self, data_train): #print(&quot;Input shape:&quot;, data_train.shape)l Outputs = self.nn(data_train) #print(&quot;Shape before concatenation:&quot;, Outputs.shape) features = torch.cat([Outputs.real,Outputs.imag],dim=1) ##Outputs = self.output_layer(Outputs) ##Outputs = Outputs.view(-1, 180, 180) # Reshape to M x N grid Outputs = self.FNN(features) #Outputs = temperature_scaled_sigmoid(Outputs) ##Outputs = Outputs.view(-1, 181, 181) ## Outputs = Outputs.unsqueeze(0) return Outputs, features </code></pre> <p>I thought features in my code can be used as projection, but I am getting an error during training</p> <blockquote> <p>C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\cuda\Loss.cu:106: block: [0,0,0], thread: [96,0,0] Assertion <code>input_val &gt;= zero &amp;&amp; input_val &lt;= one</code> failed.</p> </blockquote> <p>Can anyone guide me on how to correctly use the supervised contrastive loss? Thank you in advance</p> Answer:
https://ai.stackexchange.com/questions/48047/how-to-use-contrastive-loss-function-for-multi-label-classification
Question: <p>I trained a neural network on the <a href="https://www.unsw.adfa.edu.au/unsw-canberra-cyber/cybersecurity/ADFA-NB15-Datasets/" rel="nofollow noreferrer">UNSW-NB15 dataset</a>, but, during training, I am getting spikes in the loss function. The algorithms see part of this UNSW dataset a single time. The loss function is plotted after every batch.</p> <p><a href="https://i.sstatic.net/yoGv8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yoGv8.png" alt="enter image description here"></a></p> <p>For other datasets, I don't experience this problem. I've tried different optimizers and loss functions, but this problem remains with this dataset.</p> <p>I'm using the <code>fit_generator()</code> function from Keras. Is there anyone experience this problem using Keras with this function? </p> Answer: <p>The spikes could be caused by many reasons: insufficient model capacity, incorrect label, buggy input parsing, ... Finding out the culprit requires some detective work. For instance, you could apply the learned model to the whole train set and manually examine the datapoints which result in the highest loss. Alternatively, you could compare the learning outcomes of different models (both weaker and stronger). </p>
https://ai.stackexchange.com/questions/10764/why-am-i-getting-spikes-in-the-values-of-the-loss-function-during-training
Question: <p>I am trying to build an autoencoder for semi-supervised anomaly detection on an intrusion detection dataset (CICIDS2017). The dataset has data with very wide range (like between 0 and 1+08).</p> <p>I am struggling with choosing a combination of scaler, final layer activation function, and loss function.</p> <p>What did I try:</p> <ol> <li>MinMaxScaler (range 0 to 1) + Sigmoid activation function for output + Binary Cross Entropy Loss. The result: A model does not seem to be learning, loss is very small and stuck quickly, the final ROC-AUC is very low. I suspect that after scaling, most of the data lands in a very narrow space, making it impossible for the model to learn properly.</li> <li>MinMaxScaler (range 0 to 1) + Sigmoid activation function + MSE - similarly, the model does not learn.</li> <li>StandardScaler + LeakyReLU activation function + MSE error - the model is learning for a little bit reducing loss by around 25%, but then it gets stuck.</li> <li>RobustScaler + LeakyReLU activation function + MSE error - huge loss value, no real learning.</li> </ol> <p>I feel like I am missing something obvious, so I would greatly appreciate your suggestions on how to make the learning process work.</p> Model's architecture <pre><code> encoder = nn.Sequential( nn.Linear(78, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 16), nn.ReLU() ) decoder = nn.Sequential( nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 78), nn.LeakyReLU() ) </code></pre> <p>Example features</p> <pre><code> count mean std min 25% 50% 75% max Destination Port 2572640.0 8.522897e+03 1.886345e+04 0.000000e+00 53.000000 80.000000 4.430000e+02 6.553500e+04 Flow Duration 2572640.0 1.625736e+07 3.495376e+07 -1.300000e+01 200.000000 48854.000000 5.225583e+06 1.200000e+08 Total Fwd Packets 2572640.0 1.011604e+01 7.863759e+02 1.000000e+00 2.000000 2.000000 5.000000e+00 2.197590e+05 </code></pre> Answer:
https://ai.stackexchange.com/questions/47443/autoencoder-for-semi-supervised-anomaly-detection-a-choice-of-loss-function-s
Question: <p>I implemented a parallel backpropagation algorithm that uses <span class="math-container">$n$</span> threads. Now every thread gets <span class="math-container">$\dfrac{1}{n}$</span> examples of the training data and updates its instance of the net with it. After every epoch the different threads share their updated weights. For that I simply add the weights of the threads and then divide each weight by the number of threads. The problem now is that the more threads I use the worse the result. For me this means that my way of synchronizing the threads is not as good as it should be.</p> <p>Is there a better way to do it?</p> Answer: <p>After a whole epoch, with multiple update steps, the neural networks in each thread will have diverged in a way where it may not make sense to take means of the weights. Ideally you should be combining data for each update step. In turn that means you will want to avoid making updates on every example, because the overhead of starting, stopping and combining the threads may lose most of the benefits.</p> <p>It is common in neural networks to use mini-batches (larger than 1, smaller than the whole dataset), to get more accurate gradients, and for parallelisation. There is often a sweet spot in terms of learning speed (or sample efficiency) with some size of mini-batch. Each mini-batch calculates gradients for all examples, combines them into a mean gradient, then performs a single weight update step.</p> <p>Use your threads to calculate the gradients for a mini-batch, divided up between the threads, and average the gradients across all threads in order to make a single shared weight update. Using larger mini-batches will make more efficient use of multiple threads, but smaller mini-batches can be beneficial because you get to make more weight updates per epoch.</p>
https://ai.stackexchange.com/questions/30418/parallelize-backpropagation-how-to-synchronize-the-weights-of-each-thread
Question: <p>Assume the gradient updates (both <span class="math-container">$W_t$</span> and <span class="math-container">$W_{t+1}$</span>) and learning rate are known while data <span class="math-container">$X$</span> is unknown, is it possible to deduce the loss <span class="math-container">$L$</span> used in backprop algorithm that gave rise to the gradient update <span class="math-container">$W_{t+1} - W_{t}$</span>? If not, is it possible to verify if a given loss is the one we are looking for (in other words is the loss that gave rise to a known gradient update unique, assume we know the model architecture)?</p> Answer: <p>First, there is no way you could recover the exact loss. At best you could recover the loss up to a constant factor, because the gradient is only giving information on the slope on the loss and not the actual loss values.</p> <p>If we make assumptions like a standard model architecture, and we have access to the model architecture in addition to the weight values, then it <em>might</em> be possible to recover the loss up to a constant factor. Assuming the (scalar) loss depends only on the output layer, and assuming the weights are updated with vanilla SGD, first we have an eqn like <span class="math-container">\begin{align*} \frac{1}{\alpha}(W_{t+1} - W_t) = \dfrac{\partial f}{\partial x_n}\Big(\dfrac{\partial x_n}{\partial W_t} + \dfrac{\partial x_n}{\partial x_{n-1}}\dfrac{\partial x_{n-1}}{\partial W_t} + \ldots \Big) \end{align*}</span> where <span class="math-container">$\alpha$</span> is the learning rate, <span class="math-container">$f$</span> is the loss function, <span class="math-container">$x_i$</span> are the units of the <span class="math-container">$i$</span>-th layer (<span class="math-container">$x_n$</span> is output, <span class="math-container">$x_0$</span> is input). the LHS is what you know the gradient was and the RHS is the definition of the gradient (based on backprop). In the RHS, the unknowns are the partial derivatives <span class="math-container">$\frac{\partial f}{\partial x_n}$</span>, which has as many unknowns as dimension of the output layer. This is an over-determined system, because there are only <span class="math-container">$\text{dim}(x_n)$</span> unknowns and <span class="math-container">$\dim(W)$</span> equations. Normally this would then have no solution, but in this case, we know there actually are some loss partial derivatives <span class="math-container">$\partial f / \partial x_n$</span> which should satisfy this.</p> <p>But this doesn't give you the actual function f. You just get the partial derivatives at <span class="math-container">$x_n$</span>. Then if you wanted to try to recover <span class="math-container">$f$</span> (again, only up to a constant factor), you would need a way to actually evaluate various different <span class="math-container">$x_n$</span>. Then you can &quot;recover&quot; <span class="math-container">$f$</span> (up to a constant factor) by integrating <span class="math-container">$\partial f / \partial x_n$</span> over all possible values of <span class="math-container">$x_n$</span>.</p>
https://ai.stackexchange.com/questions/38308/is-it-possible-to-reverse-engineer-out-the-loss-based-on-weights-update-when-dat
Question: <p>I have a neural network that is being trained with a changing cost function. Could I use backpropagation at all? If yes, how would I do this?</p> Answer: <p>There is nothing wrong with changing your cost/loss function after every step while training a neural network. For example, this paper looks at a weight decay scheduler (which changes the weight regularization at every step): <a href="https://arxiv.org/abs/2006.08643" rel="nofollow noreferrer">https://arxiv.org/abs/2006.08643</a>.</p>
https://ai.stackexchange.com/questions/40059/how-would-i-use-backpropagation-with-a-changing-cost-function
Question: <p>I am reading about backpropagation for fully connected neural networks and I found a very interesting <a href="https://www.jeremyjordan.me/neural-networks-training/" rel="nofollow noreferrer">article</a> by Jeremy Jordan. It explains the process from start to finish. There is a section though that confused me a bit. The partial derivative of the cost function (MSE) with regard to the <span class="math-container">$\theta_{jk}^{(2)}$</span> weights is:</p> <p><span class="math-container">$$\frac{\partial J(\theta)}{\partial \theta_{jk}^{(2)}} = \left( \frac{\partial J(\theta)}{\partial a_j^{(3)}}\right) \left( \frac{\partial a_j^{(3)}}{\partial z_j^{(3)}}\right) \left(\frac{\partial z_j^{(3)}}{\partial \theta_{jk}^{(2)}} \right) \tag{1}$$</span></p> <p>The article defines the next equation as the &quot;error&quot; term. The equation <span class="math-container">$eq:2$</span> is the combination of the first two partials in the chain rule:</p> <p><span class="math-container">$$ \delta_i^{(3)} = \frac {1}{m} (y_i - a_i^{(3)}) f^{'}(a^{(3)}) \tag{2}$$</span></p> <p>Where:</p> <ul> <li><span class="math-container">$ i: $</span> The index of the neuron in the layer</li> <li><span class="math-container">$ ^{(3)}: $</span> Denotes the layer (in this case 3 is the output layer)</li> <li><span class="math-container">$ z_i: $</span> The weighted sum of the inputs of the <span class="math-container">$i_{th}$</span> neuron</li> <li><span class="math-container">$ m: $</span> The number of training samples</li> <li><span class="math-container">$ y_i: $</span> The expected value of the <span class="math-container">$ i_{th} $</span> neuron</li> <li><span class="math-container">$ a_i: $</span> The predicted value of the <span class="math-container">$ i_{th} $</span> neuron</li> <li><span class="math-container">$ f^{'}: $</span> The derivative of the activation function</li> </ul> <p>So a few lines after the definition above the article states:</p> <blockquote> <p><span class="math-container">$ \delta^{(3)} $</span> is a vector of length j where j is equal to the number of output neurons <span class="math-container">$$ \delta^{(3)} = \begin{bmatrix} y_1 - a_1^{(3)} \newline y_2 - a_2^{(3)} \newline \cdots \newline y_j - a_j^{(3)} \newline \end{bmatrix} f^{'}(a^{(3)}) \tag{3} $$</span></p> </blockquote> <p>Q1. I strongly suspect that the <span class="math-container">$ f^{'}(a^{(3)}) $</span> is a vector of length <span class="math-container">$j$</span> and not a scalar. Basically, it is a vector containing the derivative of the activation function for every neuron of the output layer. How is it possible in <span class="math-container">$eq:3$</span> to multiply it with another vector and still get a vector and not a <span class="math-container">$j\ x\ j$</span> matrix? Is the multiplication elementwise?</p> <p>Q2. How is the <span class="math-container">$ f^{'}(a^{(3)}) $</span> calculated for every neuron for multiple training samples? From what I understand, while training with batches I would have to average the <span class="math-container">$ (y_i - a_i^{(3)}) $</span> term for the whole batch for every neuron. So in fact the term <span class="math-container">$ (y_i - a_i^{(3)}) $</span> is the sum for the whole batch and that's why the <span class="math-container">$ \frac {1}{m} $</span> is present. Does that apply to the derivative too? Meaning do I have to calculate the average of the derivative for the whole batch for each neuron?</p> <p>Q3. What does <span class="math-container">$ f^{'}(a^{(3)}) $</span> actually mean? Is this the derivative of the activation function evaluated with the values of the <span class="math-container">$a_i^{(3)}$</span> outputs? Or is it the derivative of the activation function evaluated with the values of the weighted sum <span class="math-container">$ z_i $</span> that is actually passed through the activation function to produce the <span class="math-container">$a_i^{(3)} = f(z_i)$</span> output? And if the second would I have to keep track of the average of the <span class="math-container">$z_i$</span> for each neuron in order to obtain the average of the <span class="math-container">$ f^{'} $</span></p> Answer: <p>The author is rather free with changing from row to column format. The main philosophy or framework seems to be to implement the directions of &quot;forward&quot; evaluation and &quot;backwards&quot; gradient differentiation in the left-right direction, in diagrams as well as in formulas.</p> <p>However, this philosophy is broken several times, for instance in writing <span class="math-container">$a=f(z)$</span> instead of <span class="math-container">$f(z)=a$</span>, or in using weight matrices that are indexed for matrix-vector multiplication, that is, the usual right-to-left direction <span class="math-container">$(z^{(3)})^T=\theta^{(2)} (a^{(2)})^T$</span>, which following the philosophy should be written as <span class="math-container">$a^{(2)}(\theta^{(2)})^T=z^{(3)}$</span>.</p> <p>But then again the philosophy gets reversed in formulas like <span class="math-container">$$ \delta^{(l)} = \delta^{(l + 1)}\,\Theta^{(l)}\,f'\left( a^{(l)} \right) $$</span> which clearly is right-to-left, which suggests that the gradients <span class="math-container">$δ^{(l)}$</span> are row vectors and the argument vectors like <span class="math-container">$a^{(l)}$</span> are column vectors.</p> <p>In short, it's a mess.</p> <hr /> <p>Despite that, your questions have direct answers without relying too much on what directional philosophy is used</p> <p>Q1. <span class="math-container">$f'(a^{(3)})$</span> as used and positioned relative to other vectors and matrices is the diagonal matrix with the entries <span class="math-container">$f'(a_j^{(3)})$</span> on the diagonal. This comes out as component-wise product in matrix-vector or vector-matrix multiplications.</p> <p>Q2. If you were to discuss that, you would need another index in all the formulas indicating the training sample. Such as <span class="math-container">$J(x^{[k]},\theta)$</span> as the residual of the net output to <span class="math-container">$y^{[k]}$</span>. The gradient of the sum <span class="math-container">$\frac1m\sum_{k=1}^mJ(x^{[k]},\theta)$</span> would be the sum of all single gradients that get computed independently of each other. Another interpretation of the factor <span class="math-container">$\frac1m$</span> is that it is the gradient at the top level <span class="math-container">$J$</span> that gets propagated backwards to the gradients of each variable.</p> <p>Q3. Of course some doubt is appropriate. As the activated value is a function of the linear combined input, <span class="math-container">$a^{(3)}=f(z^{(3)})$</span>, so is the derivative <span class="math-container">$\frac{\partial a^{(3)}}{\partial z^{(3)}}=f'(z^{(3)})$</span>. Both must have the same arguments. This is just a typo, perhaps copy-pasted some times.</p> <hr /> <p>I've tried how to consistently implement the left-to-right philosophy, but it is too cumbersome. One would have to use something unfamiliar like some kind of reverse polish notation, so instead of <span class="math-container">$v=\phi(u,w)$</span> one would have to write <span class="math-container">$[u,w:\,\phi]=v$</span> or similar. So it is better to stay with right-to-left consistently, as also the author ended up doing. Thus <span class="math-container">$x,z,a$</span> are column vectors, gradients (against the tradition in differential calculus) are row vectors. In algorithmic differentiation it is one tradition to denote tangent vectors for forward differentiation with a dot, <span class="math-container">$\dot x, \dot z,\dot a$</span>, and gradients that get pushed back with a bar, so <span class="math-container">$\bar x,\bar z=\delta, \bar a$</span>.</p> <p>The construction principle for gradient propagation is that if <span class="math-container">$v=\phi(u,w)$</span>, then the relation of tangents pushed forward to the level of before and after the operation <span class="math-container">$\phi$</span> and gradients pushed back to that stage satisfy <span class="math-container">$$ \bar v\dot v=\bar u\dot u+\bar w\dot w. $$</span> Inserting <span class="math-container">$\dot v=\phi_{,u}\dot u+\phi_{,w}\dot w$</span> results in <span class="math-container">$$ \bar v\phi_{,u}\dot u+\bar v\phi_{,w}\dot w=\bar u\dot u+\bar w\dot w. $$</span> Comparing both sides gives <span class="math-container">$\bar u=\bar v\phi_{,u}$</span>, <span class="math-container">$\bar w=\bar v\phi_{,w}$</span>.</p> <p>In a wider context <span class="math-container">$\bar w$</span> is a linear functional, meaning with scalar value, of <span class="math-container">$\dot w$</span>. So if <span class="math-container">$w$</span> is a matrix, then the linear functional is obtained via the trace, <span class="math-container">${\rm Tr}(\bar w·\dot w)$</span>. So if for instance <span class="math-container">$\phi(u,w)=w·u$</span> in a matrix-vector product, then by the product rule <span class="math-container">$\dot v=w·\dot u+\dot w·u$</span> and <span class="math-container">$$ {\rm Tr}(\bar w·\dot w)=\bar v·\dot w·u={\rm Tr}(u·\bar v·\dot w), $$</span> so the comparison gives <span class="math-container">$\bar w=u·\bar v$</span>.</p> <hr /> <p>The example network in atomic formulas is <span class="math-container">\begin{align} z^{(2)}&amp;=\Theta^{(1)}·x \\ a^{(2)}&amp;=f(z^{(2)}) \\ z^{(3)}&amp;=\Theta^{(2)}·a^{(2)} \\ a^{(3)}&amp;=f(z^{(3)}) \\ \end{align}</span> and then <span class="math-container">$J$</span> is computed via some loss function from <span class="math-container">$a^{(3)}$</span> and the reference value <span class="math-container">$y$</span>.</p> <p>Starting from the gradient <span class="math-container">$\bar a^{(3)}$</span> computed from the loss function, the pushed-back gradients compute as <span class="math-container">\begin{align} \bar z^{(3)} &amp;= \bar a^{(3)}·{\rm diag}(f'(z^{(3)})) \\ \bar a^{(2)} &amp;= \bar z^{(3)}·\Theta^{(2)} \\ \bar \Theta^{(2)} &amp;= a^{(2)}·\bar z^{(3)} \\ \bar z^{(2)} &amp;= \bar a^{(2)}·{\rm diag}(f'(z^{(2)})) \\ \bar x &amp;= \bar z^{(2)}·\Theta^{(1)} \\ \bar \Theta^{(1)} &amp;= x·\bar z^{(2)} \\ \end{align}</span></p> <p>Of course one can combine some of these formulas, like <span class="math-container">$$ \delta^{(2)}=\bar z^{(2)} =\bar z^{(3)}·\Theta^{(2)}·{\rm diag}(f'(z^{(2)})) =\delta^{(3)}·\Theta^{(2)}·{\rm diag}(f'(z^{(2)})) $$</span> and if <span class="math-container">$J=\frac12\sum |a_j^{(3)}-y_j|^2$</span>, then also <span class="math-container">$$ \delta^{(3)}=\bar z^{(3)}=\bar J\,[a_1^{(3)}-y_1,a_2^{(3)}-y_2,…]·{\rm diag}(f'(z^{(3)})) $$</span> with for instance <span class="math-container">$\bar J=\frac1m$</span>.</p>
https://ai.stackexchange.com/questions/37968/back-propagation-activation-function-derivative
Question: <p>I'm trying to study how backpropagation works step by step in a MultiLayer Perceptron neural network. I would really like to be able to understand how these calculations work. And I have a specific question I would like to ask. The formulas <strong>I'm trying to learn are the following to calculate the delta, and then to update the weights and bias:</strong></p> <p><strong>Please, could you help me understand if is correct ?</strong></p> <p><strong>In Output Layer</strong></p> <pre><code>Calculate delta: error * derivative Update weights: newW = oldW + (delta * neuron entry * learning_rate) Update Bias: newB = oldB + (delta * learning_rate) </code></pre> <p>(Here in the output layer, the neuron's error is the difference between the desired output and the predicted output of the neuron, in the feedforward phase)</p> <p><em><strong>In the Hidden Layer:</strong></em></p> <pre><code>Calculate delta: SUM of (delta * connection weight ) * derivative Update weights: newW = oldW + (delta * neuron entry * learning_rate) Update Bias: newB = oldB + (delta * learning_rate) </code></pre> <p>(In the SUM, Here, in the hidden layer, the error of a neuron is a summation, adding the delta multiplied by the connection weight of the neuron in this next layer with the neuron in the current layer, of each neuron in the next layer, that is, the connection weights that connect a neuron in the current hidden layer with a neuron in the next layer.)</p> <p><strong>I would like to ask you a specific question about these two formulas used in backpropagation, because I have this doubt: the formulas I am studying to calculate the delta and then to update the weights in the output layer and hidden layer are correct, Are these formulas I mentioned correct?</strong></p> <p><em>Please, could someone help me, and tell me if what I am studying is correct?</em></p> <p>What are the backpropagation correct formulas?</p> Answer: <p>Your understanding appears correct. One formula I want to nitpick about though, is that of the delta calculation for the hidden layer. I would suggest framing it as :</p> <pre><code>SUM of (delta * connection weight ) * derivative </code></pre> <p>rather than :</p> <pre><code>(SUM of delta * connection weight ) * derivative </code></pre>
https://ai.stackexchange.com/questions/42447/what-is-the-backpropagation-formula-to-calculate-delta-and-update-weights
Question: <p>I'm trying to understand a line of my note.</p> <p>Let's say there is a simple feedforward neural network that has <span class="math-container">$N$</span> layers, and for a given layer <span class="math-container">$l$</span>, it has weight <span class="math-container">$W^l$</span>, and <span class="math-container">$g^l$</span> is the gradient to update it. Now the problem is:</p> <ol> <li><p>From the Wiki page of <a href="https://en.wikipedia.org/wiki/Backpropagation#Matrix_multiplication" rel="nofollow noreferrer">Backpropagation</a>, to compute <span class="math-container">$\nabla_{W^l}C$</span>(or simply <span class="math-container">$g^l$</span>), i.e. the gradient of the cost function with respect to the weight of layer <span class="math-container">$l$</span>, you will need two things:</p> <ol> <li>A sub-expression <span class="math-container">$\delta^l$</span>, which is the gradient of the weighted output of the current layer <span class="math-container">$l$</span>, i.e. <span class="math-container">$\nabla_{z^l}C$</span>. (there is no such symbol in the link, but I believe my usage is correct.)</li> <li>The activation of the <em>previous</em> layer <span class="math-container">$l-1$</span>, i.e. <span class="math-container">$a^{l-1}$</span>.</li> </ol> </li> </ol> <p>This is why it says <span class="math-container">$\nabla_{W^l}C=\delta^l(a^{l-1})^T$</span>. My reasoning of this is that: the weighted output of layer <span class="math-container">$l$</span>, i.e. <span class="math-container">$z^l$</span>, is the result of multiplication between the output of the previous layer, i.e. <span class="math-container">$a^{l-1}$</span>, and the weight of the current layer, i.e. <span class="math-container">$W^l$</span>.</p> <ol start="2"> <li>But now I found my note saying something different: it says that to compute the gradient <span class="math-container">$\nabla_{W^l}C$</span>(or simply <span class="math-container">$g^l$</span>), it would require <span class="math-container">$W^{l+1},g^{l+1},a^l$</span>, that is: the weight and gradient of the next layer and the output of the current layer.</li> </ol> <p>Is my note wrong?</p> Answer: <blockquote> <ol> <li>A sub-expression <span class="math-container">$\delta^l$</span>, which is the gradient of the weighted output of the current layer <span class="math-container">$l$</span>, i.e. <span class="math-container">$\nabla_{z^l}C$</span>. (there is no such symbol in the link, but I believe my usage is correct.)</li> </ol> </blockquote> <p>First of all, you're correct that the symbol <span class="math-container">$\delta^l$</span> represents the gradient of the cost w.r.t. the weighted output (so the activation function has not been applied) of the layer <span class="math-container">$l$</span>. This reasoning for this is simply chain-rule.</p> <p>But you have to be aware of that the auxiliary function <span class="math-container">$\delta^l$</span> involves the value of <span class="math-container">$(f^l)'$</span> at <span class="math-container">$z^l$</span>. This means that you will need to save <span class="math-container">$z^l$</span> for computing <span class="math-container">$\delta^l$</span>.</p> <blockquote> <p>But now I found my note saying something different: it says that to compute the gradient <span class="math-container">$\nabla_{W^l}C$</span>(or simply <span class="math-container">$g^l$</span>), it would require <span class="math-container">$W^{l+1},g^{l+1},a^l$</span>, that is: the weight and gradient of the next layer and the output of the current layer.</p> </blockquote> <p>By <span class="math-container">$\nabla_{W^l}C=\delta^l(a^{l-1})^T$</span>, it's clear that you will need both <span class="math-container">$\delta^l$</span> and <span class="math-container">$a^{l-1}$</span> to update the weight <span class="math-container">$W^l$</span>. For <span class="math-container">$\delta^l$</span>, you will need:</p> <ol> <li>the <span class="math-container">$\nabla_{a^l}{C}=(W^{l+1})^T\delta^{l+1}$</span>, which is the gradient of the cost w.r.t. the activated weighted output of the current layer <span class="math-container">$l$</span>.</li> <li>the weighted output <span class="math-container">$z^l$</span> to compute <span class="math-container">$(f^l)'$</span> at <span class="math-container">$z^l$</span>, which is mentioned in my first reply.</li> </ol> <p>To compute the gradient <span class="math-container">$\nabla_{W^l}C$</span>, the value of these symbols are required:</p> <ol> <li><span class="math-container">$W^{l+1}$</span>.</li> <li><span class="math-container">$\nabla_{a^l}{C}$</span> instead of <span class="math-container">$g^{l+1}$</span>, which is the gradient of the <em>weight</em> as you have said. <ul> <li>this involves <span class="math-container">$z^l$</span>, as stated above.</li> </ul> </li> <li><span class="math-container">$a^{l-1}$</span> instead of <span class="math-container">$a^{l}$</span>, since the latter is for <span class="math-container">$\nabla_{W^{l+1}}C$</span>.</li> </ol> <p>So yes, your note is incorrect.</p> <hr /> <p>reference: <a href="https://towardsdatascience.com/back-propagation-simplified-218430e21ad0" rel="nofollow noreferrer">https://towardsdatascience.com/back-propagation-simplified-218430e21ad0</a></p>
https://ai.stackexchange.com/questions/40727/about-the-requirement-to-compute-the-gradient-at-layer-l
Question: <p>Here's a BackProp Algo definition from <a href="https://ujjwalkarn.me/2016/08/09/quick-intro-neural-networks/" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>Initially all the edge weights are randomly assigned. For every input in the training dataset, the ANN is activated and its output is observed. This output is compared with the desired output that we already know, and the error is “propagated” back to the previous layer. This error is noted and the weights are “adjusted” accordingly. This process is repeated until the output error is below a predetermined threshold.</p> </blockquote> <p>Something I'm not understanding here: <em><strong>If inputs are fed one by one, and the weights are adjusted for each input, won't the NN essentially be trained for the last input?</strong></em></p> <p>Please clarify. Thank you.</p> Answer: <p>The concern you've raised touches on the method of training known as online learning or <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent#Iterative_method" rel="nofollow noreferrer">stochastic gradient descent (SGD)</a>, where weights are updated after each individual training example. It's a common misunderstanding that, when using SGD even though weights are updated after each individual training example, the process involves iterating over the entire dataset multiple times. Each iteration is called an epoch. There's also a simple example in the cited reference.</p> <blockquote> <p>As the algorithm sweeps through the training set, it performs the above update for each training sample. Several passes can be made over the training set until the algorithm converges. If this is done, the data can be shuffled for each pass to prevent cycles. Typical implementations may use an adaptive learning rate so that the algorithm converges.</p> </blockquote> <p>The network is exposed to each training example many times over multiple epochs. Each example contributes to the weight updates incrementally, ensuring the model learns from the entire dataset about which the usual empirical risk minimization (ERM) ML framework targets to minimize its average loss. The updates in SGD are noisy but more efficient than batch gradient descent using the entire datatset, which helps the model escape local minima and potentially find a better global minimum.</p>
https://ai.stackexchange.com/questions/46239/how-does-backprop-avoid-bias-for-the-last-input-used-for-training
Question: <p><strong>References:</strong></p> <ul> <li><strong>Chain rule in Wikipedia:</strong> <a href="https://en.wikipedia.org/wiki/Chain_rule" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Chain_rule</a></li> <li><strong>Chain rule in Towards Data Science:</strong> <a href="https://towardsdatascience.com/understanding-backpropagation-algorithm-7bb3aa2f95fd#:%7E:text=The%20algorithm%20is%20used%20to,parameters%20(weights%20and%20biases)" rel="nofollow noreferrer">https://towardsdatascience.com/understanding-backpropagation-algorithm-7bb3aa2f95fd#:~:text=The%20algorithm%20is%20used%20to,parameters%20(weights%20and%20biases)</a>.</li> </ul> <p>Searching the internet in some articles, I learned that the chain rule is used so that the network can identify the contribution of each weight to the error, and how much each weight needs to be adjusted.</p> <p>This article I mentioned in the question: <a href="https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/" rel="nofollow noreferrer">https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/</a>, they teaches you how to program a multilayer perceptron neural network from scratch in Python. During the calculations in the backpropagation phase, he uses some different terms such &quot;delta&quot;, and it calculates the &quot;delta&quot; layer by layer. I know that the explanation in the article must make use of the chain rule, but I couldn't understand where.</p> <p>I couldn't see where the chain rule is. Does this article make use of the chain rule? And where?</p> Answer: <p>Unless the derivation has been added in a comment, when you read code implementations of backpropagation, then the chain rule has already been used to derive the update rules. As it is basically a rule about multiplying one simpler derivative by another to resolve the derivative of a more complex function, then typically some of the terms in each statement represent <span class="math-container">$\frac{\partial f}{\partial x}$</span> and some represent <span class="math-container">$\frac{\partial g}{\partial f}$</span>. When those are multiplied together you find the numerical value of <span class="math-container">$\frac{\partial g}{\partial x}$</span> from the composite <span class="math-container">$g(f(x))$</span>.</p> <p>The &quot;deltas&quot; being stored in variables are components of the gradient of the loss function with respect to the network's internal states and free parameters, at its current value (due to current item, or an aggregate across the current batch).</p> <ul> <li><p>Some are temporary calculations that don't need to be stored longer term because they are not gradient components of changeable parameters.</p> </li> <li><p>Some represent components of <span class="math-container">$\nabla_{W,b} J$</span>, the gradient of the cost function <span class="math-container">$J$</span> with respect to the weights and biases of the neural network - these are the values that you can change as part of training, so they are usually stored in a structure the same shape as the weights and biases so that they can be aggregated across multiple examples and subtracted from <span class="math-container">$W,b$</span> later.</p> </li> </ul>
https://ai.stackexchange.com/questions/42722/does-this-article-make-use-of-the-chain-rule-and-where
Question: <p>I have a question about backpropagation, I'm a beginner, I'm studying the formulas to calculate the delta of neurons, there are several sources on the internet, which teach in different ways, so I'm confused about the formulas presented in the explanations, as they are a little different. Please, could someone help me understand if the explanations in these two articles are equivalent?:</p> <p>This first article: <a href="https://home.agh.edu.pl/%7Evlsi/AI/backp_t_en/backprop.html" rel="nofollow noreferrer">https://home.agh.edu.pl/~vlsi/AI/backp_t_en/backprop.html</a>, it says that the error of a neuron in the current hidden layer is the <code>sum of all (error* connection weight)</code> of the neurons in the next layer. The error calculation in this article does not use the derivative of the neuron activation when calculating the error. Instead, it will only use the derivative when updating the weights, using the formula &quot;<code>wNew = wOld + (learningRate * error * derivative * input)</code>&quot;, this is where it will use the derivative.</p> <p>However, in this second article: <a href="https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/" rel="nofollow noreferrer">https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/</a>, which teaches how to program a multi-layer perceptron from scratch in Python, he does it a little differently, In the formula for updating the weights he uses a variable called &quot;delta&quot;, he explains that the &quot;delta&quot; of a neuron is the <code>(neuron's error * derivative from the neuron's activation)</code>, and to calculate this delta we need the neuron's error. In the code presented in this article, the error of a neuron in the hidden layer is also a sum, but it is the <code>sum of (neuron delta * connection weight)</code> of the neurons in the next layer, therefore it first calculates the error of all neurons, then it calculates the &quot;deltas&quot; of all neurons (so, to calculate the deltas of neurons in one layer it uses the deltas of the next layer), and then updates the weights. And since in this article he already calculated the delta as being the (error * derivative), when updating the weights, the formula for updating the weights is simply &quot;<code>wNew = wOld + (learningRate * delta * input)</code>&quot;</p> <p><strong>So I'm confused</strong>, <strong>specifically about SUM. I would really like to understand why in the first article</strong>: <a href="https://home.agh.edu.pl/%7Evlsi/AI/backp_t_en/backprop.html" rel="nofollow noreferrer">https://home.agh.edu.pl/~vlsi/AI/backp_t_en/backprop.html</a>, he calculates the neuron error without using the derivative, and only uses the derivative just when updating the weights. And on the other hand, in this other article: <a href="https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/" rel="nofollow noreferrer">https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/</a>, it calculates the errors and then calculates the deltas using the derivative to calculate these deltas, to then update the weights without needing to use a derivative in the formula to update the weights</p> <p><strong>Why are there these differences in the formulas of the two articles? This is a question I've had for a long time, I would really like to understand. Are the explanations in these two articles equivalent? Please help me clarify this doubt?</strong></p> Answer: <p>The difference you spotted is only cosmetic when dealing with formulas yet both are equivalent. In general for any delta rule ultimately driven by some form of error be it primitive correction or Widrow-Hoff/LMS like SGD correction follows the three multiplicative terms (learning rate, error, input) format of your 2nd reference, thus the backpropagated error for each (hidden) neuron should've already absorbed the derivative of the neuron activation complying with this convention for the middle error term of the said neuron. This is reflected in the code below of the backward_propagate_error(network, expected) function in your 2nd reference. Of course there's nothing wrong to invoke the derivative of activation in the last update step as reflected in your 1st reference.</p> <pre><code> neuron = layer[j] neuron['delta'] = errors[j] * transfer_derivative(neuron['output']) </code></pre>
https://ai.stackexchange.com/questions/42626/please-could-someone-help-me-understand-if-the-backpropagation-explanations-in
Question: <p>In section 6.5.6 of the book <a href="https://www.deeplearningbook.org" rel="nofollow noreferrer">Deep Learning</a> by Ian et. al. general backpropagation algorithm is described as:</p> <blockquote> <p>The back-propagation algorithm is very simple. To compute the gradient of some scalar z with respect to one of its ancestors x in the graph, we begin by observing that the gradient with respect to z is given by dz = 1. We can then compute dz the gradient with respect to each parent of z in the graph by multiplying the current gradient by the Jacobian of the operation that produced z. We continue multiplying by Jacobians traveling backwards through the graph in this way until we reach x. For any node that may be reached by going backwards from z through two or more paths, we simply sum the gradients arriving from different paths at that node.</p> </blockquote> <p>To be specific I don't get this part:</p> <blockquote> <p>We can then compute dz the gradient with respect to each parent of z in the graph by multiplying the current gradient by the Jacobian of the operation that produced z.</p> </blockquote> <p>Can anyone help me understand this with some illustration? Thank you.</p> Answer:
https://ai.stackexchange.com/questions/22238/i-need-help-understanding-general-back-propagation-algorithm
Question: <p>I'm a bit confused about this. Assume I have a CNN network with two branches:</p> <ol> <li>Top</li> <li>Bottom</li> </ol> <p>The top branch outputs a feature vector of shape 1x1x1x10 (batch, h, w, c) The bottom branch outputs a feature vector of shape (1, 10, 10, 10).</p> <p>I want to use the top feature vector as a convolutional filter, and convolve it with the bottom feature vector. I can do this in pytorch with the "functional.Conv2D" function, the problem is, I don't know how back-prop works in this case (will it be unstable?) since the output feature is a now a parameter as well, do I need to stop gradients or do something else in this case to backprop correctly?</p> Answer:
https://ai.stackexchange.com/questions/8664/using-features-extracted-from-a-cnn-as-convolutional-filter
Question: <p>There is a theorem that states that basically a neural network can approximate any function whatsoever. However, this does not mean that it can solve any equation. I have some notes where it states that backpropagation allows us to solve problems of the following kind </p> <p><span class="math-container">$$ F(x_i, t) = y_i $$</span></p> <p>Can someone point me to what exactly this means?</p> Answer:
https://ai.stackexchange.com/questions/20715/class-of-functional-equations-that-backpropagation-can-solve
Question: <p>I read Yann LeCun's paper <a href="https://www.researchgate.net/publication/2811922_Efficient_BackProp" rel="nofollow noreferrer">Efficient BackProp</a>, which was published in 2000. I looked for similar but more recent papers on <a href="https://arxiv.org/" rel="nofollow noreferrer">Arxiv</a>, but I have not yet found any.</p> <p><em>Are there relatively new research papers that describe how to make back-propagation more efficient?</em></p> <p>So, I am looking for papers similar to <a href="https://www.researchgate.net/publication/2811922_Efficient_BackProp" rel="nofollow noreferrer">Efficient Backprop</a> by LeCun but newer. The papers could describe why ReLU now &quot;dominates&quot; tanh or even sigmoid (but tanh was Yann's favorite, as explained in the paper). ReLU is just one thing I am interested in, but the paper could also analyze e.g. the inputs from a statistical standpoint.</p> Answer: <p><a href="https://arxiv.org/pdf/2004.06093.pdf" rel="nofollow noreferrer">Here</a> is a paper that explains why ReLU rules.</p> <p>What we want is to disentangle data of different classes. In order to do that, we need a discontinuous mapping for the data. ReLU easily allows for that. It is even better than LeakyReLU, sigmoid and tanh in that regard. Also, the reason any of the activations work is because of the floating point error, there is inadvertently a discontinuous mapping for the whole data. I have also explained it <a href="https://towardsdatascience.com/relu-rules-lets-understand-why-its-popularity-remains-unshaken-ccfe952fc5b1" rel="nofollow noreferrer">here</a>.</p>
https://ai.stackexchange.com/questions/26986/are-there-relatively-new-research-papers-that-describe-how-to-make-back-propagat
Question: <p>Is a Levenberg–Marquardt algorithm a type of back-propagation algorithm or is it a different category of algorithm?</p> <p>Wikipedia says that it is a curve fitting algorithm. How is a curve fitting algorithm relevant to a neural net?</p> Answer: <p>In the context of Neural Networks, Backpropagation (with Gradient Descent, to use its full name) and Levengerg Marquardt are both members of the broader family of gradient descent algorithms. Backpropagation itself is not gradient descent, but it does the gradient climbing portion of a broader gradient descent algorithm. </p> <p>You can imagine the function of a Neural Network as a function from its inputs to its outputs. If you were trying to solve, for example, a regression problem you can imagine this problem in multidimensional space with each training point corresponding to the coordinate provided by the values of its inputs and outputs (each of which represent a dimension). Then the entire training set you have for learning this regression problem become a set of points in this multidimensional space, and the function that your neural network performs is a curve in this multidimensional space. The closer this curve is to the points on the training set, the better it performs at the regression problem which essentially means we can generalize the task of training the neural network to a curve fitting problem.</p>
https://ai.stackexchange.com/questions/2520/what-kind-of-algorithm-is-the-levenberg-marquardt-algorithm
Question: <p>I have this simple neural network in Python which I'm trying to use to aproximation tanh function. As inputs I have x - inputs to the function, and as outputs I want tanh(x) = y. I'm using sigmoid function also as an activation function of this neural network. </p> <pre><code>import numpy # scipy.special for the sigmoid function expit() import scipy.special # library for plotting arrays import matplotlib.pyplot # ensure the plots are inside this notebook, not an external window %matplotlib inline # neural network class definition class neuralNetwork: # initialise the neural network def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate): # set number of nodes in each input, hidden, output layer self.inodes = inputnodes self.hnodes = hiddennodes self.onodes = outputnodes # link weight matrices, wih and who # weights inside the arrays are w_i_j, where link is from node i to node j in the next layer # w11 w21 # w12 w22 etc self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes)) self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes)) # learning rate self.lr = learningrate # activation function is the sigmoid function self.activation_function = lambda x: scipy.special.expit(x) pass # train the neural network def train(self, inputs_list, targets_list): # convert inputs list to 2d array inputs = numpy.array(inputs_list, ndmin=2).T targets = numpy.array(targets_list, ndmin=2).T # calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) # calculate the signals emerging from hidden layer hidden_outputs = self.activation_function(hidden_inputs) # calculate signals into final output layer final_inputs = numpy.dot(self.who, hidden_outputs) # calculate the signals emerging from final output layer final_outputs = self.activation_function(final_inputs) # output layer error is the (target - actual) output_errors = targets - final_outputs # hidden layer error is the output_errors, split by weights, recombined at hidden nodes hidden_errors = numpy.dot(self.who.T, output_errors) # BACKPROPAGATION &amp; gradient descent part, i.e updating weights first between hidden # layer and output layer, # update the weights for the links between the hidden and output layers self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs)) # update the weights for the links between the input and hidden layers, second part of backpropagation. self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs)) pass # query the neural network def query(self, inputs_list): # convert inputs list to 2d array inputs = numpy.array(inputs_list, ndmin=2).T # calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) # calculate the signals emerging from hidden layer hidden_outputs = self.activation_function(hidden_inputs) # calculate signals into final output layer final_inputs = numpy.dot(self.who, hidden_outputs) # calculate the signals emerging from final output layer final_outputs = self.activation_function(final_inputs) return final_outputs </code></pre> <p>Now I try to query this network, This network has three input nodes one for each x, one node for each input. This network also has 3 output nodes, so It would classify the inputs to given outputs. Where outputs are y, y = tanh(x) function. </p> <pre><code># number of input, hidden and output nodes input_nodes = 3 hidden_nodes = 8 output_nodes = 3 learning_rate = 0.1 # create instance of neural network n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate) realInputs = [] realInputs.append(1) realInputs.append(2) realInputs.append(3) # for x in (-3, 3): # realInputs.append(x) # pass expectedOutputs = [] expectedOutputs.append(numpy.tanh(1)); expectedOutputs.append(numpy.tanh(2)); expectedOutputs.append(numpy.tanh(3)); for y in expectedOutputs: print(y) pass training_data_list = [] # epochs is the number of times the training data set is used for training epochs = 200 for e in range(epochs): # go through all records in the training data set for record in training_data_list: # scale and shift the inputs inputs = realInputs targets = expectedOutputs n.train(inputs, targets) pass pass n.query(realInputs) </code></pre> <p>Outputs: desired vs ones from network with same data as training data:</p> <pre><code>0.7615941559557649 0.9640275800758169 0.9950547536867305 array([[-0.21907413], [-0.6424568 ], [-0.25772344]]) </code></pre> <p>My results are completely wrong. I'm a beginner with neural networks so I wanted to build neural network without frameworks like tensor flow... Could someone help me? Thank you. </p> Answer: <p>This is because of <strong>Vanishing Gradient Problem</strong></p> <p>What is Vanishing Gradient Problem ?</p> <p>when we do Back-propagation i.e moving backward in the Network and calculating gradients of loss(Error) with respect to the weights , the gradients tends to get smaller and smaller as we keep on moving backward in the Network. This means that the neurons in the Earlier layers learn very slowly as compared to the neurons in the later layers in the Hierarchy. The Earlier layers in the network are slowest to train.</p> <p><strong>Reason</strong></p> <p>Sigmoid function, squishes a large input space into a small input space between 0 and 1. Therefore a large change in the input of the sigmoid function will cause a small change in the output. Hence, the derivative becomes small. <a href="https://i.sstatic.net/vKtiQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vKtiQ.png" alt="Sigmoid And its Derivative Function"></a></p> <p><strong>Solution:</strong></p> <p>Use Activation function as ReLu</p> <p><a href="https://i.sstatic.net/dAAFA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dAAFA.png" alt="ReLu"></a></p> <p>Reference:</p> <p><a href="https://towardsdatascience.com/the-vanishing-gradient-problem-69bf08b15484" rel="nofollow noreferrer">Vanishing Gradient Solution</a></p>
https://ai.stackexchange.com/questions/18762/simple-three-layer-neural-network-with-backpropagation-is-not-approximating-tanh
Question: <p>I Build this NN in c++. I reviewed it since 3 days. I checked every line 100 times, but I cant find my error. If someone can please help me find the Bugs: 1. The output is garbage 2. The weights go from 2e^79 down to -1.8e^80 after approximatly 400 iterations.</p> <pre><code>mat flip(mat m) { mat out(m.n_cols,m.n_rows); for (int i = 0; i &lt; m.n_rows; ++i) for (int j = 0; j &lt; m.n_cols; ++j) out(j, i) = m(i, j); return out; } Layer::Layer(int nodes) : rand_engine(time(0)) { y = mat (nodes, 1); net = mat(nodes, 1); e = mat(nodes, 1); } Layer::Layer(int nodes, int next_nodes) : Layer(nodes) { this-&gt;next_l = next_l; auto random = bind(uniform_real_distribution&lt;double&gt;{-1, 1}, rand_engine); w = mat(next_nodes,nodes); for (int i = 0; i &lt; w.n_rows; ++i) { for (int j = 0; j &lt; w.n_cols; ++j) { w(i,j) = random(); } } } Layer::Layer(int nodes, Layer* next_l) : Layer(nodes,next_l-&gt;y.n_rows) { this-&gt;next_l = next_l; } void Layer::feed_forward() { next_l-&gt;net = w*y; for (int i = 0; i &lt; next_l-&gt;y.n_rows;++i) next_l-&gt;y[i] = sig(next_l-&gt;net[i]); } void Layer::backprop() { for (double d : w) cout &lt;&lt; d &lt;&lt; "\t"; e = flip(w)*next_l-&gt;e; for (int i = 0; i &lt; e.n_rows; ++i) { e[i] *= net[i] * (1 - net[i]); cout &lt;&lt; e[i] &lt;&lt; '\t'; } w += l_rate*(next_l-&gt;e*flip(y)); } void Layer::backprop_last(mat t) { for (int i = 0; i &lt; e.n_rows; ++i) { e[i] = net[i] * (1 - net[i])*(t[i] - y[i]); cout &lt;&lt; e[i] &lt;&lt; '\t'; } } void Layer::feed_forward(Layer* next_l) { this-&gt;next_l = next_l; feed_forward(); } double Layer::sig(double x) { return 1 / (1 + exp(-x)); } Network::Network(vector&lt;int&gt; top): top(top) { network = new Layer*[top.size()]; network[top.size() - 1] = new Layer(top.back()); for (int i = top.size()-2; i &gt; -1; --i) network[i] = new Layer(top[i], network[i + 1]); } Network::~Network() { delete[] network; } void Network::forward() { for(int i = 0; i &lt; top.front();++i) network[0]-&gt;y[i] = input[i]; for (int i = 0; i &lt; top.size() - 1; ++i) network[i]-&gt;feed_forward(); } void Network::forward(vector&lt;double&gt; input) { set_input(input); forward(); } void Network::backprop() { network[top.size() - 1]-&gt;backprop_last(t_vals); for (int i = top.size() - 2; i &gt; -1; --i) { network[i]-&gt;backprop(); } } void Network::backprop(vector&lt;double&gt; t_vals) { set_t_vals(t_vals); backprop(); } </code></pre> <p>I know its a bunch of code but im really desprate since I cant find whats wrong. I tested it with a simple XOR.</p> <p>Edit: Heres my Main code:</p> <pre><code> #include "Network.h" #include &lt;iomanip&gt; using namespace std; vector&lt;vector&lt;double&gt;&gt; input = { {0,0},{0,1},{1,1},{1,0} }; vector&lt;vector&lt;double&gt;&gt; true_vals = { {0},{1},{0},{1} }; int main() { ifstream f("out.txt", fstream::out); f.clear(); cout &lt;&lt; fixed; cout &lt;&lt; setprecision(5); Network net({2,5,1}); vector&lt;double&gt; in,t,out; auto buf = cout.rdbuf(); for (int i = 0; i &lt; 1000; ++i) { cout.rdbuf(f.rdbuf()); in = input[i % 4]; net.forward(in); out = net.get_output(); t = true_vals[i % 4]; net.backprop(t); cout &lt;&lt; '\n'; cout.rdbuf(buf); if ((i %101))continue; cout &lt;&lt; "it: " &lt;&lt; i &lt;&lt; '\n'; cout &lt;&lt; "in:\t"; for (double d : in) cout &lt;&lt; d &lt;&lt; ' '; cout &lt;&lt; '\n'; cout &lt;&lt; "out:\t"; for (double d : out) cout &lt;&lt; d &lt;&lt; ' '; cout &lt;&lt; '\n'; cout &lt;&lt; "true:\t"; for (double d : t) cout &lt;&lt; d &lt;&lt; ' '; cout &lt;&lt; '\n'; double err = net.get_error(); cout &lt;&lt;"err:\t"&lt;&lt; err &lt;&lt; '\n' &lt;&lt; '\n'; } cout.rdbuf(NULL); f.close(); return system("pause"); } </code></pre> Answer: <p>A little search on Google answers your question.</p> <p>XOR input space is not linearly separable. It means that you cannot separate the input points in a 2D space into 1 area and 0 area by simply drawing a line between them. It requires at least 2 lines to separate the XOR input space and consequently 2 output nodes (used as classifiers rather than regression). You can easily find its details in google. Search &quot;XOR problem in Neural Net&quot;.</p> <p>You can manually implement the desired Neural Network with two output Nodes acting as classifiers as follows :</p> <p><a href="https://i.sstatic.net/KGw32.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KGw32.jpg" alt="Manual Implementation" /></a></p> <p>Where A &amp; B are two output Nodes which act as classifiers (by forming AA' and BB' decision lines respectively during training by Backpropagation). The interpretation of the Outputs of the nodes is given in the table where Net column represents the Overall output to be interpreted.</p> <p><strong>I showed the above manual implementation just to give you the idea of how classification is done behind the scenes.</strong></p> <p>Here is the actual Automatic implementation :</p> <p><a href="https://i.sstatic.net/aOumf.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aOumf.jpg" alt="Practical Implementation" /></a></p> <p>Here , all the task is performed by the Neural Net behind the scenes and you get the desired output from the output node in the topmost layer</p>
https://ai.stackexchange.com/questions/2588/why-doesnt-my-neural-network-work
Question: <p>I have really quite hard difficulties to understand what is actually going on in the backward pass of a CNN.</p> <p>I am currently focusing on these references:</p> <ol> <li><a href="https://towardsdatascience.com/forward-and-backward-propagations-for-2d-convolutional-layers-ed970f8bf602" rel="nofollow noreferrer">https://towardsdatascience.com/forward-and-backward-propagations-for-2d-convolutional-layers-ed970f8bf602</a></li> <li><a href="https://leonardoaraujosantos.gitbook.io/artificial-inteligence/machine_learning/deep_learning/convolution_layer" rel="nofollow noreferrer">https://leonardoaraujosantos.gitbook.io/artificial-inteligence/machine_learning/deep_learning/convolution_layer</a></li> </ol> <p>At the moment, <strong>I only want to compute the gradient which is then passed to the next lower layer.</strong></p> <p>I tried to implement the last equation on this image (from [1]):</p> <p><a href="https://miro.medium.com/max/2400/1*K2K0tfxmAlyRlqqbj4z0Rg@2x.png" rel="nofollow noreferrer">https://miro.medium.com/max/2400/1*K2K0tfxmAlyRlqqbj4z0Rg@2x.png</a></p> <p>For me, this formula looks like 6 nested for-loops.</p> <p>The first for the channel <code>c</code>, the second for the output height <code>i</code>, the third for the output height <code>j</code>, the fourth for the number of kernels <code>f</code>, the fith for the kernel height <code>m</code> and the sixth for the kernel width <code>n</code>.</p> <p>Am I wrong? I tried to implement this but I always get an out of bounds error.</p> <p>Someone here who doesn't mind going a bit more into detail?</p> <p>Any tips are greatly appreciated</p> Answer:
https://ai.stackexchange.com/questions/32271/cnn-difficulties-understanding-backward-pass-derivatives
Question: <p>When it comes to CNNs, I don't understand 2 things in the training process:</p> <ol> <li><p>How do I pass the error back when there are pooling layers between the convolutional layers?</p></li> <li><p>And if I know how it's done, can I train all the layers just like layers in normal Feed Forward Neural Nets?</p></li> </ol> Answer: <p>Yes. You can train end-to-end. The introduction of convolution kernels with associated pooling layers to the sequence of forward feed operations on the signals does not change the basic principles.</p> <ul> <li>Gradient descent estimates the incremental change required to converge on an optimal behavior.</li> <li>The corrective error must be distributed, which is most efficiently done by employing the derivative of the activation function sequentially to each set of parameters (whether convolution kernels or matrices that attenuates inputs to activation vectors) from the output back to the input.</li> </ul> <p>Consider studying <a href="http://www.jefkine.com/general/2016/09/05/backpropagation-in-convolutional-neural-networks/" rel="nofollow noreferrer"><em>Backpropagation In Convolutional Neural Networks</em> on Jefkine.com</a>, which clarifies the application of those principles with convolution-pooling pairs.</p> <p>There is another approach, borrowing from wisdom gained in the development of analog feedback in instrumentation. There are times when a sequence of operations can be better trained with more than one feedback loop, which requires some determination of error or wellness at intermediate stages and breaks the system into segments that each train based on those intermediate criteria.</p> <p>This other approach is hierarchical, and an overall convergence may be controlled by a higher level back propagation, considering each segment as a black box. As in analog circuitry, multiple <strong>degrees of freedom</strong> with semi-independent convergence mechanisms has been shown to allow for deeper sequences without a major loss of convergence reliability or accuracy.</p>
https://ai.stackexchange.com/questions/7527/how-to-train-a-cnn
Question: <p>My full code is as follows. I have tried to whittle it down to just the code that matters, but the problem I have is that i'm not sure what part of my network code is producing the problem. I've removed my code that loads and sifts through the CSV data because then my code would be too long.</p> <pre><code>#include &lt;iostream&gt; #include &lt;array&gt; #include &lt;random&gt; #include &lt;chrono&gt; #include &lt;iomanip&gt; #include &lt;fstream&gt; #include &lt;algorithm&gt; #include &lt;iomanip&gt; #include &lt;variant&gt; #include &lt;unordered_set&gt; typedef std::variant&lt;std::string,std::uint_fast16_t,bool,float&gt; CSVType; /* ... functions to load CSV data ... */ typedef float DataType; typedef DataType (*ActivationFuncPtr)(const DataType&amp;); DataType step(const DataType&amp; x, const DataType&amp; threshold) { return x &gt;= threshold ? 1 : 0; } DataType step0(const DataType&amp; x) { return step(x,0); } DataType step05(const DataType&amp; x) { return step(x,0.5); } DataType sigmoid(const DataType&amp; x) { return DataType(1) / (DataType(1) + std::exp(-x)); } DataType sigmoid_derivative(const DataType&amp; x) { return x * (DataType(1) - x); } template&lt;std::size_t NumInputs&gt; class Neuron { public: Neuron() { RandomiseWeights(); } void RandomiseWeights() { std::generate(m_weights.begin(),m_weights.end(),[&amp;]() { return m_xavierNormalDis(m_mt); }); m_biasWeight = 0; for(std::size_t i = 0; i &lt; NumInputs+1; ++i) m_previousWeightUpdates[i] = 0; } DataType FeedForward(const std::array&lt;DataType,NumInputs&gt; inputValues) { DataType output = m_biasWeight; for(std::size_t i = 0; i &lt; inputValues.size(); ++i) output += inputValues[i] * m_weights[i]; m_inputValues = inputValues; return output; } std::array&lt;DataType,NumInputs&gt; Backpropagate(const DataType&amp; error) { std::array&lt;DataType,NumInputs&gt; netInputOverWeight; for(std::size_t i = 0; i &lt; NumInputs; ++i) { netInputOverWeight[i] = m_inputValues[i]; } DataType netInputOverBias = DataType(1); std::array&lt;DataType,NumInputs&gt; errorOverWeight; for(std::size_t i = 0; i &lt; NumInputs; ++i) { errorOverWeight[i] = error * netInputOverWeight[i]; } DataType errorOverBias = error * netInputOverBias; for(std::size_t i = 0; i &lt; NumInputs; ++i) { m_outstandingWeightAdjustments[i] = errorOverWeight[i]; } m_outstandingWeightAdjustments[NumInputs] = errorOverBias; DataType errorOverNetInput = error; std::array&lt;DataType,NumInputs&gt; errorWeights; for(std::size_t i = 0; i &lt; NumInputs; ++i) { errorWeights[i] = errorOverNetInput * m_weights[i]; } return errorWeights; } void AdjustWeights(const DataType&amp; learningRate, const DataType&amp; momentum) { for(std::size_t i = 0; i &lt; NumInputs; ++i) { DataType adjustment = learningRate * m_outstandingWeightAdjustments[i] + momentum * m_previousWeightUpdates[i]; m_weights[i] = m_weights[i] - adjustment; m_previousWeightUpdates[i] = adjustment; } DataType adjustment = learningRate * m_outstandingWeightAdjustments[NumInputs] + momentum * m_previousWeightUpdates[NumInputs]; m_biasWeight = m_biasWeight - adjustment; m_previousWeightUpdates[NumInputs] = adjustment; } const std::array&lt;DataType,NumInputs&gt;&amp; GetWeights() const { return m_weights; } const DataType&amp; GetBiasWeight() const { return m_biasWeight; } protected: static std::mt19937 m_mt; static std::uniform_real_distribution&lt;DataType&gt; m_uniformDisRandom; static std::uniform_real_distribution&lt;DataType&gt; m_xavierUniformDis; static std::normal_distribution&lt;DataType&gt; m_xavierNormalDis; std::array&lt;DataType,NumInputs&gt; m_weights; DataType m_biasWeight; std::array&lt;DataType,NumInputs+1&gt; m_previousWeightUpdates; std::array&lt;DataType,NumInputs+1&gt; m_outstandingWeightAdjustments; std::array&lt;DataType,NumInputs&gt; m_inputValues; }; template&lt;std::size_t NumInputs&gt; std::mt19937 Neuron&lt;NumInputs&gt;::m_mt(std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(std::chrono::system_clock::now().time_since_epoch()).count()); template&lt;std::size_t NumInputs&gt; std::uniform_real_distribution&lt;DataType&gt; Neuron&lt;NumInputs&gt;::m_uniformDisRandom(-1,1); template&lt;std::size_t NumInputs&gt; std::uniform_real_distribution&lt;DataType&gt; Neuron&lt;NumInputs&gt;::m_xavierUniformDis(-std::sqrt(6.f / NumInputs+1),std::sqrt(6.f / NumInputs+1)); template&lt;std::size_t NumInputs&gt; std::normal_distribution&lt;DataType&gt; Neuron&lt;NumInputs&gt;::m_xavierNormalDis(0,std::sqrt(2.f / NumInputs+1)); template&lt;std::size_t NumNeurons&gt; class ActivationLayer { public: ActivationLayer() : m_outputs({}) {} virtual std::array&lt;DataType,NumNeurons&gt; GetOutputs() const final { return m_outputs; } virtual void CompleteBackprop(const DataType&amp; learningRate, const DataType&amp; momentum) final { } protected: std::array&lt;DataType,NumNeurons&gt; m_outputs; }; template&lt;std::size_t NumNeurons&gt; class SigmoidActivation : public ActivationLayer&lt;NumNeurons&gt; { public: virtual std::array&lt;DataType,NumNeurons&gt; FeedForward(const std::array&lt;DataType,NumNeurons&gt;&amp; inputValues) { for(std::size_t i = 0; i &lt; NumNeurons; ++i) ActivationLayer&lt;NumNeurons&gt;::m_outputs[i] = sigmoid(inputValues[i]); return ActivationLayer&lt;NumNeurons&gt;::m_outputs; } virtual std::array&lt;DataType,NumNeurons&gt; Backpropagate(const std::array&lt;DataType,NumNeurons&gt; errors) { std::array&lt;DataType,NumNeurons&gt; backpropErrors; for(std::size_t i = 0; i &lt; NumNeurons; ++i) backpropErrors[i] = errors[i] * sigmoid_derivative(ActivationLayer&lt;NumNeurons&gt;::m_outputs[i]); return backpropErrors; } }; template&lt;std::size_t NumInputs, std::size_t NumNeurons&gt; class FullyConnectedLayer { public: FullyConnectedLayer() : m_neurons([=]() { std::array&lt;Neuron&lt;NumInputs&gt;,NumNeurons&gt; neurons; for(Neuron&lt;NumInputs&gt;&amp; n : neurons) n = Neuron&lt;NumInputs&gt;(); return neurons; }()) { } virtual std::array&lt;DataType,NumNeurons&gt; FeedForward(const std::array&lt;DataType,NumInputs&gt;&amp; inputValues) { std::array&lt;DataType,NumNeurons&gt; outputValues; for(std::size_t i = 0; i &lt; NumNeurons; ++i) outputValues[i] = m_neurons[i].FeedForward(inputValues); return outputValues; } /** \brief Take a sum of errors for each node and produce the errors for each input node in the previous layer. * */ virtual std::array&lt;DataType,NumInputs&gt; Backpropagate(const std::array&lt;DataType,NumNeurons&gt; errors) { std::array&lt;std::array&lt;DataType,NumInputs&gt;,NumNeurons&gt; errorValues; for(std::size_t i = 0; i &lt; NumNeurons; ++i) { errorValues[i] = m_neurons[i].Backpropagate(errors[i]); } std::array&lt;DataType,NumInputs&gt; returnErrors; std::fill(returnErrors.begin(),returnErrors.end(),0); for(std::size_t i = 0; i &lt; NumNeurons; ++i) { for(std::size_t j = 0; j &lt; NumInputs; ++j) { returnErrors[j] += errorValues[i][j]; } } return returnErrors; } virtual void CompleteBackprop(const DataType&amp; learningRate, const DataType&amp; momentum) { for(Neuron&lt;NumInputs&gt;&amp; n : m_neurons) n.AdjustWeights(learningRate, momentum); } const Neuron&lt;NumInputs&gt;&amp; operator[](const std::size_t&amp; index) const { return m_neurons[index]; } std::array&lt;std::array&lt;DataType,NumInputs&gt;,NumNeurons&gt; GetWeights() const { std::array&lt;std::array&lt;DataType,NumInputs&gt;,NumNeurons&gt; weights; for(std::size_t i = 0; i &lt; NumNeurons; ++i) { weights[i] = m_neurons[i].GetWeights(); } return weights; } protected: std::array&lt;Neuron&lt;NumInputs&gt;,NumNeurons&gt; m_neurons; }; template&lt;std::size_t I = 0, typename FuncT, typename... Tp&gt; inline typename std::enable_if&lt;I == sizeof...(Tp)&gt;::type for_each(std::tuple&lt;Tp...&gt; &amp;, FuncT) { } template&lt;std::size_t I = 0, typename FuncT, typename... Tp&gt; inline typename std::enable_if&lt;I &lt; sizeof...(Tp)&gt;::type for_each(std::tuple&lt;Tp...&gt;&amp; t, FuncT f) { f(std::get&lt;I&gt;(t)); // call f, passing the Ith element of the std::tuple t and the existing output O for_each&lt;I + 1, FuncT, Tp...&gt;(t, f); // process the next element of the tuple with the new output } template&lt;std::size_t I = 0, typename FuncT, typename... Tp&gt; inline typename std::enable_if&lt;I == sizeof...(Tp)&gt;::type for_each(const std::tuple&lt;Tp...&gt; &amp;, FuncT) { } template&lt;std::size_t I = 0, typename FuncT, typename... Tp&gt; inline typename std::enable_if&lt;I &lt; sizeof...(Tp)&gt;::type for_each(const std::tuple&lt;Tp...&gt;&amp; t, FuncT f) { f(std::get&lt;I&gt;(t)); // call f, passing the Ith element of the std::tuple t and the existing output O for_each&lt;I + 1, FuncT, Tp...&gt;(t, f); // process the next element of the tuple with the new output } template&lt;std::size_t I = 0, typename FuncT, typename O, typename FinalOutput, typename... Tp&gt; inline typename std::enable_if&lt;I == sizeof...(Tp)&gt;::type for_each_get_final_output(std::tuple&lt;Tp...&gt; &amp;, FuncT, O o, FinalOutput&amp; finalOutput) { finalOutput = o; } template&lt;std::size_t I = 0, typename FuncT, typename O, typename FinalOutput, typename... Tp&gt; inline typename std::enable_if&lt;I &lt; sizeof...(Tp)&gt;::type for_each_get_final_output(std::tuple&lt;Tp...&gt;&amp; t, FuncT f, O o, FinalOutput&amp; finalOutput) { auto newO = f(std::get&lt;I&gt;(t),o); // call f, passing the Ith element of the std::tuple t and the existing output O for_each_get_final_output&lt;I + 1, FuncT, decltype(newO), FinalOutput, Tp...&gt;(t, f, newO, finalOutput); // process the next element of the tuple with the new output } template&lt;std::size_t I = 0, typename FuncT, typename O, typename... Tp&gt; inline typename std::enable_if&lt;I == 0&gt;::type for_each_reverse_impl(std::tuple&lt;Tp...&gt;&amp; t, FuncT f, O o) { f(std::get&lt;0&gt;(t),o); } template&lt;std::size_t I = 0, typename FuncT, typename O, typename... Tp&gt; inline typename std::enable_if&lt;(I &gt; 0)&gt;::type for_each_reverse_impl(std::tuple&lt;Tp...&gt;&amp; t, FuncT f, O o) { auto newO = f(std::get&lt;I&gt;(t),o); // call f, passing the Ith element of the std::tuple t and the existing output O for_each_reverse_impl&lt;I - 1, FuncT, decltype(newO), Tp...&gt;(t, f, newO); // process the next element of the tuple with the new output } template&lt;typename FuncT, typename O, typename... Tp&gt; inline void for_each_reverse(std::tuple&lt;Tp...&gt;&amp; t, FuncT f, O o) { for_each_reverse_impl&lt;sizeof...(Tp)-1, FuncT, O, Tp...&gt;(t, f, o); } enum class LOSS_FUNCTION : std::uint_fast8_t { MEAN_SQUARE_ERROR, CROSS_ENTROPY }; class ValidationOptions { public: enum class METRIC : std::uint_fast8_t { NONE, ACCURACY, LOSS }; ValidationOptions() : m_validationSplit(.3f), m_enableLoss(false), m_lossFunction(LOSS_FUNCTION::MEAN_SQUARE_ERROR), m_enableAccuracy(false), m_outputFilter([](const DataType&amp; x){ return x; }), m_earlyStoppingMetric(METRIC::NONE), m_earlyStoppingPatience(1.f), m_earlyStoppingDelta(1.f), m_earlyStoppingNumEpochsAverage(1) {} ValidationOptions&amp; Loss(const bool enable = true, LOSS_FUNCTION lossFunction = LOSS_FUNCTION::MEAN_SQUARE_ERROR) { m_enableLoss = enable; m_lossFunction = lossFunction; return *this; } ValidationOptions&amp; Split(const float dataSplitValidation) { m_validationSplit = dataSplitValidation; return *this; } ValidationOptions&amp; Accuracy(const bool enable = true, ActivationFuncPtr outputFilter = [](const DataType&amp; x){return x;}) { m_enableAccuracy = enable; m_outputFilter = outputFilter; return *this; } ValidationOptions&amp; EarlyStop(const bool enable = true, const METRIC metric = METRIC::ACCURACY, const float patience = .1f, const DataType delta = .01, const std::size_t epochNumToAverage = 10) { if(enable == false) m_earlyStoppingMetric = METRIC::NONE; else m_earlyStoppingMetric = metric; m_earlyStoppingPatience = patience; m_earlyStoppingDelta = delta; m_earlyStoppingNumEpochsAverage = epochNumToAverage; return *this; } float GetValidationSplit() const { return m_validationSplit; } bool Loss() const { return m_enableLoss; } LOSS_FUNCTION GetLossFunction() const { return m_lossFunction; } bool Accuracy() const { return m_enableAccuracy; } ActivationFuncPtr GetOutputFilter() const { return m_outputFilter; } METRIC GetEarlyStoppingMetric() const { return m_earlyStoppingMetric; } float GetEarlyStoppingPatience() const { return m_earlyStoppingPatience; } DataType GetEarlyStoppingDelta() const { return m_earlyStoppingDelta; } std::size_t GetEarlyStoppingNumEpochsAvg() const { return m_earlyStoppingNumEpochsAverage; } protected: float m_validationSplit; /**&lt; Percentage of the data set aside for validation */ bool m_enableLoss; LOSS_FUNCTION m_lossFunction; /**&lt; Loss function to use */ bool m_enableAccuracy; ActivationFuncPtr m_outputFilter; /**&lt; When measuring accuracy data is passed through this */ METRIC m_earlyStoppingMetric; /**&lt; The metric used to stop early */ float m_earlyStoppingPatience; /**&lt; Percentage of total epochs to wait before stopping early */ DataType m_earlyStoppingDelta; /**&lt; The amount that the early stopping metric needs to change in a single step before stopping */ std::size_t m_earlyStoppingNumEpochsAverage; /**&lt; The number of epochs averaged over to smooth out the stopping metric */ }; template&lt;typename... Layers&gt; class NeuralNetwork { public: NeuralNetwork(Layers... layers) : m_layers(std::make_tuple(layers...)) { } template&lt;std::size_t NumFeatures, std::size_t NumOutputs, std::size_t NumTrainingRows&gt; void Fit(const std::size_t&amp; numberEpochs, const std::size_t&amp; batchSize, DataType learningRate, const DataType&amp; momentum, std::array&lt;std::array&lt;DataType,NumFeatures&gt;,NumTrainingRows&gt;&amp; trainingData, std::array&lt;std::array&lt;DataType,NumOutputs&gt;,NumTrainingRows&gt;&amp; trainingOutput, const ValidationOptions validationOptions, const bool linearDecayLearningRate = true, std::ostream&amp; outputStream = std::cout) { std::size_t epochNumber = 0; // need to support more than just MSE to measure loss std::vector&lt;DataType&gt; lastEpochLoss(validationOptions.GetEarlyStoppingNumEpochsAvg(),0); DataType lastEpochLossAverage = std::numeric_limits&lt;DataType&gt;::max(); std::vector&lt;DataType&gt; lastValidationAccuracys(validationOptions.GetEarlyStoppingNumEpochsAvg(),0); DataType lastValidationAccuraryAvg = 0; std::vector&lt;std::size_t&gt; randomIndices(NumTrainingRows,0); for(std::size_t i = 0; i &lt; NumTrainingRows; ++i) randomIndices[i] = i; std::random_shuffle(randomIndices.begin(),randomIndices.end()); // take some percentage as validation split // we do this by taking the first percentage of already shuffled indices and removing them // from what is available std::size_t numValidationRecords = NumTrainingRows*validationOptions.GetValidationSplit(); std::size_t numTrainingRecords = NumTrainingRows - numValidationRecords; std::vector&lt;std::size_t&gt; validationRecords(numValidationRecords); for(std::size_t i = 0; i &lt; numValidationRecords; ++i) { std::size_t index = randomIndices.back(); randomIndices.pop_back(); validationRecords[i] = index; } while(epochNumber &lt; numberEpochs) { // shuffle the indices so that they are pulled into each batch randomly each time std::random_shuffle(randomIndices.begin(),randomIndices.end()); DataType epochLoss = 0; std::tuple&lt;Layers...&gt; backupLayers = m_layers; for(std::size_t batchNumber = 0; batchNumber &lt; std::ceil(numTrainingRecords / batchSize); ++batchNumber) { std::array&lt;DataType,NumOutputs&gt; propagateError = {0}; std::size_t startIndex = batchNumber * batchSize; std::size_t endIndex = startIndex + batchSize; if(endIndex &gt; numTrainingRecords) endIndex = numTrainingRecords; DataType batchLoss = 0; for(std::size_t index = startIndex; index &lt; endIndex; ++index) { std::size_t row = randomIndices[index]; const std::array&lt;DataType,NumFeatures&gt;&amp; dataRow = trainingData[row]; const std::array&lt;DataType,NumOutputs&gt;&amp; desiredOutputRow = trainingOutput[row]; // Feed the values through to the output layer // use of "auto" is so this lambda can be used for all layers without // me needing to do any fucking around std::array&lt;DataType,NumOutputs&gt; finalOutput; for_each_get_final_output(m_layers, [](auto&amp; layer, auto o) { return layer.FeedForward(o); }, dataRow, finalOutput); DataType totalError = 0; for(std::size_t i = 0; i &lt; NumOutputs; ++i) { if(validationOptions.GetLossFunction() == LOSS_FUNCTION::MEAN_SQUARE_ERROR) totalError += std::pow(desiredOutputRow[i] - finalOutput[i],2.0); else if(validationOptions.GetLossFunction() == LOSS_FUNCTION::CROSS_ENTROPY) { if(NumOutputs == 1) { // binary cross entropy totalError += (desiredOutputRow[i] * std::log(1e-15 + finalOutput[i])); } else { // cross entropy } } } batchLoss += totalError; } batchLoss *= DataType(1) / (endIndex - startIndex); for(std::size_t i = 0; i &lt; NumOutputs; ++i) propagateError[i] = batchLoss; // update after every batch for_each_reverse(m_layers, [](auto&amp; layer, auto o) { auto errors = layer.Backpropagate(o); return errors; }, propagateError); // once backprop is finished, we can adjust all the weights for_each(m_layers, [&amp;](auto&amp; layer) { layer.CompleteBackprop(learningRate,momentum); }); epochLoss += batchLoss; } epochLoss *= DataType(1) / numTrainingRecords; lastEpochLoss.erase(lastEpochLoss.begin()); lastEpochLoss.push_back(epochLoss); DataType avgEpochLoss = 1.f * std::accumulate(lastEpochLoss.begin(),lastEpochLoss.end(),0.f) / (epochNumber &lt; validationOptions.GetEarlyStoppingNumEpochsAvg() ? epochNumber+1 : lastEpochLoss.size()); if(validationOptions.GetEarlyStoppingMetric() == ValidationOptions::METRIC::LOSS &amp;&amp; epochNumber &gt; numberEpochs * validationOptions.GetEarlyStoppingPatience() &amp;&amp; avgEpochLoss &gt; lastEpochLossAverage + validationOptions.GetEarlyStoppingDelta()) { // the loss average has decreased, so we should go back to the previous run and exit std::cout &lt;&lt; "Early exit Loss Avg \n" &lt;&lt; "Last Epoch: " &lt;&lt; lastEpochLossAverage &lt;&lt; "\n" &lt;&lt; "This Epoch: " &lt;&lt; avgEpochLoss &lt;&lt; std::endl; m_layers = backupLayers; break; } lastEpochLossAverage = avgEpochLoss; // check for the error against the reserved validation set std::size_t numCorrect = 0; for(std::size_t row = 0; row &lt; validationRecords.size(); ++row) { const std::array&lt;DataType,NumFeatures&gt;&amp; dataRow = trainingData[row]; const std::array&lt;DataType,NumOutputs&gt;&amp; desiredOutputRow = trainingOutput[row]; std::array&lt;DataType,NumOutputs&gt; finalOutput; for_each_get_final_output(m_layers, [](auto&amp; layer, auto o) { return layer.FeedForward(o); }, dataRow, finalOutput); bool correct = true; for(std::size_t i = 0; i &lt; NumOutputs; ++i) { if(validationOptions.GetOutputFilter()(finalOutput[i]) != desiredOutputRow[i]) correct = false; } if(correct) ++numCorrect; } DataType validationAccuracy = DataType(numCorrect) / numValidationRecords; lastValidationAccuracys.erase(lastValidationAccuracys.begin()); lastValidationAccuracys.push_back(validationAccuracy); DataType avgValidationAccuracy = std::accumulate(lastValidationAccuracys.begin(),lastValidationAccuracys.end(),0.f) / (epochNumber &lt; validationOptions.GetEarlyStoppingNumEpochsAvg() ? epochNumber+1 : lastValidationAccuracys.size()); if(validationOptions.GetEarlyStoppingMetric() == ValidationOptions::METRIC::ACCURACY &amp;&amp; epochNumber &gt; numberEpochs * validationOptions.GetEarlyStoppingPatience() &amp;&amp; avgValidationAccuracy &lt; lastValidationAccuraryAvg - validationOptions.GetEarlyStoppingDelta()) { // the accuracy has decreased, so we should go back to the previous run and exit std::cout &lt;&lt; "Early exit validation accuracy \n" &lt;&lt; "Last Epoch: " &lt;&lt; lastValidationAccuraryAvg &lt;&lt; "\n" &lt;&lt; "This Epoch: " &lt;&lt; avgValidationAccuracy &lt;&lt; std::endl; m_layers = backupLayers; break; } lastValidationAccuraryAvg = avgValidationAccuracy; outputStream &lt;&lt; epochNumber &lt;&lt; "," &lt;&lt; epochLoss &lt;&lt; "," &lt;&lt; avgEpochLoss &lt;&lt; "," &lt;&lt; validationAccuracy &lt;&lt; "," &lt;&lt; avgValidationAccuracy &lt;&lt; std::endl; learningRate -= learningRate / (numberEpochs-epochNumber); ++epochNumber; } } template&lt;std::size_t NumFeatures, std::size_t NumOutputs, std::size_t NumEvaluationRows&gt; void Evaluate(std::array&lt;std::array&lt;DataType,NumFeatures&gt;,NumEvaluationRows&gt; inputData, std::array&lt;std::array&lt;DataType,NumOutputs&gt;,NumEvaluationRows&gt; correctOutputs, DataType&amp; loss, DataType&amp; accuracy, ActivationFuncPtr outputFilter = [](const DataType&amp; x){return x;}) { loss = 0; std::size_t numCorrect = 0; for(std::size_t row = 0; row &lt; NumEvaluationRows; ++row) { const std::array&lt;DataType,NumFeatures&gt;&amp; dataRow = inputData[row]; const std::array&lt;DataType,NumOutputs&gt;&amp; outputRow = correctOutputs[row]; // Feed the values through to the output layer std::array&lt;DataType,NumOutputs&gt; finalOutput; for_each_get_final_output(m_layers, [](auto&amp; layer, auto o) { layer.FeedForward(o); return layer.GetOutputs(); }, dataRow, finalOutput); DataType thisLoss = 0; for(std::size_t i = 0; i &lt; NumOutputs; ++i) thisLoss += outputRow[i] - finalOutput[i]; loss += thisLoss * thisLoss; bool correct = true; for(std::size_t i = 0; i &lt; NumOutputs; ++i) { if(outputFilter(finalOutput[i]) != outputRow[i]) correct = false; } if(correct) ++numCorrect; } loss *= DataType(1) / NumEvaluationRows; accuracy = DataType(numCorrect) / NumEvaluationRows; } template&lt;std::size_t NumFeatures, std::size_t NumOutputs, std::size_t NumRecords&gt; void Predict(std::array&lt;std::array&lt;DataType,NumFeatures&gt;,NumRecords&gt; inputData, std::array&lt;std::array&lt;DataType,NumOutputs&gt;,NumRecords&gt;&amp; predictions, ActivationFuncPtr outputFilter = [](const DataType&amp; x){return x;}) { for(std::size_t row = 0; row &lt; NumRecords; ++row) { const std::array&lt;DataType,NumFeatures&gt;&amp; dataRow = inputData[row]; // Feed the values through to the output layer std::array&lt;DataType,NumOutputs&gt; finalOutput; for_each_get_final_output(m_layers, [](auto&amp; layer, auto o) { return layer.FeedForward(o); }, dataRow, finalOutput); for(std::size_t i = 0; i &lt; NumOutputs; ++i) predictions[row][i] = outputFilter(finalOutput[i]); } } protected: std::tuple&lt;Layers...&gt; m_layers; }; main() { std::vector&lt;std::vector&lt;CSVType&gt;&gt; trainingCSVData; /* load training CSV data */ std::vector&lt;std::vector&lt;CSVType&gt;&gt; testCSVData; /* load test CSV data */ std::cout &lt;&lt; std::fixed &lt;&lt; std::setprecision(80); std::ofstream file("error_out.csv", std::ios::out | std::ios::trunc); if(!file.is_open()) { std::cout &lt;&lt; "couldn't open file" &lt;&lt; std::endl; return 0; } file &lt;&lt; std::fixed &lt;&lt; std::setprecision(80); /* Features 1 pClass 1 2 pClass 2 3 pClass 3 4 Sex female 1, male 0 5 Age normalised between 0 and 1 age range 0 to 100 6 Number siblings between 0 and 1 num range 0 to 8 7 Number of parents / children num range 0 to 9 8 Ticket cost between 0 and 1 num range 0 to 512.3292 9 embarked S 10 embarked Q 11 embarked C */ std::array&lt;std::array&lt;DataType,29&gt;,891&gt; inputData; std::array&lt;std::array&lt;DataType,1&gt;,891&gt; desiredOutputs; /* ... data that loads the titanic data into a series of features. Either class labels or normalised values (like age) */ NeuralNetwork neuralNet{ FullyConnectedLayer&lt;29,256&gt;(), SigmoidActivation&lt;256&gt;(), FullyConnectedLayer&lt;256,1&gt;(), SigmoidActivation&lt;1&gt;() }; neuralNet.Fit(300, 1, 0.05, 0.25f, inputData, desiredOutputs, ValidationOptions().Accuracy(true,step05).Loss(true,LOSS_FUNCTION::CROSS_ENTROPY).Split(0.3), false, file); file.close(); return 0; } </code></pre> <p>The data used is from the titanic problem that you can <a href="https://www.kaggle.com/c/titanic/data" rel="nofollow noreferrer">download from Kaggle here</a>.</p> <p>The typical output file that's being generated is like this:</p> <pre><code>0,-4.91843843460083007812500000000000000000000000000000000000000000000000000000000000,-4.91843843460083007812500000000000000000000000000000000000000000000000000000000000,0.65168541669845581054687500000000000000000000000000000000000000000000000000000000,0.65168541669845581054687500000000000000000000000000000000000000000000000000000000 1,-6.14257431030273437500000000000000000000000000000000000000000000000000000000000000,-6.14257431030273437500000000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 2,-6.43130302429199218750000000000000000000000000000000000000000000000000000000000000,-6.43130302429199218750000000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 3,-6.58864736557006835937500000000000000000000000000000000000000000000000000000000000,-6.58864736557006835937500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 4,-6.70884752273559570312500000000000000000000000000000000000000000000000000000000000,-6.70884752273559570312500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 5,-6.78206682205200195312500000000000000000000000000000000000000000000000000000000000,-6.78206682205200195312500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 6,-6.86832284927368164062500000000000000000000000000000000000000000000000000000000000,-6.86832284927368164062500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 7,-6.92110681533813476562500000000000000000000000000000000000000000000000000000000000,-6.92110681533813476562500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 8,-6.96584081649780273437500000000000000000000000000000000000000000000000000000000000,-6.96584081649780273437500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 9,-7.02414274215698242187500000000000000000000000000000000000000000000000000000000000,-7.02414274215698242187500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 10,-7.06421041488647460937500000000000000000000000000000000000000000000000000000000000,-7.06421041488647460937500000000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000,0.65543073415756225585937500000000000000000000000000000000000000000000000000000000 </code></pre> <p>(shortened for space)</p> <p>This was previously working when the error I fed back through backprop was just the difference between the correct result and the prediction. <a href="https://www.reddit.com/r/learnmachinelearning/comments/dixyiy/i_think_ive_got_some_elements_of_neural_networks/" rel="nofollow noreferrer">But I've since been told that I should be propagating back the Loss Functions error</a>, which I then implemented as Binary Cross Entropy.</p> <p>So either:</p> <ol> <li>I should not feed back the error from the loss function</li> <li>I am calculating the loss incorrectly</li> <li>My back propagation code is wrong</li> <li>I've got something horrible happening in my validation loop</li> </ol> Answer: <p>This is a guess, as I am not reading all that code!</p> <blockquote> <p>This was previously working when the error I fed back through backprop was just the difference between the correct result and the prediction. But I've since been told that I should be propagating back the Loss Functions error, which I then implemented as Binary Cross Entropy.</p> </blockquote> <p>You may have been right before, and the advice you received wrong. Sort of.</p> <p>Backpropagation does not feed back the error value directly. It works exclusively with <em>gradients</em> of the error. So you typically start with a gradient value based on the objective function. </p> <p>If you backprop each function in the network a single step at a time, then you would start with <span class="math-container">$\nabla_{\hat{y}}\mathcal{L}$</span>, the gradient of the loss function with respect to the estimated values (i.e. output of the NN). Then from that you could calculate <span class="math-container">$\nabla_{z}\mathcal{L}$</span>, which is the gradient of the loss function with respect to the pre-activation values of the output layer.</p> <p>However, it is possible to combine steps analytically, and really common to start with the first gradient being <span class="math-container">$\nabla_{z}\mathcal{L}$</span>. That's because these pre-activation values are what you use to then calculate <span class="math-container">$\nabla_{W}\mathcal{L}$</span> and <span class="math-container">$\nabla_{b}\mathcal{L}$</span> - the gradients with respect to the layer's weights and biases, plus also to calculate <span class="math-container">$\nabla_{z'}\mathcal{L}$</span> - the gradients with respect to pre-activation values of the previous layer.</p> <p>Either way, once you have <span class="math-container">$\nabla_{z}\mathcal{L}$</span> for the output layer you can just run back though each layer in turn, repeating the same calcuation steps again and again. It is this repetition over each layer that looks like classic backprop in code.</p> <p>Assuming your neural network outputs a single value, the probablility of survival in the case of this dataset:</p> <ul> <li><p>Your objective/loss function for binary classification <em>should</em> be Binary Cross Entropy.</p></li> <li><p>Your output layer should have a sigmoid activation function.</p></li> </ul> <p>If you take the gradient of the loss function and backpropagate it throught that output layer's activation function, you end up with a starting delta <span class="math-container">$\nabla_{z} \mathcal{L}$</span> i.e. the gradient of the loss function with respect to the pre-activation value of the first layer. This is a nice place to start the recursive backprop code.</p> <p>The value of this gradient is mathematically, per item:</p> <p><span class="math-container">$$\nabla_{z} \mathcal{L} = \hat{y}_i - y_i$$</span> </p> <p>i.e. the difference the neural network estimate and the ground truth value. It takes this value because complex terms in the gradient of the loss function and the sigmoid activation function cancel out exactly. This is one reason why you often see sigmoid activation used with binary cross entropy - it is very convenient that the combination simplifies the gradient like this. You need to backpropagate each data point separately, and average the gradients for each batch/minibatch (actually you don't need to take this mean value, but doing so means that you don't need to adjust your learning rate as much to account for the number of items being processed per update step).</p> <p>It appears to of worked for you.</p> <p>Whether or not you were accidentally correct depends on whether you were getting an estimate for <span class="math-container">$\nabla_{z}\mathcal{L}$</span> to start your backprop routine, or <span class="math-container">$\nabla_{\hat{y}}\mathcal{L}$</span>. I cannot find what that assumption is in your code, but the fact that it worked before and does not now suggests that you may of been correct, even though you may not of fully understood the maths.</p>
https://ai.stackexchange.com/questions/15970/why-is-my-neural-network-giving-me-wildly-incorrect-error-and-not-changing-accur
Question: <p>I was wanting to add a maximum in my neural network, but this seems a bad thing to do since it kills the gradients to all but one of the inputs.</p> <p>Is there some kind of &quot;weighted maximum&quot; that allows the gradients to backpropagate?</p> <p>Edit: I had a two dimensional tensor (correlation matrix) I wanted to reduce to one dimension.</p> Answer: <p>The maximum function is not smooth, since it's first derivative is not continuous.</p> <p>Having non-smooth functions is generally a bad thing for neural networks, since they don't work nicely with gradient decent.</p> <p>So what you want is a smooth approximation to these functions.</p> <p>Logsumexp is the smooth approximation to the maximum function and so it is what you should use in a neural network, just like softmax is a smooth approximation to the argmax <a href="https://en.wikipedia.org/wiki/LogSumExp" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/LogSumExp</a></p>
https://ai.stackexchange.com/questions/35494/is-there-some-kind-of-weighted-maximum-that-allows-the-gradients-to-backpropag
Question: <p>I have a neural network that is composed of an input layer, two hidden layers and an output layer. The topology is [151, 200, 100, 1] I am using ReLU activation function on the neurons that are in the hidden layers and no activation function on the neuron that is in the output layer. I am wondering if when calculating the delta value of the neuron in the output layer, I should be using a derivative or if I should just subtract the expected output? Here I will put my line of code that this question concerns:</p> <pre><code>this.deltas[this.NN.length-2][0] = this.NN[this.NN.length-1][0] - expected; //In forward propagation this neuron has no activation function. </code></pre> Answer: <p>Having no activation function means your activation function is the identity, namely <span class="math-container">$g(z)=z$</span>.</p> <p>Therefore, any derivative of <span class="math-container">$g(z)$</span> wrt to a parameter is simply the corresponding derivative of <span class="math-container">$z$</span>, with no extra factor.</p> <p>You would get the same result if you include the derivative, as it is multiplying by <span class="math-container">$1$</span>.</p>
https://ai.stackexchange.com/questions/36594/in-a-neural-networks-neuron-that-has-no-activation-function-to-calculate-the-d
Question: <p>I am working on an implementation of the back propagation algorithm. What I have implemented so far seems working but I can't be sure that the algorithm is well implemented, here is what I have noticed during training test of my network:</p> <p>Specification of the implementation:</p> <ul> <li>A data set containing almost 100000 raw containing (3 variable as input, the sinus of the sum of those three variables as expected output).</li> <li>The network does have 7 layers, all the layers use the sigmoid activation function</li> </ul> <p>When I run the back propagation training process:</p> <ul> <li>The minimum of costs of the error is found at the fourth iteration (<strong>The minimum cost of error is 140, is it normal? I was expecting much less than that</strong>)</li> <li>After the fourth iteration the costs of the error start increasing (<strong>I don't know if it is normal or not?</strong>)</li> </ul> Answer: <p>Actually the implementation was correct, </p> <p>The source of the problem that causes a big error and really slow learning was the architecture of the neural network it self, the ANN has 7 hidden layers which causes the vanishing gradient problem.</p> <p>When I have decreased the ANN layers to 3 the cost of error was widely reduced besides of that the learning process was faster.</p> <p>Another common solution is to use RELU or ELU or SELU in the hidden layers of the neural network instead of the sigmoid function</p>
https://ai.stackexchange.com/questions/2727/how-to-test-if-my-implementation-of-back-propagation-neural-network-is-correct
Question: <p>I'm relatively new to neural networks and was wondering what an implementation of <a href="https://www.researchgate.net/profile/Bing_Zhao23/publication/271546169_Study_on_NNPID-based_adaptive_control_for_electro-optical_gyro_stabilized_platform/links/56e745f408ae438aab881bab.pdf" rel="noreferrer">this paper</a> would look like. More specifically, how are the correct values of Kp, Ki, and Kd determined at run time so it can be back propagated?</p> Answer: <p>In the paper there is a diagram of the network showing how there are 3 outputs which share features but have their own set of associated weights. Back propagation works by only looking at one output at a time. <a href="https://i.sstatic.net/b1ywu.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/b1ywu.jpg" alt="Network Architecture"></a></p>
https://ai.stackexchange.com/questions/3971/what-would-an-implementation-of-this-neural-network-look-like
Question: <p>I'm wondering if I can visualize the backprop process as follows (please excuse me if I have written something terrible wrong). If the loss function <span class="math-container">$L$</span> on a neural network represents the function has the form <span class="math-container">$$L = f(g(h(\dots u(v(\dots))))$$</span> then we can visualize the derivative of <span class="math-container">$L$</span> wrt the <span class="math-container">$i$</span>th function <span class="math-container">$v$</span> as <span class="math-container">$$\frac{\partial L}{\partial v} = \frac{\partial f}{\partial g}\frac{\partial g}{\partial h}\dots\frac{\partial u}{\partial v}.$$</span></p> <p>Am I able to view all neural networks as having a loss function of the form of <span class="math-container">$L$</span> given above? That is, am I correct in saying that any neural network is just a function composition and that I can write the partial derivative wrt any parameter as written above (I know I took the partial with respect to the function <span class="math-container">$v$</span>). </p> <p>Thanks</p> Answer: <p>Yes, a neural network plus loss function can be viewed as a function composition as you have written, and back propagation is just the chain function repeated. Your equations <span class="math-container">$L = f(g(h(\dots u(v(\dots))))$</span> and <span class="math-container">$\frac{\partial L}{\partial v} = \frac{\partial f}{\partial g}\frac{\partial g}{\partial h}\dots\frac{\partial u}{\partial v}$</span> are useful for high level intuition.</p> <p>At some point you need to look at the actual forms of the functions, and that introduces a bit more complexity. For instance, the loss function for a mini-batch can be expressed in terms of the output. This is the equivalent of <span class="math-container">$L = f(g)$</span> for a batch or mini-batch with mean squared error loss, where I am using <span class="math-container">$J$</span> (for cost) in place of <span class="math-container">$L$</span> and the output of the neural network <span class="math-container">$\hat{y}$</span> in place of <span class="math-container">$g$</span>:</p> <p><span class="math-container">$$J = \frac{1}{2N}\sum_{i=1}^{N}(\hat{y}_i - y_i)^2$$</span></p> <p>The gradient of <span class="math-container">$J$</span> with respect to <span class="math-container">$\hat{y}$</span> is equivalent to your first part <span class="math-container">$\frac{\partial f}{\partial g}$</span>:</p> <p><span class="math-container">$$\nabla_{\hat{y}} J = \frac{1}{N}\sum_{i=1}^{N}(\hat{y}_i - y_i)$$</span></p> <p>Many of the functions in a neural network involve sums over terms. They can be expressed as vector and matrix operations, which can make them look simpler, but you still need to have code somewhere that works through all the elements.</p> <p>There is one thing that the function composition view does not show well. The gradient you want to calculate is <span class="math-container">$\nabla_{\theta} J$</span>, where <span class="math-container">$\theta$</span> represents all the <em>parameters</em> of the neural network (weights and biases). The parameters in each layer are end points of back propagation - they are not functions of anything else, and the chain rule has to stop with them. That means you have a series of "dead ends" - or possibly another way of thinking about it would be that your <span class="math-container">$\frac{\partial L}{\partial v} = \frac{\partial f}{\partial g}\frac{\partial g}{\partial h}\dots\frac{\partial u}{\partial v}$</span> is the "trunk" of the algorithm that links layers together, and every couple of steps there is a "branch" to calculate the gradient of the parameters that you want to change.</p> <p>More concretely, if you have weight parameters in each layer noted as <span class="math-container">$W^{(n)}$</span>, and two functions for each layer (the sum over weights times inputs, and an activation function) then your example ends up looking like this progression:</p> <p><span class="math-container">$$\frac{\partial L}{\partial W^{(n)}} = \frac{\partial f}{\partial g}\frac{\partial g}{\partial h}\frac{\partial h}{\partial W^{(n)}}$$</span></p> <p><span class="math-container">$$\frac{\partial L}{\partial W^{(n-1)}} = \frac{\partial f}{\partial g}\frac{\partial g}{\partial h}\frac{\partial h}{\partial i}\frac{\partial i}{\partial j} \frac{\partial j}{\partial W^{(n-1)}}$$</span></p> <p><span class="math-container">$$\frac{\partial L}{\partial W^{(n-2)}} = \frac{\partial f}{\partial g}\frac{\partial g}{\partial h}\frac{\partial h}{\partial i}\frac{\partial i}{\partial j}\frac{\partial j}{\partial k}\frac{\partial k}{\partial l} \frac{\partial l}{\partial W^{(n-2)}}$$</span></p> <p>. . . this is the same idea but showing the goal of calculating <span class="math-container">$\nabla_{W} L$</span> which doesn't fit into a <em>single</em> chain of gradients. Notice the last term on each line does not appear in the next line. However, you can keep all the terms prior to that and re-use them in the next line - this matches the layer-by-layer calculations in many implementations of back propagation.</p>
https://ai.stackexchange.com/questions/9190/am-i-able-to-visualize-the-differentiation-in-backprop-as-follows
Question: <p>I'm developing my first neural network, using the well known MNIST database of handwritten digit. I want the NN to be able to classify a number from 0 to 9 given an image.</p> <p>My neural network consists of three layers: the input layer (784 neurons, each one for every pixel of the digit), a hidden layer of 30 neurons (it could also be 100 or 50, but I'm not too worried about hyperparameter tuning yet), and the output layer, 10 neurons, each one representing the activation for every digit. That gives to me two weight matrices: one of 30x724 and a second one of 10x30.</p> <p>I know and understand the theory behind back propagation, optimization and the mathematical formulas behind that, that's not a problem as such. I can optimize the weights for the second matrix of weights, and the cost is indeed being reduced over time. But I'm not able to keep propagating that back because of the matrix structure.</p> <p>Knowing that I have find the derivative of the cost w.r.t. the weights:</p> <pre><code>d(cost) / d(w) = d(cost) / d(f(z)) * d(f(z)) / d(z) * d(z) / d(w) </code></pre> <p>(Being <code>f</code> the activation function and <code>z</code> the dot product plus the bias of a neuron)</p> <p>So I'm in the rightmost layer, with an output array of 10 elements. <code>d(cost) / d(f(z))</code> is the subtraction of the observed an predicted values. I can multiply that by <code>d(f(z)) / d(z)</code>, which is just <code>f'(z)</code> of the rightmost layer, also an unidimensional vector of 10 elements, having now d(cost) / d(z) calculated. Then, <code>d(z)/d(w)</code> is just the input to that layer, i.e. the output of the previous one, which is a vector of 30 elements. I figured that I can transpose d(cost) / <code>d(z)</code> so that <code>T( d(cost) / d(z) ) * d(z) / d(w)</code> gives me a matrix of (10, 30), which makes sense because it matches with the dimension of the rightmost weight matrix.</p> <p>But then I get stuck. The dimension of <code>d(cost) / d(f(z))</code> is (1, 10), for <code>d(f(z)) / d(z)</code> is (1, 30) and for <code>d(z) / d(w)</code> is (1, 784). I don't know how to come up with a result for this.</p> <p>This is what I've coded so far. The incomplete part is the <code>_propagate_back</code> method. I'm not caring about the biases yet because I'm just stuck with the weights and first I want to figure this out. </p> <pre><code>import random from typing import List, Tuple import numpy as np from matplotlib import pyplot as plt import mnist_loader np.random.seed(42) NETWORK_LAYER_SIZES = [784, 30, 10] LEARNING_RATE = 0.05 BATCH_SIZE = 20 NUMBER_OF_EPOCHS = 5000 def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_der(x): return sigmoid(x) * (1 - sigmoid(x)) class Layer: def __init__(self, input_size: int, output_size: int): self.weights = np.random.uniform(-1, 1, [output_size, input_size]) self.biases = np.random.uniform(-1, 1, [output_size]) self.z = np.zeros(output_size) self.a = np.zeros(output_size) self.dz = np.zeros(output_size) def feed_forward(self, input_data: np.ndarray): input_data_t = np.atleast_2d(input_data).T dot_product = self.weights.dot(input_data_t).T[0] self.z = dot_product + self.biases self.a = sigmoid(self.z) self.dz = sigmoid_der(self.z) class Network: def __init__(self, layer_sizes: List[int], X_train: np.ndarray, y_train: np.ndarray): self.layers = [ Layer(input_size, output_size) for input_size, output_size in zip(layer_sizes[0:], layer_sizes[1:]) ] self.X_train = X_train self.y_train = y_train @property def predicted(self) -&gt; np.ndarray: return self.layers[-1].a def _normalize_y(self, y: int) -&gt; np.ndarray: output_layer_size = len(self.predicted) normalized_y = np.zeros(output_layer_size) normalized_y[y] = 1. return normalized_y def _calculate_cost(self, y_observed: np.ndarray) -&gt; int: y_observed = self._normalize_y(y_observed) y_predicted = self.layers[-1].a squared_difference = (y_predicted - y_observed) ** 2 return np.sum(squared_difference) def _get_training_batches(self, X_train: np.ndarray, y_train: np.ndarray) -&gt; Tuple[np.ndarray, np.ndarray]: train_batch_indexes = random.sample(range(len(X_train)), BATCH_SIZE) return X_train[train_batch_indexes], y_train[train_batch_indexes] def _feed_forward(self, input_data: np.ndarray): for layer in self.layers: layer.feed_forward(input_data) input_data = layer.a def _propagate_back(self, X: np.ndarray, y_observed: int): """ der(cost) / der(weight) = der(cost) / der(predicted) * der(predicted) / der(z) * der(z) / der(weight) """ y_observed = self._normalize_y(y_observed) d_cost_d_pred = self.predicted - y_observed hidden_layer = self.layers[0] output_layer = self.layers[1] # Output layer weights d_pred_d_z = output_layer.dz d_z_d_weight = hidden_layer.a # Input to the current layer, i.e. the output from the previous one d_cost_d_z = d_cost_d_pred * d_pred_d_z d_cost_d_weight = np.atleast_2d(d_cost_d_z).T * np.atleast_2d(d_z_d_weight) output_layer.weights -= LEARNING_RATE * d_cost_d_weight # Hidden layer weights d_pred_d_z = hidden_layer.dz d_z_d_weight = X # ... def train(self, X_train: np.ndarray, y_train: np.ndarray): X_train_batch, y_train_batch = self._get_training_batches(X_train, y_train) cost_over_epoch = [] for epoch_number in range(NUMBER_OF_EPOCHS): X_train_batch, y_train_batch = self._get_training_batches(X_train, y_train) cost = 0 for X_sample, y_observed in zip(X_train_batch, y_train_batch): self._feed_forward(X_sample) cost += self._calculate_cost(y_observed) self._propagate_back(X_sample, y_observed) cost_over_epoch.append(cost / BATCH_SIZE) plt.plot(cost_over_epoch) plt.ylabel('Cost') plt.xlabel('Epoch') plt.savefig('cost_over_epoch.png') training_data, validation_data, test_data = mnist_loader.load_data() X_train, y_train = training_data[0], training_data[1] network = Network(NETWORK_LAYER_SIZES, training_data[0], training_data[1]) network.train(X_train, y_train) </code></pre> <p>This is the code for <code>mnist_loader</code>, in case someone wanted to reproduce the example:</p> <pre><code>import pickle import gzip def load_data(): f = gzip.open('data/mnist.pkl.gz', 'rb') training_data, validation_data, test_data = pickle.load(f, encoding='latin-1') f.close() return training_data, validation_data, test_data </code></pre> Answer: <p>I'm not familiar with python I'm afraid, but I'll give a go at presenting some of the maths...</p> <p>In order to perform the <strong>back propagation</strong> using matrices, matrix <a href="https://en.wikipedia.org/wiki/Transpose" rel="nofollow noreferrer">transpose</a> is used for different sized layers. Also note that when using matrices for this, we need to distinguish different types of matrix multiplication, namely matrix <a href="https://en.wikipedia.org/wiki/Matrix_multiplication" rel="nofollow noreferrer">product</a>, and the <a href="https://en.wikipedia.org/wiki/Hadamard_product_(matrices)" rel="nofollow noreferrer">Hadamard product</a> which operates differently (the latter of which is denoted by a circle with a dot in the centre).</p> <p>Note the <strong>back propagation</strong> formulas:</p> <p>(EQ1) <span class="math-container">\begin{equation*}\delta ^{l} = (w^{l+1})^{T} \delta ^{l+1} \odot \sigma {}' (z ^{l})\end{equation*}</span></p> <p>(EQ2) <span class="math-container">\begin{equation*}\frac{\partial E}{\partial w}=a^{l-1}\delta ^{l}\end{equation*}</span></p> <p>As you can see the transpose of the weight matrix is used to multiply against the delta of the layer. </p> <p>As an example, consider a simple network with an input layer of 3 neurons, and an output layer of 2 neurons.</p> <p>The <em>unactivated</em> <strong>feed forward</strong> output is given by...</p> <p><span class="math-container">\begin{equation*}z_{1} = h_{1} w_{1} + h_{2} w_{3} + h_{3} w_{5}\end{equation*}</span> <span class="math-container">\begin{equation*}z_{2} = h_{1} w_{2} + h_{2} w_{4} + h_{3} w_{6}\end{equation*}</span></p> <p>Which can be represented in matrix form as...</p> <p><span class="math-container">\begin{equation*} z = \begin{bmatrix}z_{1}\\z_{2}\end{bmatrix} = \begin{bmatrix}h_{1} w_{1} + h_{2} w_{3} + h_{3} w_{5}\\h_{1} w_{2} + h_{2} w_{4} + h_{3} w_{6}\end{bmatrix} \end{equation*}</span></p> <p>(EQ3) <span class="math-container">\begin{equation*} = \begin{bmatrix}w_{1}&amp;w_{3}&amp;w_{5}\\w_{2}&amp;w_{4}&amp;w_{6}\end{bmatrix} \begin{bmatrix}h_{1}\\h_{2}\\h_{3}\end{bmatrix} \end{equation*}</span></p> <p>Which allows us to <strong>forward propagate</strong> from a layer of 3 neurons, to a layer of 2 neurons (via matrix multiplication).</p> <p>For the <strong>back propagation</strong>, we need the <em>error</em> of each neruon...</p> <p>N.B <em>Cost</em> is a metric used to denote the <em>error</em> of the entire network and depends on your cost function. It is usually the mean of the sum of the <em>errors</em> of each nuerons, but of course depends on your cost function used.</p> <p>e.g for <a href="https://en.wikipedia.org/wiki/Mean_squared_error" rel="nofollow noreferrer">MSE</a> is... <span class="math-container">\begin{equation*} C_{MSE}=\frac{1}{N}\sum (o_{n}-t_{n})^{2} \end{equation*}</span></p> <p>We are interested in the derivative of the <em>error</em> for each neuron (not the <em>cost</em>), which by the chain rule is...</p> <p><span class="math-container">\begin{equation*} \frac{\partial E}{\partial z} = \frac{\partial E}{\partial o} \frac{\partial o}{\partial z} \end{equation*}</span></p> <p>Expressed in matrix form...</p> <p><span class="math-container">\begin{equation*} \frac{\partial E}{\partial z} = \begin{bmatrix} \frac{\partial E}{\partial z_{1}}\\ \frac{\partial E}{\partial z_{2}} \end{bmatrix} = \begin{bmatrix} \frac{\partial E}{\partial o_{1}} \frac{\partial o_{1}}{\partial z_{1}}\\ \frac{\partial E}{\partial o_{2}} \frac{\partial o_{2}}{\partial z_{2}} \end{bmatrix} \end{equation*}</span></p> <p>(EQ4) <span class="math-container">\begin{equation*} = \begin{bmatrix} \frac{\partial E}{\partial o_{1}} \\ \frac{\partial E}{\partial o_{2}} \end{bmatrix} \odot \begin{bmatrix} \frac{\partial o_{1}}{\partial z_{1}} \\ \frac{\partial o_{2}}{\partial z_{2}} \end{bmatrix} \end{equation*}</span></p> <p>Note the use of the hadamard product here. In fact, given these are simply vectors, vector dot product would work, but hadamard is used as this becomes important later when using this expression with the matrix equations as we want to distinguish the use of hadamard product as opposed to matrix product.</p> <p>We start off with our first delta error, which for the first layer <strong>back propagation</strong> is...</p> <p><span class="math-container">\begin{equation*} \delta ^{L} = \frac{\partial E}{\partial o} \end{equation*}</span></p> <p>And then we want to calculate the next delta error using the formula (EQ1)...</p> <p><span class="math-container">\begin{equation*} \delta ^{l} = (w^{l+1})^{T} \delta ^{l+1} \odot \sigma {}' (z ^{l}) = \frac{\partial E}{\partial h} \end{equation*}</span></p> <p>Explicitly, the equations are...</p> <p><span class="math-container">\begin{equation*}\frac{\partial E}{\partial h_{1}}=\frac{\partial E}{\partial z_{1}} w_{1} + \frac{\partial E}{\partial z_{2}} w_{2}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial h_{2}}=\frac{\partial E}{\partial z_{1}} w_{3} + \frac{\partial E}{\partial z_{2}} w_{4}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial h_{3}}=\frac{\partial E}{\partial z_{1}} w_{5} + \frac{\partial E}{\partial z_{2}} w_{6}\end{equation*}</span></p> <p>Also given the transpose of the weight matrix which allows us to <strong>back propagate</strong> from a layer of 2 neurons to a layer of 3 neurons (via matrix multiplication) ...</p> <p><span class="math-container">\begin{equation*} \left (w \right )^{T} = \left ( \begin{bmatrix} w_{1} &amp; w_{3} &amp; w_{5}\\ w_{2} &amp; w_{4} &amp; w_{6} \end{bmatrix} \right )^{T} = \begin{bmatrix} w_{1} &amp; w_{2}\\ w_{3} &amp; w_{4}\\ w_{5} &amp; w_{6} \end{bmatrix} \end{equation*}</span></p> <p>So in a similar way to how we represented the forward pass (EQ3), this can be represented in matrix form...</p> <p><span class="math-container">\begin{equation*} \frac{\partial E}{\partial h} = \begin{bmatrix} \frac{\partial E}{\partial h_{1}}\\ \frac{\partial E}{\partial h_{2}}\\ \frac{\partial E}{\partial h_{3}} \end{bmatrix} = \begin{bmatrix} \frac{\partial E}{\partial z_{1}} w_{1} + \frac{\partial E}{\partial z_{2}} w_{2} \\ \frac{\partial E}{\partial z_{1}} w_{3} + \frac{\partial E}{\partial z_{2}} w_{4} \\ \frac{\partial E}{\partial z_{1}} w_{5} + \frac{\partial E}{\partial z_{2}} w_{6} \end{bmatrix} \end{equation*}</span></p> <p>(EQ5) <span class="math-container">\begin{equation*} = \begin{bmatrix} w_{1} &amp; w_{2}\\ w_{3} &amp; w_{4}\\ w_{5} &amp; w_{6} \end{bmatrix} \begin{bmatrix} \frac{\partial E}{\partial z_{1}} \\ \frac{\partial E}{\partial z_{2}} \end{bmatrix} \end{equation*}</span></p> <p>And then plugging the hadamard version of the delta (EQ4) into this, we get...</p> <p><span class="math-container">\begin{equation*} \begin{bmatrix} w_{1} &amp; w_{2}\\ w_{3} &amp; w_{4}\\ w_{5} &amp; w_{6} \end{bmatrix} \begin{bmatrix} \frac{\partial E}{\partial o_{1}} \\ \frac{\partial E}{\partial o_{2}} \end{bmatrix} \odot \begin{bmatrix} \frac{\partial o_{1}}{\partial z_{1}} \\ \frac{\partial o_{2}}{\partial z_{2}} \end{bmatrix} \end{equation*}</span></p> <p>aka (EQ1) ...</p> <p><span class="math-container">\begin{equation*}(w^{l+1})^{T} \delta ^{l+1} \odot \sigma {}' (z ^{l})\end{equation*}</span></p> <p>And thus we have <strong>back propagated</strong> from a layer of 2 neurons, to a layer of 3 neurons (via matrix multiplication) thanks to transpose.</p> <p>For completeness... the other aspect of the back propagation to uses matrices, is the delta weight matrix....</p> <p><span class="math-container">\begin{equation*} \frac{\partial E}{\partial w} = \begin{bmatrix} \frac{\partial E}{\partial w_{1}} &amp; \frac{\partial E}{\partial w_{3}} &amp; \frac{\partial E}{\partial w_{5}}\\ \frac{\partial E}{\partial w_{2}} &amp; \frac{\partial E}{\partial w_{4}} &amp; \frac{\partial E}{\partial w_{6}} \end{bmatrix} \end{equation*}</span></p> <p>As mentioned before, you need to cache weight matrix and the activated layer output of a forward pass of the network.</p> <p>In a similar vein to (EQ3)...</p> <p>We explcitily have the equations...</p> <p><span class="math-container">\begin{equation*}\frac{\partial E}{\partial w_{1}}=\frac{\partial E}{\partial z_{1}}h_{1}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial w_{2}}=\frac{\partial E}{\partial z_{2}}h_{1}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial w_{3}}=\frac{\partial E}{\partial z_{1}}h_{2}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial w_{4}}=\frac{\partial E}{\partial z_{2}}h_{2}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial w_{5}}=\frac{\partial E}{\partial z_{1}}h_{3}\end{equation*}</span> <span class="math-container">\begin{equation*}\frac{\partial E}{\partial w_{6}}=\frac{\partial E}{\partial z_{2}}h_{3}\end{equation*}</span></p> <p>Note the use of h1, h2 and h3, which are the activated outputs of the previous layer.. (or in the case of our example these are the inputs).</p> <p>Which we represent in matrix form...</p> <p><span class="math-container">\begin{equation*} \frac{\partial E}{\partial w} = \begin{bmatrix} \frac{\partial E}{\partial z_{1}}h_{1} &amp; \frac{\partial E}{\partial z_{1}}h_{2} &amp; \frac{\partial E}{\partial z_{1}}h_{3}\\ \frac{\partial E}{\partial z_{2}}h_{1} &amp; \frac{\partial E}{\partial z_{2}}h_{2} &amp; \frac{\partial E}{\partial z_{2}}h_{3} \end{bmatrix} \end{equation*}</span> (EQ6) <span class="math-container">\begin{equation*} = \begin{bmatrix} \frac{\partial E}{\partial z_{1}} \\ \frac{\partial E}{\partial z_{2}} \end{bmatrix} \begin{bmatrix} h_{1} &amp; h_{2} &amp; h_{3} \end{bmatrix} \end{equation*}</span></p> <p>Which just so happens to be (EQ2) ...</p> <p><span class="math-container">\begin{equation*}\frac{\partial E}{\partial w}=\delta ^{l}a^{l-1}\end{equation*}</span></p> <p>:)</p> <p>Since the delta weight matrix and the original weight matrix are the same dimensions, it is trivia to apply the learning rate...</p> <p><span class="math-container">\begin{equation*} w = \begin{bmatrix} w_{1} - \alpha \frac{\partial E}{\partial w_{1}} &amp; w_{3} - \alpha \frac{\partial E}{\partial w_{3}} &amp; w_{5} - \alpha \frac{\partial E}{\partial w_{5}}\\ w_{2} - \alpha \frac{\partial E}{\partial w_{2}} &amp; w_{4} - \alpha \frac{\partial E}{\partial w_{4}} &amp; w_{6} - \alpha \frac{\partial E}{\partial w_{6}} \end{bmatrix} \end{equation*}</span></p> <p><span class="math-container">\begin{equation*} = \begin{bmatrix}w_{1}&amp;w_{3}&amp;w_{5}\\w_{2}&amp;w_{4}&amp;w_{6}\end{bmatrix} - \alpha \begin{bmatrix} \frac{\partial E}{\partial w_{1}} &amp; \frac{\partial E}{\partial w_{3}} &amp; \frac{\partial E}{\partial w_{5}}\\ \frac{\partial E}{\partial w_{2}} &amp; \frac{\partial E}{\partial w_{4}} &amp; \frac{\partial E}{\partial w_{6}} \end{bmatrix} \end{equation*}</span></p> <p><span class="math-container">\begin{equation*} = w - \alpha \frac{\partial E}{\partial w}\end{equation*}</span></p> <p>I'll omit the equations for the bias, as these are easy to put in and don't require any other equations other than the ones presented here. So in summary, the equations you want are (EQ3), (EQ5) and (EQ6) to use matrices, and the ability to change move between layers of differing number of neurons is the matrix transpose. Hope this helps, and let me know if you want me to expand on anything. </p> <p>It might be also important to note that you appear to be using MSE as the cost. This is perhaps not optimal for the MNIST data set which is a clasification. A better cost function to use would be <a href="https://www.google.com/search?client=firefox-b-d&amp;q=cross%20entropy" rel="nofollow noreferrer">cross entropy</a>.</p> <p>Happy propagating!</p>
https://ai.stackexchange.com/questions/20053/how-to-perform-back-propagation-with-different-sized-layers
Question: <p>I was reading a paper on alternatives to backpropagation as a learning algorithm in neural networks. In <a href="https://arxiv.org/pdf/1609.01596.pdf" rel="nofollow noreferrer">this paper</a>, the author talks about the disadvantages of backpropagation, and one of the disadvantages stated is that backpropagation requires symmetric weights and that's why it's not biologically plausible.</p> <p>What do symmetric weights mean and how does it make backpropagation biologically implausible?</p> Answer: <p>&quot;Symmetric weights&quot; means that the same weight value associated to a pair of nodes must be used during the forwards and backwards steps.</p> <p>The reason it makes back propagation biologically impossible in its naive formulation is that neurons fire electrical signals in only one direction, from the dendrite through the axon to other dendrites of other neurons. They do receive of course &quot;backwards&quot; feedback, but by other means, e.g. chemical neurotransmitters or other signals from other neurons, but these signals are very likely not of the same intensity as the signal emitted by the neurons themselves (i.e. no symmetry).</p>
https://ai.stackexchange.com/questions/35449/what-do-symmetric-weights-mean-and-how-does-it-make-backpropagation-biologically
Question: <p>I recently just finished programming a neural network in c#, and it seems like it's working. My question is if I'm doing it right. It's a very confusing process so I will explain.</p> <p>Basically every neuron in the network has a bias (except the first layer) and fully connected weights to the next. every neuron also has a <code>double[] desiredBias</code> which holds all the desired changes to the neuron for every iteration in a given mini batch. The same thing for the weights. So I start from the last layer, and from there I calculate the &quot;sensitivity&quot; you might say between the cost of a given neuron on that last layer and the bias, and i take note of it (put it into changes). Then for every weight connected to the layer behind, I also calculate the sensitivity for that one. And I keep doing that until I get to the second to first layer. And to take note of the <code>desiredChanges</code> for neurons not in the last layer, I use this array called &quot;<code>changes</code>&quot;. For the first layer it's basically just a list of all the derivatives of the activations (z) with respect to the actual activations (sigmoid(z)) respectively. After I shift to the layer behind, and behind, every time I do that, I create a new changes array, which is the size of the layer behind, and for each item in the previous changes array, I take the sum of all of them multiplied by the partial derivative of that same z-activation with respect to the previous layer's z activation. I do this for every neuron in the previous layer.</p> <p>after all of that I end up with for every neuron a list of desired changes to it's bias, and a list of lists which contain desired changes to the weights of each neuron. Then for each neuron (except for the first of course) I average together all of the biases and SUBTRACT it from the neuron's bias. I do the same thing for the weights.</p> <p>Is this the correct process to go through for exactly one batch of training data?</p> <p>here's my code:</p> <pre><code>using System; namespace NeuralNetwork { public class Functions { // Activation Functions public static double sigmoid(double x) { return 1 / (1 + Math.Pow(Math.E, -x)); } public static double ReLU(double x) { return Math.Max(0, x); } public static double Tanh(double x) { return Math.Tanh(x); } public static double Linear(double x) { return x; } // Derivatives public static double sigmoidDerivative(double x) { return sigmoid(x) * (1 - sigmoid(x)); } public static double ReLUDerivative(double x) { return (x &gt; 0) ? 1 : 0; } public static double TanhDerivative(double x) { return 1 - (Math.Pow(Tanh(x) * Tanh(x), 2)); } public static double LinearDerivative(double x) { return 1; } public enum ActFunction { Sigmoid, ReLU, Tanh, Linear } // Loss Functions public static double MSE(double[] outputs, double[] desired) { double sum = 0; for (int i = 0; i &lt; outputs.Length; i++) { sum += Math.Pow((outputs[i] - desired[i]), 2); } return sum / outputs.Length; } // Derivatives public static double[] MSEDerivative(double[] outputs, double[] desired) { double[] derivatives = new double[outputs.Length]; for (int i = 0; i &lt; outputs.Length; i++) { derivatives[i] = 2 * (outputs[i] - desired[i]); } return derivatives; } public enum LossFunction { MSE } } public class Neuron { public double activation = 0; public Functions.ActFunction activationFunction = Functions.ActFunction.Linear; public double bias; public double[] weights = new double[] {}; public int x; public int y; public Neuron[][] network; public double[] desiredBias; public double[][] desiredWeights; public void fire() { for (int i = 0; i &lt; network[x + 1].Length; i++) { Neuron next = network[x + 1][i]; next.activation += activation * weights[i]; } } public void activate() { double n_activation = activation + bias; switch(activationFunction) { case Functions.ActFunction.Sigmoid: activation = Functions.sigmoid(n_activation); break; case Functions.ActFunction.ReLU: activation = Functions.ReLU(n_activation); break; case Functions.ActFunction.Tanh: activation = Functions.Tanh(n_activation); break; case Functions.ActFunction.Linear: activation = Functions.Linear(n_activation); break; } } } public class Network { public Neuron[][] network; public double learningRate; public int iterations; public Functions.LossFunction lossFunction; public int trainingLength; public Network(int[] size, double _learningRate, int _iterations, int _trainingLength, Functions.LossFunction _lossFunction) { learningRate = _learningRate; iterations = _iterations; trainingLength = _trainingLength; lossFunction = _lossFunction; network = new Neuron[size.Length][]; for (int i = 0; i &lt; size.Length; i++) { network[i] = new Neuron[size[i]]; } for (int i = 0; i &lt; size.Length; i++) { for (int j = 0; j &lt; size[i]; j++) { network[i][j] = new Neuron(); } } for (int i = 0; i &lt; network.Length - 1; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; neuron.weights = new double[network[i + 1].Length]; neuron.desiredWeights = new double[neuron.weights.Length][]; // i would have put iterations right here but the compiler thinks otherwise for (int k = 0; k &lt; neuron.desiredWeights.Length; k++) { neuron.desiredWeights[k] = new double[trainingLength/iterations]; } } } for (int i = 1; i &lt; network.Length; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; neuron.desiredBias = new double[trainingLength/iterations]; } } } public void init() { Random rand = new Random(); for (int i = 0; i &lt; network.Length; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; neuron.x = i; neuron.y = j; neuron.network = network; if (i != 0) { neuron.bias = (rand.NextDouble() * 2) - 1; } if (i != network.Length - 1) { for (int k = 0; k &lt; network[neuron.x + 1].Length; k++) { neuron.weights[k] = (rand.NextDouble() * 20) - 1; } } } } } public void info() { Console.WriteLine(&quot;Here are the statistics for the network:\n&quot;); for (int i = 0; i &lt; network.Length; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; Console.WriteLine(&quot;Neuron &quot; + j + &quot; of layer &quot; + i); //Console.WriteLine(&quot;Activation: &quot; + neuron.activation); Console.WriteLine(&quot;Bias: &quot; + neuron.bias); Console.WriteLine(&quot;X and Y: &quot; + neuron.x + &quot;, &quot; + neuron.y); string weights = &quot;Weights: &quot;; foreach (double weight in neuron.weights) { weights += weight + &quot; &quot;; } Console.WriteLine(weights); Console.WriteLine(); } } Console.WriteLine(); } public double[] run(double[] inputs) { // initialize inputs for (int i = 0; i &lt; network[0].Length; i++) { network[0][i].activation = inputs[i]; } for (int i = 0; i &lt; network.Length - 1; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; neuron.fire(); } for (int j = 0; j &lt; network[i + 1].Length; j++) { Neuron neuron = network[i + 1][j]; neuron.activate(); } } // get outputs Neuron[] outputs = network[network.Length - 1]; double[] activations = new double[outputs.Length]; for (int i = 0; i &lt; outputs.Length; i++) { activations[i] = outputs[i].activation; } return activations; } public double iteration() { Random rand = new Random(); int iterationLength = trainingLength/iterations; double[] costs = new double[iterationLength]; // training for (int iter = 0; iter &lt; iterationLength; iter++) { double[] inputs = { (rand.NextDouble() ), ( rand.NextDouble() )}; double[] answers = { inputs[0] + inputs[1] }; double[] outputs = run(inputs); for (int i = 0; i &lt; network.Length; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; neuron.desiredBias = new double[iterationLength]; if (i == network.Length - 1) continue; neuron.desiredWeights = new double[network[i + 1].Length][]; for (int k = 0; k &lt; neuron.desiredWeights.Length; k++) { neuron.desiredWeights[k] = new double[iterationLength]; } } } double cost = 0; switch(lossFunction) { case Functions.LossFunction.MSE: cost = Functions.MSE(outputs, answers); break; } costs[iter] = cost; double[] changes = new double[network[network.Length - 1].Length]; switch(lossFunction) { case Functions.LossFunction.MSE: changes = Functions.MSEDerivative(outputs, answers); break; } for (int i = 0; i &lt; changes.Length; i++) { Neuron neuron = network[network.Length - 1][i]; double act = neuron.activation; switch(neuron.activationFunction) { case Functions.ActFunction.Sigmoid: changes[i] *= Functions.sigmoidDerivative(Math.Log(act / (1 - act))); break; case Functions.ActFunction.Linear: changes[i] *= Functions.LinearDerivative(act); break; } } for (int i = network.Length - 1; i &gt; 0; i--) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron bNeuron = network[i][j]; bNeuron.desiredBias[iter] += changes[j]; // bias partial derivative is always one for (int k = 0; k &lt; network[i - 1].Length; k++) { Neuron aNeuron = network[i - 1][k]; aNeuron.desiredWeights[bNeuron.y][iter] += aNeuron.weights[bNeuron.y] * changes[j]; // chain rule } } double[] holderChanges = changes; changes = new double[network[i - 1].Length]; for (int j = 0; j &lt; changes.Length; j++) { for (int k = 0; k &lt; holderChanges.Length; k++) { Neuron aNeuron = network[i - 1][j]; Neuron bNeuron = network[i][k]; switch(aNeuron.activationFunction) { case Functions.ActFunction.Sigmoid: double activation = aNeuron.activation; changes[j] += Functions.sigmoidDerivative(Math.Log(activation / 1 - activation)) * aNeuron.weights[bNeuron.y] * holderChanges[k]; break; case Functions.ActFunction.Linear: activation = aNeuron.activation; changes[j] += Functions.LinearDerivative(activation) * aNeuron.weights[bNeuron.y] * holderChanges[k]; break; } } } } // reset activations for (int i = 0; i &lt; network.Length; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; neuron.activation = 0; } } } // after everything we now actually add the desired changes // the weights for (int i = 0; i &lt; network.Length - 1; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; for (int k = 0; k &lt; neuron.desiredWeights.Length; k++) { double weightSum = 0; foreach (double weight in neuron.desiredWeights[k]) { weightSum += weight; } weightSum /= iterationLength; neuron.weights[k] -= learningRate * weightSum; } } } // the biases for (int i = 1; i &lt; network.Length; i++) { for (int j = 0; j &lt; network[i].Length; j++) { Neuron neuron = network[i][j]; double biasSum = 0; foreach (double bias in neuron.desiredBias) { biasSum += bias; } biasSum /= iterationLength; neuron.bias -= learningRate * biasSum; } } double netcost = 0; foreach (double cost in costs) { netcost += cost; } return netcost/costs.Length; } public void epoch(bool showInfo) { Console.WriteLine(&quot;Starting training...\n&quot;); for (int iter = 0; iter &lt; iterations; iter++) { double cost = iteration(); if (showInfo) info(); Console.WriteLine(&quot;Cost for iteration &quot; + iter + &quot;: &quot; + cost + &quot;\n&quot;); // reset desired for (int k = 0; k &lt; network.Length - 1; k++) { for (int l = 0; l &lt; network[k].Length; l++) { Neuron neuron = network[k][l]; for (int i = 0; i &lt; neuron.desiredWeights.Length; i++) { for (int j = 0; j &lt; neuron.desiredWeights[i].Length; j++) { neuron.desiredWeights[i][j] = 0; } } } } for (int k = 1; k &lt; network.Length; k++) { for (int l = 0; l &lt; network[k].Length; l++) { Neuron neuron = network[k][l]; for (int i = 0; i &lt; neuron.desiredBias.Length; i++) { neuron.desiredBias[i] = 0; } } } } Console.WriteLine(&quot;Training finished!\n&quot;); } public void prompt() { while(true) { Console.WriteLine(&quot;What would you like to do?&quot;); Console.WriteLine(&quot;Train, info, run or end?&quot;); string answer = Console.ReadLine(); if (answer.ToLower() == &quot;end&quot;) { Console.WriteLine(&quot;...&quot;); break; } switch(answer.ToLower()) { case &quot;info&quot;: Console.WriteLine(); info(); Console.WriteLine(); break; case &quot;run&quot;: double[] runanswer = new double[network[0].Length]; while (true) { try { for (int i = 0; i &lt; network[0].Length; i++) { Console.WriteLine(&quot;Enter input &quot; + i); runanswer[i] = Convert.ToDouble(Console.ReadLine()); } Console.WriteLine(&quot;Running...\n&quot;); double[] outputs = run(runanswer); string _string = &quot;&quot;; foreach (double output in outputs) { _string += output; } Console.WriteLine(&quot;Here were the outputs:&quot;); Console.WriteLine(_string + &quot;\n&quot;); break; } catch (FormatException exception) { Console.WriteLine(&quot;Only numbers!&quot;); continue; } } break; case &quot;train&quot;: int trainanswer = 0; int trainanswer2 = 0; double trainanswer3 = 0; while (true) { try { Console.WriteLine(&quot;Enter epoch length:&quot;); trainanswer = Convert.ToInt32(Console.ReadLine()); trainingLength = trainanswer; Console.WriteLine(&quot;\nEnter batch size:&quot;); trainanswer2 = Convert.ToInt32(Console.ReadLine()); iterations = trainanswer2; Console.WriteLine(&quot;\nEnter learning rate:&quot;); trainanswer3 = Convert.ToDouble(Console.ReadLine()); learningRate = trainanswer3; for (int i = 0; i &lt; trainanswer2; i++) { double cost = iteration(); Console.WriteLine(&quot;The cost was: &quot; + cost + &quot;\n&quot;); } break; } catch (FormatException exception) { Console.WriteLine(&quot;Only numbers!&quot;); continue; } } break; default: Console.WriteLine(&quot;Invalid command!\n&quot;); break; } } } } public class Run { public static void Main(string[] args) { Network brain = new Network(new int[] { 2, 1 }, .01, 50, 50, Functions.LossFunction.MSE); brain.init(); int i = 7; while (i &gt; 0) { brain.epoch(false); i--; } brain.prompt(); } } } </code></pre> <p>*** to clarify if you don't understand my question, I'm just asking if i'm implementing backpropagation correctly</p> Answer: <p>Unfortunately I highly doubt anyone is going to check your code or exact implementation as that is a very time consuming process. Luckily for you though, you don't need someone to check, you can check it yourself with <strong>gradient checking</strong>! The basic process is to manually calculate the exact gradient for every single parameter for an input by varying every parameter one at a time, then seeing how each changes your output. With a proper implementation of backpropagation, the gradients will match.</p> <p><a href="https://stackoverflow.com/a/47506918/9546874">Here's another question describing this process on stack overflow</a></p> <p>Note though that with ReLU the function is undefined at 0, and you will quickly see how this is a problem when you start doing grad checking. The gradients wont match if you try and check a parameter using the output of a ReLU function when the input to said ReLU is 0. I did some research on this a while ago when I had this problem, and I believe the consensus was to just ignore it</p>
https://ai.stackexchange.com/questions/37297/is-my-neural-network-working
Question: <p>When an LLM creates an output, it seemingly has no way to check if its output was valid. Therefore it wouldn't be able to back-propagate any changes to the weights is used to create that output.</p> <p>Right now, I suspect that all weight modification is done by training on input data, as that can (generally) be assumed to be human and valid.</p> <p>But perhaps it does have some way of checking if its output was good or not, and being modified based off of it. For instance, there is the thumb up and down button on ChatGPT which could be used for that.</p> <p>Do LLM's modify their neural weights based off of their own answers? If so, how?</p> Answer: <p>I will base my answer on GPT-2, as most LLMs are not too different in their architecture.</p> <p>The output of the transformer in an LLM is not text or tokens; it is a categorical distribution over the space of next possible tokens.</p> <p>To calculate loss of the transformer, you (commonly) take negative log likelihood. If the training data says the next token was <span class="math-container">$i$</span> and the transformer's output was a vector <span class="math-container">$v$</span>, then we have this loss. <span class="math-container">$$L = -\log(v_i)$$</span> Backpropagating this encourages the transformer to assign higher confidence to the correct token, according to data.</p> <p>Reagarding the 'thumbs up' feature of ChatGPT, this is probably an auxiliary loss. OpenAI is known to use Reinforcement Learning to tune ChatGPT, in addition to the negative log likelihood which would've been used during pre-training. How exactly this is calculated, we don't know; ChatGPT is closed source.</p>
https://ai.stackexchange.com/questions/41253/does-the-output-of-llms-affect-their-neural-weights
Question: <p>I'm currently working on constructing a neural network from scratch (in JavaScript). I'm in the middle of working on the backpropagation, but there's something I don't understand: how does the backprop algorithm know which weights to change or which paths to take? The way I did it, it always took all of the paths/weights and changed them all. So how does the algorithm know which paths to take, which weights to change, and whether to add or subtract X amount from said weight?</p> Answer: <p>@serali is correct, there are many resources to describe this process. I'm going to talk about it in a very general way.</p> <p><strong>Disclaimer</strong>: this is a work in progress, it is not yet complete.</p> <p><strong>Question</strong>:<br /> How do we know what weights to change in the network?</p> <p><strong>General Answer</strong>:<br /> This is a very good question. This is a key component of ML, and even small improvements there would make a huge difference for the overall community. There are gigawatt-hours of electricity spent using the current answers to this question.</p> <p>Training means you have an input that you want the network to transform into an output, and it means you have an output to compare it against.</p> <p>The difference between what it makes, and what it should make, the error, can be run in reverse through the network. As you go through that reverse run, you can get an error associated with each weight. if you move that error to zero, by changing the weight, then the network can be less bad.</p> <p><strong>Some variations</strong>:<br /> Here are some approaches for relating the per-weight errors to the new weights.</p> <p>Approaches:</p> <ul> <li>(sgd <a href="https://optimization.cbe.cornell.edu/index.php?title=Stochastic_gradient_descent" rel="nofollow noreferrer">link</a>) take just a few or one sample at random and compute the error, and then move weights in that direction, usually only a small percentage of it. The intention is that each new update occurs closer to the optimum, and works well in lower-noise cases.</li> <li>(conjugate gradient <a href="https://optimization.cbe.cornell.edu/index.php?title=Conjugate_gradient_methods" rel="nofollow noreferrer">link</a>, ) find a line along which to minimize, find the minimum, explore around that minimum to find a new direction for minimization. For quadratic problems (shaped like parabola) it gives good solutions quickly.</li> <li>(momentum <a href="https://optimization.cbe.cornell.edu/index.php?title=Momentum" rel="nofollow noreferrer">link</a>) take a running average of the last several weight changes, and do most of the movement in that direction</li> <li>(regularization <a href="https://medium.com/intelligentmachines/convolutional-neural-network-and-regularization-techniques-with-tensorflow-and-keras-5a09e6e65dc7" rel="nofollow noreferrer">link</a>) penalize weights that are too high, push back against learning them, tries to keep weights in smaller subset of the space unless pushed there by the data.</li> <li>(dropout <a href="https://machinelearningmastery.com/dropout-for-regularizing-deep-neural-networks/" rel="nofollow noreferrer">link</a>) randomly set internal responses of neurons to zero, to force a robust and distributed representation of the processing in the network. Keeps on network from &quot;dominating the show&quot; because in practice it tends to do more harm than good for generalization.</li> <li>(rotated locking <a href="https://paperswithcode.com/method/stochastic-depth" rel="nofollow noreferrer">link</a>) aka stochastic depth, randomly freeze layers in the architecture to avoid most learning occurring only in the last few layers, aka diminishing gradients.</li> <li>(pca in vectorized weights) given a batch of errors for weights, perform pca and only retain highest x percent of eigenvalues, move in that direction.</li> <li>(entropy-scaled momentum in pca elements) given batch of errors for weights, perform svd, and then map weight changes per sample to the largest eigenvectors associated with it</li> </ul>
https://ai.stackexchange.com/questions/31945/how-does-backpropagation-know-which-weights-to-change
Question: <p><strong>What is the difference between &quot;delta&quot;, &quot;gradient&quot; and &quot;error&quot;, are these names the same thing?</strong></p> <p>I'm confused because someone once told me that both the names &quot;delta&quot; and &quot;error&quot; are commonly used. And I searched the internet, and some explanations also use the name &quot;gradient&quot;.</p> <p>For example, this article: <a href="https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/" rel="nofollow noreferrer">https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/</a>, that teaches you how to create a multilayer perceptron neural network in Python, uses the name &quot;delta&quot;, but don't call it &quot;gradient&quot;.</p> <p>But, this other article: <a href="https://home.agh.edu.pl/%7Evlsi/AI/backp_t_en/backprop.html" rel="nofollow noreferrer">https://home.agh.edu.pl/~vlsi/AI/backp_t_en/backprop.html</a>, it does not use the name &quot;delta&quot; or &quot;gradient&quot;.</p> <p><strong>Please, could someone help me understand about &quot;error&quot;, &quot;delta&quot; and &quot;gradient&quot;, what is the difference between these names? are they the same thing?</strong></p> Answer: <p>The terms &quot;error&quot;, &quot;delta&quot; and &quot;gradient&quot; in neural network back-propagation are often used as shorthand, or loose explanations for the same thing. This is not strictly correct in all cases, and you should be careful to check the code in context. However, these words do make for suitable variable names, so you will see them in implenentations.</p> <p>Back-propagation is repeated application of the <a href="https://www.khanacademy.org/math/ap-calculus-ab/ab-differentiation-2-new/ab-3-1a/a/chain-rule-review" rel="nofollow noreferrer">chain rule of calculus</a>, which can be written:</p> <p><span class="math-container">$$\frac{d}{dx} f(g(x)) = \frac{df}{dg} \frac{dg}{dx}$$</span></p> <p>This is useful for neural networks, because each layer (and each activation function) is applied as a function to each previous layer, so a neural network is effectively a giant composite of much simpler functions, each applied to the output of the previous one.</p> <p>The goal of back-propagation is to figure out the <em>gradient of the loss function with respect to the neural network's changeable parameters</em> (the weights and biases usually). So &quot;gradient&quot; is kind of shorthand for this, although you work it out in part, plus some are temporary useful values that are not part of the final array of partial derivatives.</p> <p>Some people like to think of the gradient as an &quot;error correction signal&quot;, and also with careful design, the initial gradient of the loss for the neuron output with respect to the output layer, before the activation is applied, can be <span class="math-container">$\hat{y} - y$</span>, the difference between the current output and the ground truth. So it even looks a little bit like an error value, even though it is a different kind of quantity which happens to equal the error value.</p> <p>I am not sure, but I think &quot;delta&quot; is a direct reference to the Greek letter delta in the partial derivative <span class="math-container">$\frac{\delta L}{\delta W_i}$</span>, as the full gradient is an array of these partial derivatives of the loss function with respect to each parameter in turn.</p> <p>A good way to understand and isolate yourself from all the different names used in implementation code is to learn the mathematical representation of backpropagation. The maths gives you a less ambiguous view of what is going on, and doesn't use any of those three terms.</p>
https://ai.stackexchange.com/questions/42633/in-multilayer-perceptron-neural-networks-are-the-names-delta-gradient-and
Question: <p><strong>Reference:</strong> <a href="https://home.agh.edu.pl/%7Evlsi/AI/backp_t_en/backprop.html" rel="nofollow noreferrer">https://home.agh.edu.pl/~vlsi/AI/backp_t_en/backprop.html</a></p> <p>If I trained a multilayer percetron neural network manually, following exactly the backpropagation steps described in the article, with fixed initial weights (that is, without starting randomly), and then repeating this training again several more times just like I did the first time, ignoring the randomness and unforeseen events of the computation(because as I would be following everything manually, there would be no random initialization of the weights, no rounding problems, nor any variation in the process), if I do this when training the network, and I always use the same fixed initial weights( so that it always starts from the same starting point), using the same network structure (same number of layers, neurons, exactly the same network), with exactly the same parameters (such as number of epochs, learning rate, etc.), with the same dataset, with this network being trained with the dataset samples in the same order, <strong>following meticulously, very carefully, mathematically will I always get the same results? this is true ?</strong></p> <p><strong>I are without considering of whether the predictions are correct or not. My specific doubt, whether mathematically the results will be the same in the circumstances described.</strong></p> Answer: <p>Unless you use full batch gradient descent method for your BP algo which is very rare in practice mainly due to its inefficiency and slow convergence, the usual <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent#Iterative_method" rel="nofollow noreferrer">stochastic</a> or mini-batch or momentum-based gradient descent methods don't produce exactly same results.</p> <blockquote> <p>As the algorithm sweeps through the training set, it performs the above update for each training sample. Several passes can be made over the training set until the algorithm converges. If this is done, the data can be shuffled for each pass to prevent cycles. Typical implementations may use an adaptive learning rate so that the algorithm converges.</p> </blockquote> <p>Obviously in above case the <em>order</em> of all your training samples to be fitted in any epoch matters due to the data shuffle along with an adaptive learning rate and the nonzero threshold even in all the cases of actual convergence.</p>
https://ai.stackexchange.com/questions/42776/if-i-manually-trained-a-multilayer-percetron-neural-network-always-following-ex
Question: <p><strong>Article 1:</strong> <a href="https://pyimagesearch.com/2021/05/06/backpropagation-from-scratch-with-python/" rel="nofollow noreferrer">https://pyimagesearch.com/2021/05/06/backpropagation-from-scratch-with-python/</a></p> <p><strong>Article 2:</strong> <a href="https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/" rel="nofollow noreferrer">https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/</a></p> <p>I was reading the 2 articles that teach backpropagation from scratch. I had a doubt about the first article, and so I would really like to ask specifically about the way he used to calculate the deltas of neurons in the hidden layer.</p> <p>The first article, talking about calculating the delta in hidden layers, mentions the following:</p> <blockquote> <p>the delta of the current layer is equal to the delta from the previous layer dotted with the weight matrix of the current layer, followed by multiplication of the delta by the derivative of the nonlinear activation function for the activations of the current layer</p> </blockquote> <p>However, in the second article, the explanation seems to be a little different, in the second article's explanation on how to calculate the delta he mentions</p> <blockquote> <p>You can see that the error signal for neurons in the hidden layer is accumulated from neurons in the output layer where the hidden neuron number j is also the index of the neuron’s weight in the output layer neuron[‘weights’][j].</p> </blockquote> <p>Analyzing this explanation from the second article, <strong>I had this doubt: the first article on the hidden layer says that the delta of the current layer is equal to the delta from the previous layer dotted with the weight matrix of the current layer. However, in the second article he says that the delta in the hidden layer is calculated using the sum of the deltas of the next layer multiplied by the connection weights with the neuron with index J in the current hidden layer</strong> (in this case, the next layer is the output layer), this sum is multiplied by the derivative of the activation of the hidden layer neuron. I was very confused precisely because in the second article the weights that were used to calculate the delta are not the weights of the current layer (as is done in the first article), instead, the weights used in the second article are the weights of the next layer (That's it, the weights of the inputs of the neurons in the next layer, in this case the output layer)</p> <p><strong>I know that both articles are similar explanations, but I was confused. Is there any difference in the formulas of both articles? Or in practice are both equivalent? Could someone please help me understand these differences?</strong></p> Answer: <p>The key idea of <a href="https://en.wikipedia.org/wiki/Backpropagation" rel="nofollow noreferrer">backpropagation</a> can be summarized as:</p> <blockquote> <p>Each individual component of the gradient, <span class="math-container">$\partial C/\partial w_{jk}^{l}$</span> can be computed by the chain rule; but doing this separately for each weight is inefficient. Backpropagation efficiently computes the gradient by avoiding duplicate calculations and not computing unnecessary intermediate values, by computing the gradient of each layer – specifically the gradient of the weighted input of each layer, denoted by <span class="math-container">$\delta^{l}$</span> – from back to front... The <span class="math-container">$\delta ^{l}$</span> can easily be computed recursively, going from right to left, as: <span class="math-container">$$\delta ^{l-1}:=(f^{l-1})'\circ (W^{l})^{T}\cdot \delta ^{l}$$</span> The gradients of the weights can thus be computed using a few matrix multiplications for each level; this is backpropagation.</p> </blockquote> <p>Once this crucial step is done, all the weights can be straightforwardly updated via the delta rule involving a learning rate. Therefore you 1st article's quoted section/code just essentially implements the above crucial gradients <span class="math-container">$\delta ^{l-1}$</span> of the weighted inputs of each layer from code line 99-111, and code line 113-125 implements the final weights delta update rule which additionally involves the multiplicative terms of learning rate and the respective weighted inputs of each layer in Numpy's matrix/array linear algebra way.</p> <p>And the error signal of your 2nd article's quoted section (&quot;the error signal for neurons in the hidden layer is accumulated from neurons in the output layer&quot;) is just the inner function part <span class="math-container">$(W^{l})^{T}\cdot \delta ^{l}$</span> of the composed gradient function <span class="math-container">$\delta ^{l-1}$</span>. And at the end line 18 of the quoted code snippet you have:</p> <p><code>neuron['delta'] = errors[j] * transfer_derivative(neuron['output'])</code></p> <p>Thus the same gradient of each layer <span class="math-container">$\delta ^{l-1}$</span> as expressed as <code>neuron['delta']</code> here is obtained too after multiplied by the derivative of the activation/transfer function though here seems only primitive Python data types are employed instead of Numpy's linear algebra data types.</p>
https://ai.stackexchange.com/questions/42884/why-in-one-article-to-calcule-the-delta-uses-the-weights-of-current-layer-while
Question: <p>Here's a basic GPT2 implementation:</p> <pre><code>class GPT(nn.Module): def __init__(self, vocab_size, seq_len, model_dim, n_heads, n_layers): super().__init__() self.seq_len = seq_len self.wte = nn.Embedding(vocab_size, model_dim) self.wpe = nn.Embedding(seq_len, model_dim) self.h = nn.Sequential( *[DecodeLayer(model_dim, n_heads) for _ in range(n_layers)] ) self.ln_f = nn.LayerNorm(model_dim) def forward(self, x): embeds = self.wte(x) + self.wpe(torch.arange(0, self.seq_len).to(x.device)) # [seq_len, model_dim] embeds = self.h(embeds) embeds = self.ln_f(embeds) # (seq_len, model_dim) x (model_dim, vocab_size) =&gt; seq_len vocab_size return embeds @ self.wte.weight.T </code></pre> <p>The positional embeddings are added to the input with:</p> <pre><code>self.wpe(torch.arange(0, self.seq_len).to(x.device)) </code></pre> <p>I wonder, if it would be possible to just do: <code>self.wpe = nn.Parameter(seq_len, model_dim)</code>, and change the line in the forward pass to:</p> <pre><code>embeds = self.wte(x) + self.wpe </code></pre> Answer: <p>Depends... for ViT yes, they are called learned positional encodings, and the reason is that you always have a fixed number of patches (at least theoretically)</p> <p>However, for NLP, you cannot do that, because at inference, you might have strings longer or shorter than the reference, and if you have trained only <code>seq_len</code> positional encoding, and the inference string is longer than that, than you won't be able to apply a positional encoding to the final part of it</p>
https://ai.stackexchange.com/questions/43565/can-positional-encodings-in-transformers-be-added
Question: <p>My understanding is this: When doing Stochastic Gradient Descent over a neural network, in every epoch, we run <span class="math-container">$n$</span> iterations (where the dataset has <span class="math-container">$n$</span> training examples) and in every iteration, we take a random sample and update the parameters wrt the sample.</p> <p>However, in batch gradient descent, we take the whole dataset every epoch, and update the parameters wrt the batch. I have the following questions:</p> <ol> <li>Why do we need to compute the loss function every time, especially if the value of the loss has no importance as such in the backprop process? Is it just to ensure that the loss decreases over time? How can you propagate the error back when the value of L is of no significance?</li> <li>What exactly does updating wrt a &quot;batch&quot; mean? What would you take the input vector (required to compute gradients for the first set of weights) as? I assume that the loss is taken to be the average of the losses for the entire batch</li> </ol> Answer: <p>In batch gradient descent computing the loss function every time serves several purposes. While the value of the loss itself may not directly affect the backpropagation process, as you said monitoring the loss over time is essential to ensure that the optimization process is converging. Also many optimization algorithms such as learning rate schedules or adaptive learning rate methods adjust the learning rate or other hyperparameters based on the behavior of the loss function during training. Therefore, computing the loss function is crucial for determining how the learning rate should be updated. Finally, monitoring the loss function can also be used for early stopping, a technique where training is halted if the loss on a validation set stops decreasing or starts increasing, which helps prevent the usual overfitting of neural networks and wasting computational resources.</p> <p>Updating parameters with respect to a batch means computing the gradients of the (average) loss function with respect to the parameters using all examples in the batch and then updating the parameters accordingly. This process is repeated for each batch during each epoch of training and in your case each batch could simply mean the entire training dataset.</p> <p>The input vector used to compute gradients for the first set of weights is a matrix whose row represents an individual example from the batch and whose columns represent the features of that example, and the number of features would typically determine the number of input nodes of your network. During training the neural network processes this entire batch at once with operations including forward and backward passes performed in a vectorized or parallelized manner for efficiency.</p>
https://ai.stackexchange.com/questions/43688/what-do-you-mean-by-updating-based-on-a-training-example-batch-in-gradient-des
Question: <p>Why are the weights of a neural net updated only considering the old values of the later layer, not the already updated values?</p> <p>I use <a href="https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/" rel="nofollow noreferrer">this example</a> to explain my problem. When applying the backpropagation chain rule, the weights of the previous layer (<span class="math-container">$w_1, w_2, w_3, w_4$</span>) are updated making use of the chain rule:</p> <p><span class="math-container">$$\frac{\partial E_{total}}{\partial w_1} = \frac{\partial E_{total}}{\partial out_{h1}} * \frac{\partial out_{h1}}{\partial net_{h1}}*\frac{\partial net_{h1}}{\partial w_1}$$</span></p> <p>He then says:</p> <p><span class="math-container">$$\frac{\partial net_{o1}}{\partial out_{h1}}=w_5$$</span></p> <p>Although he has already calculated the updated value for <span class="math-container">$w_5$</span>, he uses the old value of <span class="math-container">$w_5$</span> to update <span class="math-container">$w_1$</span>? Because the updated value of <span class="math-container">$w_1$</span> will have an impact on the outcome together with the updated value of <span class="math-container">$w_5$</span>?</p> Answer: <p>The basic idea of gradient descent is:</p> <ul> <li><p>Calculate the gradient of some score with respect to parameters that you can control</p> </li> <li><p>Take a step in the direction of that gradient that improves the score (subract a multiple of gradient - for gradient descent - if you want to minimise some cost function)</p> </li> </ul> <p>The backpropagation using chain rule in neural network layers is part of the first part, calculating the gradient.</p> <p>If you interleaved these steps during a single calculation, by taking an update step before propagating the gradient over all layers, you would not propagate the true gradient, but some interim value. There is no guarantee this value would reflect the true gradient of the affected layer when compared to training data and loss functions.</p> <p>There are some manipulations of the gradient that are acceptable and improve convergence. For instance momentum, and various forms of weighting based on previous gradient calculations. However, I am not aware of any successful attempt to perform updates with partially-calculated gradient then attempt to continue the interrupted gradient calculations over the mixed updated and not-yet-updated parameters.</p> <p>It is also possible to calculate gradients and then only update <em>some</em> of the possible parameters. In some cases this is useful, for instance it is a good choice when performing transfer learning, by only updating a few layers close to the output. This constrains the network to keep a lot of its trained parameters as-is, which reduces the chances of over-fitting to the smaller dataset that the network is learning from when transferring.</p>
https://ai.stackexchange.com/questions/26136/why-are-the-weights-of-the-previous-layers-updated-only-considering-the-old-valu
Question: <p>I recently started working on very simple machine learning codes in Python and I came across a big problem: teaching the system to improve on its guesses.</p> <p>So this is what the code is about: I will have a list of organisms with their features stated in numerical values. I want to write a code that identifies that whether the organism is a cat or a fish or neither based on their characteristics. (For example an organism with a high fur value and 4 legs is more probable to be a cat.)</p> <p>My idea for the neural network is to have five input nodes(for the five characteristics) and 2 output nodes (one for how cat it is and one for how fish it is). The input nodes are multiplied by a weight value and then all summed together to produce one of the output nodes. This repeats itself for the other output. How much the system got wrong is just the difference between the value of the output nodes and how cat/fish the being actually is. </p> <p>But how can I use this information to correct the weights of the input nodes? Since the weights are randomly generated they can be in the "wrong" directions to begin with. For example if the subject is a cat then we should be expecting high fur and leg values. But what if the weight for the leg value is negative while the weight for the fur value is positive? Adding or multiplying the weight by the error won't bring us any closer to accurately determining the being. Is my neural network flawed to begin with? Or is there a rule of thumb in choosing back propagation algorithms?</p> <p>Thanks. <a href="https://i.sstatic.net/0LDQ0.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0LDQ0.jpg" alt="the neural network"></a></p> Answer: <p>When you are training a neural network, you use an algorithm called back propagation. This algorithm uses partial derivatives to determine the optimal values for weights. Partial derivatives are a calculus based method which tell you how far you need to adjust the weights in order to get to an optimum value. However, when you have neural networks with many different weights you need to be able to decide which ones to update in order to achieve a more optimal network. This is where stochastic gradient descent comes in. This algorithm is able to take many different gradients and traverse through many dimensional space into a lower error rate. Also, from your diagram of your neural network, I do not see any hidden neurons, which are neurons between the input and output layers which do most of the actual work. While you might be able to train your neural network optimally without hidden neurons, it might improve your accuracy depending upon your dataset. Finally, implementing a back propagation algorithm is a lot of work which is why many people use pre built libraries. Unless you are doing research, I recommend you do the same. I think for a problem like this, pybrain would be perfect, and if you want to use deep neural networks, tensorflow would be good for that.</p>
https://ai.stackexchange.com/questions/4211/finding-an-optimum-back-propagation-algorithm
Question: <p>Implementations of variational autoencoders that I've looked at all include a sampling layer as the last layer of the encoder block. The encoder learns to generate a mean and standard deviation for each input, and samples from it to get the input's representation in latent space. The decoder then attempts to decode this back out to match the inputs.</p> <p><strong>My question</strong>: How does backpropagation handle the random sampling step?</p> <p>Random sampling is not a deterministic function and doesn't have a derivative. In order to train the encoder, gradient updates must somehow propagate back from the loss, through the sampling layer.</p> <p>I did my best to hunt for the source code for tensorflow's autodifferentiation of this function, but couldn't find it. Here's an example of a keras implementation of that sampling step, from <a href="https://keras.io/examples/generative/vae/" rel="noreferrer">the keras docs</a>, in which <code>tf.keras.backend.random_normal</code> is used for the sampling.</p> <pre><code>class Sampling(layers.Layer): &quot;&quot;&quot;Uses (z_mean, z_log_var) to sample z, the vector encoding a digit.&quot;&quot;&quot; def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape=(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon </code></pre> Answer: <p>You do not backpropagate with respect to <span class="math-container">$\epsilon$</span>, which is the random sample or random variable (depending on how you look at it). You backpropagate with respect to the mean <span class="math-container">$\mu$</span> and variance <span class="math-container">$\sigma$</span> of the latent Gaussian (the variational distribution). Note that, although <span class="math-container">$z$</span> is a random sample (and not just a sample), because it's computed as a function of <span class="math-container">$\epsilon$</span> (a random sample, once it's sampled from e.g. <span class="math-container">$\mathcal{N}(0, 1)$</span>), <span class="math-container">$\mu$</span> and <span class="math-container">$\sigma$</span> are not: these are learnable parameters and are deterministic.</p> <p>Having said this, note that we use the <a href="https://arxiv.org/pdf/1312.6114.pdf" rel="nofollow noreferrer"><strong>reparametrization trick</strong></a> in the VAE, so we compute the random sample as <span class="math-container">$z = g_\phi(\epsilon, x))$</span>, where <span class="math-container">$g_\phi$</span> is a deterministic function (encoder) parametrized by <span class="math-container">$\phi$</span> (the weights of the neural network that represents the encoder). In case the random variable <span class="math-container">$z \sim \mathcal{N}(\mu, \sigma^2)$</span>, then we can express the random variable (so also the random sample) as follows <span class="math-container">$z=g_\phi(\epsilon, x)) = \mu+\sigma \epsilon$</span>. So, as you can see from the code, we sample <span class="math-container">$\epsilon$</span> from some prior <span class="math-container">$p(\epsilon)$</span> (e.g. <span class="math-container">$\mathcal{N}(0, 1)$</span>), then we compute <span class="math-container">$z$</span> deterministically.</p> <p>Why is this <strong>reparametrization trick</strong> useful? The authors of the VAE paper explain it.</p> <blockquote> <p>This reparameterization is useful for our case since it can be used to rewrite an expectation w.r.t <span class="math-container">$q_{\phi}(\mathbf{z} \mid \mathbf{x})$</span> such that the Monte Carlo estimate of the expectation is differentiable w.r.t. <span class="math-container">$\phi$</span>. A proof is as follows. Given the deterministic mapping <span class="math-container">$\mathbf{z}=g_{\phi}(\boldsymbol{\epsilon}, \mathbf{x})$</span> we know that <span class="math-container">$q_{\phi}(\mathbf{z} \mid \mathbf{x}) \prod_{i} d z_{i}=$</span> <span class="math-container">$p(\boldsymbol{\epsilon}) \prod_{i} d \epsilon_{i}$</span>. Therefore <span class="math-container">$^{1}, \int q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x}) f(\mathbf{z}) d \mathbf{z}=\int p(\boldsymbol{\epsilon}) f(\mathbf{z}) d \boldsymbol{\epsilon}=\int p(\boldsymbol{\epsilon}) f\left(g_{\boldsymbol{\phi}}(\boldsymbol{\epsilon}, \mathbf{x})\right) d \boldsymbol{\epsilon}$</span>. It follows that a differentiable estimator can be constructed: <span class="math-container">$\int q_{\phi}(\mathbf{z} \mid \mathbf{x}) f(\mathbf{z}) d \mathbf{z} \simeq \frac{1}{L} \sum_{l=1}^{L} f\left(g_{\phi}\left(\mathbf{x}, \boldsymbol{\epsilon}^{(l)}\right)\right)$</span> where <span class="math-container">$\boldsymbol{\epsilon}^{(l)} \sim p(\boldsymbol{\epsilon}).$</span></p> </blockquote> <p>Note that <span class="math-container">$\mathbb{E}_{q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x})} \left[ f(\mathbf{z}) \right] = \int q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x}) f(\mathbf{z}) d \mathbf{z} = \int p(\boldsymbol{\epsilon}) f\left(g_{\boldsymbol{\phi}}(\boldsymbol{\epsilon}, \mathbf{x})\right) d \boldsymbol{\epsilon} = \mathbb{E}_{p(\boldsymbol{\epsilon})} \left[ f\left(g_{\boldsymbol{\phi}}(\boldsymbol{\epsilon}, \mathbf{x})\right) \right]$</span>, which can be <strong>estimated</strong> with <span class="math-container">$\frac{1}{L} \sum_{l=1}^{L} f\left(g_{\phi}\left(\mathbf{x}, \boldsymbol{\epsilon}^{(l)}\right)\right)$</span> where <span class="math-container">$\boldsymbol{\epsilon}^{(l)} \sim p(\boldsymbol{\epsilon})$</span>. In other words, you can sample <span class="math-container">$L$</span> <span class="math-container">$z$</span> in the way we did in order to estimate <span class="math-container">$\mathbb{E}_{\color{blue}{q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x})}} \left[ \color{red}{f(\mathbf{z})} \right]$</span> (this are Monte Carlo estimates of the expectation).</p> <p>In the case of the VAE, we want to optimize the ELBO, which is the following objective function</p> <p><span class="math-container">$$\mathcal{L}\left(\boldsymbol{\theta}, \boldsymbol{\phi} ; \mathbf{x}^{(i)}\right)=\underbrace{-D_{K L}\left(q_{\boldsymbol{\phi}}\left(\mathbf{z} \mid \mathbf{x}^{(i)}\right) \| p_{\boldsymbol{\theta}}(\mathbf{z})\right)}_{\text{KL divergence}}+ \underbrace{\mathbb{E}_{\color{blue}{q_{\phi}\left(\mathbf{z} \mid \mathbf{x}^{(i)}\right)}}\left[\color{red}{\log p_{\boldsymbol{\theta}}\left(\mathbf{x}^{(i)} \mid \mathbf{z}\right)}\right]}_{\text{likelihood}}$$</span></p> <p>which we can estimate with Monte Carlo estimates of the second term (the <strong>likelihood term</strong>)</p> <p><span class="math-container">$$ \widetilde{\mathcal{L}}^{B}\left(\boldsymbol{\theta}, \boldsymbol{\phi} ; \mathbf{x}^{(i)}\right)=-D_{K L}\left(q_{\boldsymbol{\phi}}\left(\mathbf{z} \mid \mathbf{x}^{(i)}\right) \| p_{\boldsymbol{\theta}}(\mathbf{z})\right)+ \underbrace{\frac{1}{L} \sum_{l=1}^{L}\left(\log p_{\boldsymbol{\theta}}\left(\mathbf{x}^{(i)} \mid \mathbf{z}^{(i, l)}\right)\right)}_{\text{likelihood}} $$</span> where <span class="math-container">$$ \text { where } \quad \mathbf{z}^{(i, l)}=g_{\phi}\left(\boldsymbol{\epsilon}^{(i, l)}, \mathbf{x}^{(i)}\right) \text { and } \boldsymbol{\epsilon}^{(l)} \sim p(\boldsymbol{\epsilon}) $$</span></p> <p>Here, the likelihood is computed with the neural network, for example, in practice, you use the cross-entropy of the output of your decoder, which gets as input the input to the decoder, hence <span class="math-container">$z$</span>.</p> <p>You can ignore the KL divergence now because, in the case of Gaussians, <a href="https://ai.stackexchange.com/a/26408/2444">it can be computed analytically</a>.</p> <p>Now, what if we didn't use the reparametrization trick? Could we still backpropagate with respect to <span class="math-container">$\phi$</span>? The authors of the VAE write</p> <blockquote> <p>The usual (naïve) Monte Carlo gradient estimator for this type of problem is: <span class="math-container">$\nabla_{\phi} \mathbb{E}_{q_{\phi}(\mathbf{z})}[f(\mathbf{z})]=\mathbb{E}_{q_{\phi}(\mathbf{z})}\left[f(\mathbf{z}) \nabla_{q_{\phi}(\mathbf{z})} \log q_{\phi}(\mathbf{z})\right] \simeq \frac{1}{L} \sum_{l=1}^{L} f(\mathbf{z}) \nabla_{q_{\phi}\left(\mathbf{z}^{(l)}\right)} \log q_{\phi}\left(\mathbf{z}^{(l)}\right)$</span> where <span class="math-container">$\mathbf{z}^{(l)} \sim q_{\phi}\left(\mathbf{z} \mid \mathbf{x}^{(i)}\right) .$</span> This gradient estimator exhibits exhibits very high variance (see e.g. <a href="https://arxiv.org/pdf/1206.6430.pdf" rel="nofollow noreferrer">[BJP12]</a>)</p> </blockquote> <p>So, the answer is <strong>yes</strong>, as opposed to what many people might say around, but with another estimator (which may remind you of some equations you have seen in reinforcement learning related to <a href="http://incompleteideas.net/book/RLbook2020.pdf#page=348" rel="nofollow noreferrer">REINFORCE</a>, if you are familiar with this), i.e. <span class="math-container">$$\frac{1}{L} \sum_{l=1}^{L} f(\mathbf{z}) \nabla_{q_{\phi}\left(\mathbf{z}^{(l)}\right)} \log q_{\phi}\left(\mathbf{z}^{(l)}\right) \tag{1}\label{1},$$</span> which has high variance.</p> <p>So, in the end, the reparametrization trick can be viewed as a <a href="http://proceedings.mlr.press/v89/xu19a/xu19a.pdf" rel="nofollow noreferrer">variance reduction technique</a>. There are others, like <a href="https://arxiv.org/pdf/1206.6430.pdf" rel="nofollow noreferrer"><strong>control variates</strong></a> or <a href="https://arxiv.org/abs/1803.04386" rel="nofollow noreferrer"><strong>Flipout</strong></a> (<a href="https://github.com/tensorflow/probability/blob/main/tensorflow_probability/examples/bayesian_neural_network.py" rel="nofollow noreferrer">used e.g. in the context of Bayesian neural networks</a>).</p> <p>The first thing to note about \ref{1} is that we do not need to take the derivative with respect to <span class="math-container">$f$</span>. The second thing is that <span class="math-container">$\nabla_{q_{\phi}\left(\mathbf{z}^{(l)}\right)} \log q_{\phi}\left(\mathbf{z}^{(l)}\right)$</span> is the <a href="https://jmlr.org/papers/volume21/19-346/19-346.pdf" rel="nofollow noreferrer"><strong>score function</strong></a>.</p> <p>Now, don't ask me how to calculate this gradient <span class="math-container">$\nabla_{q_{\phi}\left(\mathbf{z}^{(l)}\right)} \log q_{\phi}\left(\mathbf{z}^{(l)}\right)$</span> (because I am bad at math). However, note that <span class="math-container">$ \mathbf{z}^{(l)} \sim q_{\phi}\left(\mathbf{z} \mid \mathbf{x}^{(i)}\right) $</span>, so we treat <span class="math-container">$\mathbf{z}^{(l)}$</span> as a fixed random sample. By the way, I am not sure whether they used <span class="math-container">$q_{\phi}\left(\mathbf{z} \mid \mathbf{x}^{(i)}\right)$</span> differently from <span class="math-container">$q_{\phi}\left(\mathbf{z} \right)$</span>. I don't think so. I think they are the same and I think we can still back-propagate with respect to <span class="math-container">$\phi$</span>, even if we use it to sample <span class="math-container">$\mathbf{z}^{(i)}$</span>, because, once this latter is sampled, it can be treated as fixed (random) sample.</p> <p>I also note that I think they meant <span class="math-container">$\frac{1}{L} \sum_{l=1}^{L} f(\mathbf{z}^{(l)}) \nabla_{q_{\phi}\left(\mathbf{z}^{(l)}\right)} \log q_{\phi}\left(\mathbf{z}^{(l)}\right)$</span>, i.e. they forget to use <span class="math-container">$\mathbf{z}^{(l)}$</span> rather than just <span class="math-container">$\mathbf{z}$</span> as input for <span class="math-container">$f$</span> in the Monte Carto estimate. You can see in section 3 of <a href="https://arxiv.org/pdf/1206.6430.pdf" rel="nofollow noreferrer">[BJP12]</a> and section 4.2. of <a href="https://jmlr.org/papers/volume21/19-346/19-346.pdf" rel="nofollow noreferrer">[1]</a> they do it like this, and it makes sense. So, the VAE paper has sloppy stuff in there.</p> <p>My intuition of why this has high variance is because you sample something according to the variational distribution, but then you update this variational distribution, and you continuously do this. However, I am not sure this is the right intuition. In <a href="https://arxiv.org/pdf/1206.6430.pdf" rel="nofollow noreferrer">[BJP12]</a>, they say (in section 4) this MC estimate has high variance and that you need a lot of samples <span class="math-container">$\mathbf{x}$</span>. I don't know exactly why this is the case because I didn't fully read this paper yet.</p>
https://ai.stackexchange.com/questions/33824/how-does-backprop-work-through-the-random-sampling-layer-in-a-variational-autoen
Question: <p>The Back propagation through time on recurrent layer is defined similar to normal one, means somethin like </p> <p><code>self.deltas[x] = self.deltas[x+1].dot(self.weights[x].T) * self.layers[x] * (1- self.layers[x])</code> where </p> <p><code>self.deltas[x+1]</code> is error from prevous layer, <code>self.weights[x]</code> is weights map and <code>self.layers[x](1- self.layers[x])</code> is bakwards activation of sigmoid function where <code>self.layers[x]</code> is vector of sigmoid. But while normal backpropagation the values are there, while BPTT i can not take the current <code>self.layers[x]</code> : i need the previous ones, right ? </p> <p>So unlike normal BP, do i need extra store old weights and layers, for example in circular queue, and then apply the formula where <code>self.deltas[x+1]</code> is layer from next time ?</p> <p>Not realy implementation, just basic understanding in order to can implement it.</p> <p>Lets see the picture:</p> <p><a href="https://i.sstatic.net/NwXQ9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NwXQ9.png" alt="enter image description here"></a></p> <p>Here are : self.layers[0] = <span class="math-container">$x_{t+1}$</span>, self.layers[<em>1</em>] = <span class="math-container">$h_{t+1}$</span> , self.layers[2] = <span class="math-container">$o_{t+1}$</span>, in order to perform backprop <span class="math-container">$h_{t+1}$</span> -> <span class="math-container">$h_{t}$</span> -> <span class="math-container">$h_{t-1}$</span>... <strong>I DO NEED to have layers <span class="math-container">$h_t$</span> ,<span class="math-container">$h_{t-1}$</span>... and weights <span class="math-container">$v_{t+1}$</span>, <span class="math-container">$v_t$</span>... EXTRA stored in additional to the network <span class="math-container">$x_{t+1}$</span> -> <span class="math-container">$h_{t+1}$</span> -> <span class="math-container">$o_{t+1}$</span>, right?</strong> Thats all the question.</p> <p>And i do not need to store previous outputs <span class="math-container">$o[t, o_{t-1}, etc..]$</span>, because backprop from them ot->ht, etc was <em>already</em> calculated. </p> Answer: <p>One word answer for your question "<strong>Do you need to store previous values of weights and layers on recurrent layer while BPTT?</strong>" is <strong>YES</strong></p> <p>Let us go through the details.</p> <p>For training an RNN using BPTT, we need gradients of error w.r.t all three parameters <strong>U</strong>, <strong>V</strong>, <strong>W</strong></p> <p>Notation of my explanation is different from notation in the figure of question. My notation is as below:</p> <ol> <li><strong>V</strong> - Hidden Layer - Output Layer (gradients of V are independent of previous time steps) </li> <li><strong>U</strong> - Input Layer - Hidden Layer (gradients of U are dependent on previous time steps) </li> <li><strong>W</strong> - Hidden Layer - Hidden Layer (gradients of W are also dependent on previous time steps)</li> </ol> <p>And for calculating these gradients, we use chain rule of differentiation, the same rule that we used to calculate gradients in a fully connected neural network. </p> <p>The gradient w.r.t V only depends on current time step (doesn't need any values from previous time step). </p> <p>The gradients w.r.t U, W depends on current time step and also all previous time steps (so needs values from all time steps)</p> <p>Basically, we need to back propagate gradients from current time step all the way to t=0.</p> <p>How this back propagation is different from the back propagation we use in fully connected neural network is that, in fully connected neural network we don't have the concept of t and also we don't share any weights across layers. But, here we share weights across layers and time instants. So, gradients depend on all time instants.</p> <p><strong>Note: Be careful with notation difference between several articles. I followed slightly different notation than in the diagram in question.</strong></p> <p>Some links that will help you explore.</p> <p><a href="https://www.youtube.com/watch?v=RrB605Mbpic" rel="nofollow noreferrer">https://www.youtube.com/watch?v=RrB605Mbpic</a> (clearly explains about gradients of all three U, V, W; but notation is different from diagram in question)</p> <p><a href="http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/" rel="nofollow noreferrer">http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/</a><a href="http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/" rel="nofollow noreferrer">enter link description here</a></p> <p><a href="http://ir.hit.edu.cn/~jguo/docs/notes/bptt.pdf" rel="nofollow noreferrer">http://ir.hit.edu.cn/~jguo/docs/notes/bptt.pdf</a></p> <p><a href="https://www.d2l.ai/chapter_recurrent-neural-networks/bptt.html" rel="nofollow noreferrer">https://www.d2l.ai/chapter_recurrent-neural-networks/bptt.html</a></p> <p>Remember, you should understand chain rule of partial derivative very clearly to do the derivation yourself and understand it.</p> <p>Also, dont think BPTT is separate than BP. It is one and the same. Since neural network architecture in RNN includes time instants and sharing of weights across time instants, just using chain rule on this network makes back propagation also dependent on time and so is the name. </p> <p>Hope it helps. Feedback is welcome.</p>
https://ai.stackexchange.com/questions/12657/do-you-need-to-store-prevous-values-of-weights-and-layers-on-recurrent-layer-whi
Question: <p>I was reading the following book: <a href="http://neuralnetworksanddeeplearning.com/chap2.html" rel="nofollow noreferrer">http://neuralnetworksanddeeplearning.com/chap2.html</a></p> <p>and towards the end of equation 29, there is a paragraph that explains this: </p> <p><a href="https://i.sstatic.net/KkBdn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KkBdn.png" alt="enter image description here"></a></p> <p>However I am unsure how the equation below is derived:</p> <p><a href="https://i.sstatic.net/DlOfT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DlOfT.png" alt="enter image description here"></a></p> Answer: <p>I believe he's just saying that:</p> <p><span class="math-container">$$ \frac{\partial C}{\partial z_j^l} \Delta z_j^l \approx \frac{\partial C}{\partial z_j^l} \partial z_j^l \approx \partial C $$</span></p> <p>so that the change in cost function can be arrived at simply for a small enough perturbation <span class="math-container">$\Delta z_j^l$</span>.</p> <p>Or, taking that line of approximations backwards, the change in the cost function for a given perturbation is just: <span class="math-container">$$ \partial C \approx \frac{\partial C}{\partial z_j^l} \partial z_j^l \approx \frac{\partial C}{\partial z_j^l} \Delta z_j^l $$</span></p>
https://ai.stackexchange.com/questions/12682/how-does-adding-a-small-change-to-an-neurons-weighted-input-affect-the-overall
Question: <p>I am trying to wrap my head around how weights get updated during back propagation. I've been going through a school book and I have the following setup for an ANN with 1 hidden layer, a couple of inputs and a single output. </p> <p><a href="https://i.sstatic.net/fVkiR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fVkiR.png" alt="calculating errors and updating weights"></a> The first line gives the error that will be used to update the weights going from the hidden layer to the output layer. <span class="math-container">$t$</span> represents the target output, <span class="math-container">$a$</span> represents the activation and the formula is using the derivative for the sigmoid function <span class="math-container">$(a(1-a))$</span>. Then, the weights are updated with the learning rate, multiplied by the error and the activation of the given neuron which uses the weight <span class="math-container">$w_h$</span>. Then, the next step is moving on to calculate the error with respect to the input going into the hidden layer from the input layer (sigmoid is the activation function on both the hidden and the output layer for this purpose). So we have the total error * derivative of the activation for the hidden layer * the weight for the hidden layer.</p> <p>I am following this train of thought as it was provided, but my question is &mdash; if the activation is changed to <span class="math-container">$tanh$</span> for example and the derivative of <span class="math-container">$tanh$</span> is <span class="math-container">$1-f(x)^2$</span>, then would we have the error formula update to <span class="math-container">$(t-a)*(1-a^2)$</span> where <span class="math-container">$a$</span> represents the activation function so <span class="math-container">$1-a^2$</span> is the derivative of <span class="math-container">$tanh$</span>?</p> Answer:
https://ai.stackexchange.com/questions/18213/function-to-update-weights-in-back-propagation
Question: <p>We require to find the gradient of loss function(cost function) w.r.t to the weights to use optimization methods such as SGD or gradient descent. So far, I have come across two ways to compute the gradient:</p> <ol> <li>BackPropagation</li> <li>Calculating gradient of loss function by calculus</li> </ol> <p>I found many resources for understanding backpropagation. The 2nd method I am referring to is the image below(taken for a specific example, e is the error: difference between target and prediction): <a href="https://i.sstatic.net/OSOVB.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OSOVB.jpg" alt="enter image description here"></a> </p> <p>Also, the proof was mentioned in this paper:<a href="https://arxiv.org/pdf/1802.01528.pdf" rel="nofollow noreferrer">here</a></p> <p>Moreover, I found this method while reading this <a href="https://www.pyimagesearch.com/2016/10/10/gradient-descent-with-python/" rel="nofollow noreferrer">blog</a>.(You might have to scroll down to see the code: gradient = X.T.dot(error) / X.shape[0] ) </p> <p>My question is are the two methods of finding gradient of cost function same? It appears different and if yes, which one is more efficient( though one can guess it is backpropagation)</p> <p>Would be grateful for any help. Thanks for being patient(it's my 1st time learning ML). </p> Answer: <p>I'm pretty sure they're the same thing. Both backpropagation and gradient descent's essential ideas are to calculate the partial derivative of the cost with respect to each weight, and subtract the partial derivative times the learning rate.</p>
https://ai.stackexchange.com/questions/19895/different-methods-of-calculating-gradients-of-cost-functionloss-function
Question: <p>For the purposes of this question I am asking about training the generator, assume that training the discriminator is another topic.</p> <p>My understanding of generative adversarial networks is that you feed random input data to the generator and it generates images. Out of those images, the ones which the discriminator thinks are real are used to train the generator.</p> <p>For example, I have the random inputs <span class="math-container">$i_1$</span>, <span class="math-container">$i_2$</span>, <span class="math-container">$i_3$</span>, <span class="math-container">$i_4$</span>... from which the generator produces <span class="math-container">$o_1$</span>, <span class="math-container">$o_2$</span>, <span class="math-container">$o_3$</span>, <span class="math-container">$o_4$</span>. Say for example, the discriminator thinks that <span class="math-container">$o_1$</span> and <span class="math-container">$o_2$</span> are real but <span class="math-container">$o_3$</span> and <span class="math-container">$o_4$</span> are fake, I then throw away input output pairs 3 and 4, but keep 1 and 2, and run back propagation on the generator to tell it that <span class="math-container">$i_1$</span> should produce <span class="math-container">$o_1$</span>, and <span class="math-container">$i_2$</span> should produce <span class="math-container">$o_2$</span> since these were "correct" according to the discriminator.</p> <p>The contradiction seems to come from the fact that the generator <em>already</em> generates those outputs from those inputs, so nothing will be gained by running backprop on those input output pairs.</p> <p>Where is the flaw in my logic here? I seem to have something wrong in my reasoning, or a misunderstanding of how the generator is trained.</p> Answer: <p>I had this same problem some time ago, here's what you should do:</p> <p>notice how we first input i1 to the generator, that outputs o1, than we input o1 into the discriminator, that outputs y1, so the output from the first (o1) is the input to the second, but that's like if we combine the two networks into one from a moment, right? under the hood, a layer from a neural network connects with the next layer, just like the output layer from the generator connected with the input layer from the generator, so you could interpret them as a single big neural network. Then it's easy to see how we would backpropagate through this whole combined network, all the way into the first layer of the generator, successfully updating all it's parameters, thus training it.</p> <p>That's not all when training a GAN, as we need to also train the discriminator separately with real images. For that we simply input the image directly into the discriminator, and when backpropagating, we stop in the discriminator, as anything from the generator has nothing to do with the real images.</p> <p>Really, all you need to do is treat the generator and discriminator as one big neural network when you want to input noise to the generator, but separate them when you want to input a real image into the discriminator.</p>
https://ai.stackexchange.com/questions/10053/training-the-generator-in-a-gan-pair-with-back-propagation
Question: <p>I'm reading the paper <a href="https://arxiv.org/pdf/1806.07366.pdf" rel="nofollow noreferrer">Neural Ordinary Differential Equations</a> and I have a simple question about adjoint method. When we train NODE, it uses a blackbox ODESolver to compute gradients through model parameters, hidden states, and time. It uses another quantity <span class="math-container">$\mathbf{a}(t) = \partial L / \partial \mathbf{z}(t)$</span> called <em>adjoint</em>, which also satisfies another ODE. As I understand, the authors build a single ODE that computes all the gradients <span class="math-container">$\partial L / \partial \mathbf{z}(t_{0})$</span> and <span class="math-container">$\partial L / \partial \theta$</span> by solving that single ODE. However, I can't understand how do we know the value <span class="math-container">$\partial L / \partial \mathbf{z}(t_1)$</span> which corresponds to the initial condition for the ODE corresponds to the adjoint. I'm using <a href="https://msurtsukov.github.io/Neural-ODE/" rel="nofollow noreferrer">this</a> tutorial as a reference, and it defines custom forward and backward methods for solving ODE. However, for the backward computation (especially <code>ODEAdjoint</code> class in the tutorial) we need to pass <span class="math-container">$\partial L / \partial \mathbf{z}$</span> for backpropagation, and this enables us to compute <span class="math-container">$\partial L / \partial \mathbf{z}(t_i)$</span> from <span class="math-container">$\partial L / \partial \mathbf{z}(t_{i+1})$</span>, but we still need to know the adjoint value <span class="math-container">$\partial L / \partial \mathbf{z}(t_N)$</span>. I do not understand well about how pytorch's <code>autograd</code> package works, and this seems to be a barrier to understand this. Could anyone explain how it operates, and where <span class="math-container">$\partial L / \partial \mathbf{z}(t_1)$</span> (or <span class="math-container">$\partial L / \partial \mathbf{z}(t_N)$</span> if this is more comfortable) comes from? Thanks in advance.</p> <hr /> <p>Here's my <em>guess</em> for the initial adjoint from simple example. Let <span class="math-container">$d\mathbf{z}/dt = Az$</span> be a 2-dim linear ODE with given <span class="math-container">$A \in \mathbb{R}^{2\times 2}$</span>. If we use Euler's method as a ODE solver, then the estimate for <span class="math-container">$z(t_1)$</span> is explicitly given as <span class="math-container">$$\hat{\mathbf{z}}(t_1) = \mathrm{ODESolve}(\mathbf{z}(t_0), f, t_0, t_1, \theta))= \left(I + \frac{t_1 - t_0}{N}A\right)^{N} \mathbf{z}(t_0) $$</span> where <span class="math-container">$N$</span> is the number of steps for Euler's method (so that <span class="math-container">$h = (t_1 - t_0) /N$</span> is the step size). If we use MSE loss for training, then the loss will be <span class="math-container">$$ L(\mathbf{z}(t_1)) = \Bigl|\Bigl| \mathbf{z}_1 - \left(I + \frac{t_1 - t_0}{N}A\right)^N\mathbf{z}(t_0)\Bigr|\Bigr|_2^2 $$</span> where <span class="math-container">$\mathbf{z}_1$</span> is the true value at time <span class="math-container">$t_1$</span>, which is <span class="math-container">$\mathbf{z}_1 = e^{A(t_1 - t_0)}\mathbf{z}(t_0)$</span>. Since adjoint <span class="math-container">$\mathbf{a}(t) = \partial L / \partial \mathbf{z}(t)$</span> satisfies <span class="math-container">$$\frac{d\mathbf{a}(t)}{dt} = -\mathbf{a}(t)^{T} \frac{\partial f(\mathbf{z}(t), t, \theta)}{\partial \mathbf{z}} = \mathbf{0},$$</span> <span class="math-container">$\mathbf{a}(t)$</span> is constant and we get <span class="math-container">$\mathbf{a}(t_0) = \mathbf{a}(t_1)$</span>. So we do not need to use augmented ODE for computing <span class="math-container">$\mathbf{a}(t)$</span>. However, I still don't know what <span class="math-container">$\mathbf{a}(t_1) = \partial L / \partial \mathbf{z}(t_1)$</span> should be. If my understanding is correct, since <span class="math-container">$L = ||\mathbf{z}_1 - \mathbf{z}(t_1)||^{2}_{2}$</span>, it seems that the answer might be <span class="math-container">$$ \frac{\partial L}{\partial \mathbf{z}(t_1)} = 2(\mathbf{z}(t_1) - \mathbf{z}_1). $$</span> However, this doesn't seem to be true: if it is, and if we have multiple datapoints at <span class="math-container">$t_1, t_2, \dots, t_N$</span>, then the loss is <span class="math-container">$$ L = \frac{1}{N} \sum_{i=1}^{N}||\mathbf{z}_i -\mathbf{z}(t_i)||_{2}^{2} $$</span> and we may have <span class="math-container">$$ \frac{\partial L}{\partial \mathbf{z}(t_i)} = \frac{2}{N} (\mathbf{z}(t_i) - \mathbf{z}_i), $$</span> which means that we don't need to solve ODE associated to <span class="math-container">$\mathbf{a}(t)$</span>.</p> Answer: <p>First, a forward pass is done to obtain predictions of <span class="math-container">$z$</span>, at every <span class="math-container">$t$</span>. Then the adjoint state is run backward in time for every <span class="math-container">$t$</span>. Which gives the learning impulse. So an initial run is done to obtain values of the dynamical system at all time points and the last of these is the initial point for the backward pass.</p> <p>This picture depicts it. <a href="https://i.sstatic.net/qvtfy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qvtfy.png" alt="enter image description here" /></a></p> <p>To be more specific with regards to the question in your initial paragraph the input of <span class="math-container">$t_0$</span> and <span class="math-container">$t_1$</span> into <span class="math-container">$ODE\_Solve$</span> are time points at which the network is evaluated. In this specific case, the first point is <span class="math-container">$t_0$</span> which should always be the case and <span class="math-container">$t_1$</span> is the last point. But you can also insert more time points for example <span class="math-container">$N$</span> time points than you input the sequence <span class="math-container">$t_0, t_1, t_2, ..., t_N$</span> into <span class="math-container">$ODE\_Solve$</span>. In that case, <span class="math-container">$t_N$</span> is the last time point.</p> <p>This picture also shows a lot. But in this picture, a RNN is used to generate <span class="math-container">$z_{t_0}$</span>. The RNN encoder is given the time points in reversed order: <span class="math-container">$(t_N, t_{N-1}, t_{N-2}, ..., t_0)$</span>. <a href="https://i.sstatic.net/YnJnC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YnJnC.png" alt="enter image description here" /></a></p> <p>This is probably not enough to satisfy your question, hopefully, I can get more specific with respect to the math later.</p>
https://ai.stackexchange.com/questions/24040/computation-of-initial-adjoint-for-node
Question: <p>Can we create a learning algorithm that solves all the problems of backpropagation through evolution?</p> Answer: <p>What you are referring to are called evolutionary methods/genetic algorithms/zero order optimizers/many other names.</p> <p>However, it all depends on what you do with them. The core idea of evolution, and thus of this class of algorithms, is to &quot;apply some small perturbation, and only the strongest survive&quot;.</p> <p>However, you need small enough perturbation not to generate degenerate solutions, and given that they are indeed small enough, then in the continuous case, you can see these methods as some sort of finite difference methods for the optimization of a non differentiable system (your environment)</p> <p>In other words, if back propagations gives you <span class="math-container">$\nabla f(x)$</span> in closed form and exact (or with some stochasticity due by the minibatch), evolutionary methods estimate <span class="math-container">$\nabla f(x)\approx \frac{f(x+h)-f(x)}{h}$</span> given <span class="math-container">$h$</span> small enough</p> <p>To conclude... backpropagation is just a way to calculate the gradient of a network, and by itself it has no specific problems, and evolutionary methods are just another way to estimate that same gradient (thus if you were referring to exploding/vanishing gradients, consider that that is a problem of the model, not of the algorithm behind the calculation of the gradient)</p>
https://ai.stackexchange.com/questions/45746/creating-a-replacement-for-backpropagation-through-evolution
Question: <p>I have an odd little problem facing me for my project.</p> <p>I have a smooth polygon defined by parameters.</p> <p>I have convolution transformation, similar to a Gaussian blur. This transformation can only be applied to an image.</p> <p>Consequently, I need to convert the polygon to an image. I then apply the transformation. This is straightforward.</p> <p>However, it is important I am able to backpropagate the gradient back to the parameters of the polygon.</p> <p>I can get the jacobian of the rasterized shape vs the transformed shape. That gives me the derivative with respect to every pixel.</p> <p>But how on earth do I backpropagate it to the original polygon?</p> Answer:
https://ai.stackexchange.com/questions/46614/backpropagation-with-rasterization-step
Question: <p>A am interested in physiologic neural network. Altough there are some opposite views, most probably there seems to be no plausible way to explain a physiologic backpropagation in the brain.</p> <p>So I am trying to code a neural network without backpropagation yet my mathematical understanding is inadaquate, so I want to ask folowing simple question:</p> <p>“If we do have only one node at the right side of the network, accepting that the inputs are on the left, can we train the network without backpropoagation and using the mean of weights instead? As we would know the y for all x it should be possible to calculate the mean w?”</p> <p>The idea is that the system should work continiously, and train continiously for one class, until the trained network decides that the input is different from the known previously trained classes. And if it is different, it should create and train for that new class of inputs. I think that should be the working system of the brain, and as the cortex has similar cells, mathematically it also must be that easy?</p> <p>But where is my flaw (with simplified math please :))</p> Answer:
https://ai.stackexchange.com/questions/34937/do-we-need-backpropagation-if-there-is-only-one-class
Question: <p>I work with a few different automatic differentiation frameworks, including pytorch, Jax, and Flux in Julia. Periodically I run some code and I get errors about mutations or operations occurring &quot;in-place.&quot; These errors generally cause the program to fail. <em>My question is, what does this error mean--in the sense of the AD algorithm and not the specific programming framework?</em></p> <p>So I wanted to understand from a very low level, what the problem is and how to get around it. I believe most AD frameworks focus on reverse mode AD because it is more efficient for a large number of parameters.</p> <p>I am not sure how current AD algorithms are implemented. Older AD systems were based on Wengert lists, while more recent implementations use source-to-source transformations. So just to elaborate on my original equation, does in-place mutation create problems for both source-to-source AD packages and Wengert list/tape based AD packages?</p> <p>Here is my guess at the issue, though I cannot confirm it. It seems like the whole mutation issue has something to do with computing either the forward pass or the backward pass of the AD algorithm. So to compute the gradient, the current value of each variable needs to be known. If we change the value of a variable in the chain in-place, then we compute the wrong gradient at that variable, in that time-step. So that makes sense. But I am not sure if my understanding is correct here. So any clarification is appreciated.</p> <p>After that, how does one write code that avoids this kind of problem? I suppose this question can depend on the AD framework the user is using, but does any operation need to create a new variable instead of reusing existing variables? How smart are these frameworks in handling these types of mutations.</p> Answer: <p>Here is my sense of the answer. In reverse model automatic differentiation (or backpropagation), the automatic differentiation library has to keep track of the values at each stage in the forward pass. These values are stored in memory.</p> <p>When values are changed in-place. then the values stored by the forward pass (as mentioned above), get changed in-place. This change then generates errors as the backward pass computation is working with altered data instead of the original values from the forward pass. Hence automatic differentiation libraries will do things to unroll loops or such to prevent memory locations from being overwritten during the execution of the code.</p> <p>If anyone wants to add some additional detail to this response, please feel free.</p>
https://ai.stackexchange.com/questions/43760/why-does-in-place-mutation-cause-automatic-differentiation-to-fail-and-how-to
Question: <p>I will give an example of wishful thinking. When you try to prove a theorem you think what would imply that theorem and maybe try to find a lemma that implies it. Maybe neurons try to connect previous neurons that has the relevant information. I am not knowledgeable in the subject.</p> Answer: <p>The short answer is no. The network isn't thinking, wishing, or desiring. The training process is simply trying to minimize the loss/error between the model output and the predicted output. The effect is that a complex function is modeled. It would be more correct to think of this in terms of an expectation function.</p>
https://ai.stackexchange.com/questions/48451/do-neural-networks-do-wishful-thinking
Question: <p>Assuming that the cost function <span class="math-container">$J$</span> is the average of the loss function <span class="math-container">$\mathcal{L}$</span> over all training examples <span class="math-container">$m$</span></p> <p><span class="math-container">$J(w) = \frac{1}{m} \displaystyle\sum_{i=0}^{m} \mathcal{L}$</span></p> <p>why do we update the parameters with respect to the cost function</p> <p><span class="math-container">$w := w - \alpha \frac{dJ}{dw}$</span></p> <p>instead of updating the parameters at each iteration with respect to its loss?</p> <pre><code>for i in m: w = w - learning_rate*(dL/dw) </code></pre> Answer: <p>The objective in parametric ML is to find parameter values that minimize the overall cost function <span class="math-container">$J(w)$</span> across the entire training dataset, whether in terms of the framework of empirical risk minimization (ERM) or information-theoretic cross-entropy (CE). Intuitively minimizing the average cost over <em>all</em> examples leads to a more <em>generalizable</em> model as it helps the model generalize well to unseen data rather than being influenced too heavily by the noise or fluctuations in individual examples.</p> <p>Having said that, in the common stochastic gradient descent (SGD) training method, if your minibatch size is 1 then effectively during each batch you're updating the parameters w.r.t the loss of the single current sample, and this can be proved to be convergent under certain conditions albeit at a lower rate as referenced <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>The sum-minimization problem also arises for empirical risk minimization. There, <span class="math-container">${Q_{i}(w)}$</span> is the value of the loss function at <span class="math-container">${i}$</span>-th example, and <span class="math-container">${Q(w)}$</span> is the empirical risk... However, in other cases, evaluating the sum-gradient may require expensive evaluations of the gradients from all summand functions. When the training set is enormous and no simple formulas exist, evaluating the sums of gradients becomes very expensive, because evaluating the gradient requires evaluating all the summand functions' gradients. To economize on the computational cost at every iteration, stochastic gradient descent samples a subset of summand functions at every step.</p> </blockquote> <blockquote> <p>The convergence of stochastic gradient descent has been analyzed using the theories of convex minimization and of stochastic approximation. Briefly, when the learning rates <span class="math-container">${\eta }$</span> decrease with an appropriate rate, and subject to relatively mild assumptions, stochastic gradient descent converges almost surely to a global minimum when the objective function is convex or pseudoconvex, and otherwise converges almost surely to a local minimum. This is in fact a consequence of the Robbins–Siegmund theorem.</p> </blockquote>
https://ai.stackexchange.com/questions/45044/why-do-we-update-parameters-with-respect-to-cost-instead-of-loss
Question: <p>This is the back-propogation rule for the output layer of a multi-layer network:</p> <p><span class="math-container">$$W_{jk} := W_{jk} - C \dfrac{\delta E}{\delta W_{jk}}$$</span></p> <p>What does this rule do in the more ambiguous cases such as:</p> <p>(1) The output of a hidden node is near the middle of a sigmoid curve?</p> <p>(2) The graph of error with respect to weight is near a maximum or minimum?</p> Answer: <p>I assume you are considering a network where the activation function of the last layer is a sigmoid, so the output of your network is <span class="math-container">$$\tilde{y}=\sigma(W^{L}\cdot f(X, W^1, \dots, W^{L-1})),$$</span> where <span class="math-container">$X$</span> is the input vector, and <span class="math-container">$f$</span> is obtained by feeding the input to the network up to the layer <span class="math-container">$L-1$</span>. Let's also call <span class="math-container">$Z:= W^{L}\cdot f(X, W^1, \dots, W^{L-1})$</span>.</p> <p>The error term is computed as <span class="math-container">$$E(y, \tilde{y})=E(y, \sigma(Z)),$$</span> where <span class="math-container">$y$</span> is the actual output. Let's get the derivative of the error with respect to the output of the last node (the input of the sigmoid) <span class="math-container">$$\frac{\partial E}{z_i}=\frac{\partial E}{\partial \tilde{y}}\frac{\partial\tilde{y}}{\partial z_i}=\frac{\partial E}{\partial \tilde{y}}\frac{\partial\sigma}{\partial z_i}.$$</span> The update rule is <span class="math-container">$$z_i =z_i - C\frac{\partial E}{z_i}= z_i - C\frac{\partial E}{\partial \tilde{y}}\frac{\partial\sigma}{\partial z_i}.$$</span> Now we can analyse your questions.</p> <ol> <li>To be close to the middle of the sigmoid means that <span class="math-container">$z_i$</span> is close to <span class="math-container">$0$</span>; moreover the derivative <span class="math-container">$\frac{\partial\sigma}{\partial z_i}$</span> reaches its maximum value when it is evaluated in <span class="math-container">$0$</span>. This means that the term <span class="math-container">$\frac{\partial\sigma}{\partial z_i}$</span> gets &quot;large&quot; as <span class="math-container">$z_i$</span> approaches the center of the sigmoid, contributing more to the update of the weight. Of course it is difficult to say what happens in general, as the term <span class="math-container">$\frac{\partial E}{\partial \tilde{y}}$</span> is also in the expression and it is possible that this term gets really small (or big) for <span class="math-container">$z_i$</span> close to <span class="math-container">$0$</span>. You just know that the term <span class="math-container">$\frac{\partial\sigma}{\partial z_i}$</span> is trying to push <span class="math-container">$z_i$</span> further away from <span class="math-container">$0$</span>, so the idea should be that the closer to the center the larger the update.</li> <li>To be close to an extremum point of the loss means that the derivative of the loss with respect to <span class="math-container">$\tilde{y}$</span> is close to <span class="math-container">$0$</span>. Since <span class="math-container">$\frac{\partial E}{\partial \tilde{y}}$</span> is backpropagated in a multiplicative fashion, the rule of thumb is that the closer you are to an extremum the smaller the updates get. Though, as above, is kind of difficult to say what will happen when updating a general node, as some of the term in the multiplication can be very large, making the update large even if <span class="math-container">$\frac{\partial E}{\partial \tilde{y}}$</span> is small.</li> </ol> <p>For instance, what happens if you are close to the center of the sigmoid but also close to an extremum of the loss? You will have a multiplication of <span class="math-container">$2$</span> terms, one trying to make the update small and the other trying to make the update large, and what matter are the orders of magnitude involved.<br /> In conclusion, the rules of thumb are as in the points 1. and 2., but they are no guarantee that you won't find any special cases.</p>
https://ai.stackexchange.com/questions/25500/backpropogation-rule-for-the-output-layer-of-a-multi-layer-network-what-does-t
Question: <p>We have always known that gradient descent is a function of two or more variables. But how can we geometrically represent gradient descent if it is a function of only one variable?</p> Answer: <p>For a function of one variable, there are only two options for directions in the domain: left or right, so it becomes almost trivial, but you can still talk about gradient descent.</p> <p>You would take steps to the left if the slope/derivative is positive and make steps to the right if the slope/derivative is negative--i.e. the opposite direction of the derivative (the 1d version of the "gradient" in gradient descent), which is equivalent to the higher dimensional case.</p>
https://ai.stackexchange.com/questions/3668/how-would-1d-gradient-descent-look-like
Question: <p>I'm trying to implement a simple neural network for classification (multi-class) as an exercise (written in C). During gradient descent, the weights and biases quickly get out of control and the gradient becomes infinite.</p> <p>I haven't been able to find any discussion of such problems (vanishing gradients is kind of the opposite).</p> <p>To be more specific, for testing I use a very simple network with 1 hidden layer and sigmoid as activation function. For the output layer I use softmax and logarithmic loss.</p> <p>The issue as I see it is that when an output activation is very small, for the derivative of the loss I basically get <code>1 / &lt;very_small number&gt;</code> and this leads to an enormous gradient.</p> <p>Am I doing something wrong in terms of network architecture? What is the typical way to deal with such problems?</p> Answer: <p>You're describing exploding gradients, which as you noted is the opposite issue of vanishing gradients. Both these problems arise from the process of propagating and backpropagating activations/errors through the network. The intuition is that repeated multiplications of numbers less than 1 rapidly leads to a product of 0, while repeated multiplications of numbers greater than 1 rapidly leads to a product which tends to infinity.</p> <p>The number of matrix multiplications you need to perform increases with the number of layers, which is why this tends to be a problem with deeper networks. In particular, recurrent neural networks are infamously susceptible to vanishing/exploding gradients as a result of propagating through each layer multiple times corresponding to each time step.</p> <p>Careful choice of activation functions, proper weight initialization, and gradient clipping are the standard ways to address this problem, though more specialized solutions can arise depending on the context (for example, for RNNs, entirely new types of neurons, LSTMs and GRUs, were developed to address the issue).</p>
https://ai.stackexchange.com/questions/36567/numerical-problems-with-gradient-descent
Question: <p>Andrew Ng said in his slide that: <a href="https://i.sstatic.net/ImraM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ImraM.png" alt="enter image description here" /></a> However, there are numerous types of 'learning rate schedules' in TensorFlow that change the learning rate profile as training progresses.</p> <p>If it's true that these adjustments are redundant then why do we need learning rate schedules?</p> Answer: <p>In one hand you have the fact that if the initial step-size is a bit too optimistic, decay will at some point lead to a step-size that works</p> <p>However, there is a much more theoretical reason for it.<br /> Indeed if you consider a non-smooth function, it's necessary sometimes to converge to decay your stepsize...</p> <p>As an example, consider <span class="math-container">$f(x) = |x|$</span>, with an initial guess of <span class="math-container">$x = 2.5$</span> and a stepsize of <span class="math-container">$\alpha = 1$</span></p> <p>Well, the gradient of such function is <span class="math-container">$1$</span> if <span class="math-container">$x &gt; 0$</span> and <span class="math-container">$-1$</span> if <span class="math-container">$x &lt; 0$</span></p> <p>Now, apply GD: <span class="math-container">$x = x - \alpha \nabla_x f(x) \rightarrow x = x - \nabla_x f(x)$</span>, and considering that the gradient on <span class="math-container">$x = 2.5$</span> is also 1, becomes <span class="math-container">$x = x - 1$</span></p> <p>Therefore, you will start from 2.5, then next time go to 1.5, then again to 0.5, and at that point, you'll jump to -0.5, and from there jump back to 0.5</p> <p>As you can see, you will never converge to the optimal <span class="math-container">$x = 0$</span>, except if you decay your stepsize</p>
https://ai.stackexchange.com/questions/43523/why-use-learning-rate-schedules-if-weight-updates-automatically-decrease-when-ap
Question: <p>imaging input vector a = {a1,a2,a3} and z = softmax(a) = {z1,z2,z3}</p> <p>So, we expect than gradient of z with respect of a would be the same shape as vector a (so we can make gradient step: a = a - learning rate * dz/da). But the real shape is (3,3). So what should i do to make the gradient step? <a href="https://i.sstatic.net/g3uG12Iz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/g3uG12Iz.png" alt="enter image description here" /></a></p> Answer: <p>(ignoring the fact that is probably the other way around, meaning <span class="math-container">$z$</span> are the logits, <span class="math-container">$a = softmax(z)$</span>)</p> <p>Automatic differentiation expects you to take the derivative of a function <span class="math-container">$f: R^N \rightarrow R$</span>, where <span class="math-container">$f$</span> for example can be the loss function.</p> <p>If you have multiple outputs, you cannot apply GD, except if you &quot;collapse/aggregate&quot; these multiple outputs (for example, taking the mean)</p> <p>From an intuitive perspective, that matrix is telling you &quot;how to change <span class="math-container">$z$</span> so that <span class="math-container">$a$</span> increases&quot;... you have to decide which of these &quot;<span class="math-container">$a$</span>&quot; should increase, or, taking the mean of them, averaging over the gradients</p>
https://ai.stackexchange.com/questions/47062/softmax-gradient-for-automatic-differentiation
Question: <p>I have 10000 tuples of numbers <code>(x1, x2, y)</code> generated from the equation: <code>y = np.cos(0.583 * x1) + np.exp(0.112 * x2)</code>. I want to use a neural network, trained with gradient descent, in PyTorch, to find the 2 parameters, i.e. 0.583 and 0.112</p> <p>Here is my code:</p> <pre><code>class NN_test(nn.Module): def __init__(self): super().__init__() self.a = torch.nn.Parameter(torch.tensor(0.7)) self.b = torch.nn.Parameter(torch.tensor(0.02)) def forward(self, x): y = torch.cos(self.a*x[:,0])+torch.exp(self.b*x[:,1]) return y model = NN_test().cuda() lrs = 1e-4 optimizer = optim.SGD(model.parameters(), lr = lrs) loss = nn.MSELoss() epochs = 30 for epoch in range(epochs): model.train() for i, dtt in enumerate(my_dataloader): optimizer.zero_grad() inp = dtt[0].float().cuda() output = dtt[1].float().cuda() ls = loss(model(inp),output) ls.backward() optimizer.step() if epoch%1==0: print("Epoch: " + str(epoch), "Loss Training: " + str(ls.data.cpu().numpy())) </code></pre> <p>where <code>x</code> contains the 2 numbers <code>x1</code> and <code>x2</code>. In theory, it should work easily, but the loss doesn't go down. What am I doing wrong? </p> Answer:
https://ai.stackexchange.com/questions/17239/how-can-i-train-a-neural-network-to-find-the-hyper-parameters-with-which-the-dat
Question: <p>The gradient descent step is the following</p> <p><span class="math-container">\begin{align} \mathbf{W}_i = \mathbf{W}_{i-1} - \alpha * \nabla L(\mathbf{W}_{i-1}) \end{align}</span></p> <p>were <span class="math-container">$L(\mathbf{W}_{i-1})$</span> is the loss value, <span class="math-container">$\alpha$</span> the learning rate and <span class="math-container">$\nabla L(\mathbf{W}_{i-1})$</span> the gradient of the loss.</p> <p>So, how do we get to the <span class="math-container">$L(\mathbf{W}_{i-1})$</span> to calculate the gradient of <span class="math-container">$L(\mathbf{W}_{i-1})$</span>? As an example, we can initialize the set of <span class="math-container">$\mathbf{W}$</span> to 0.5. How can you explain it to me?</p> Answer: <p>In your case, <span class="math-container">$L$</span> is the loss (or cost) function, which can be, for example, the <a href="https://en.wikipedia.org/wiki/Mean_squared_error" rel="nofollow noreferrer">mean squared error (MSE)</a> or the cross-entropy, depending on the problem you want to solve. Given one training example <span class="math-container">$(\mathbf{x}_i, y_i) \in D$</span>, where <span class="math-container">$\mathbf{x}_i \in \mathbb{R}^d$</span> is the input (for example, an image) and <span class="math-container">$y_i \in \mathbb{R}$</span> can either be a label (aka class) or a numerical value, and <span class="math-container">$D$</span> is your training dataset, then the <a href="https://en.wikipedia.org/wiki/Mean_squared_error" rel="nofollow noreferrer">MSE</a> is defined as follows</p> <p><span class="math-container">$$L(\mathbf{W}) = \frac{1}{2} \left(f(\mathbf{x}_i) - y_i \right)^2,$$</span></p> <p>where <span class="math-container">$f(\mathbf{x}_i) \in \mathbb{R}$</span> is the output of the neural network <span class="math-container">$f$</span> given the input <span class="math-container">$\mathbf{x}_i$</span>.</p> <p>If you have a mini-batch of <span class="math-container">$M$</span> training examples <span class="math-container">$\{(\mathbf{x}_i, y_i) \}_{i=1}^M$</span>, then the loss will be an average of the MSE for each training example. For more info, have a look at this answer <a href="https://ai.stackexchange.com/a/11675/2444">https://ai.stackexchange.com/a/11675/2444</a>. The <a href="https://ai.stackexchange.com/a/8985/2444">https://ai.stackexchange.com/a/8985/2444</a> may also be useful.</p> <p>See the article <a href="https://machinelearningmastery.com/loss-and-loss-functions-for-training-deep-learning-neural-networks/" rel="nofollow noreferrer">Loss and Loss Functions for Training Deep Learning Neural Networks</a> for more info regarding different losses used in deep learning and how to choose the appropriate loss for your problem.</p>
https://ai.stackexchange.com/questions/17295/how-is-the-loss-value-calculated-in-order-to-compute-the-gradient
Question: <p>I found this <a href="https://ai.stackexchange.com/questions/25109/is-there-anything-that-ensures-that-convolutional-filters-dont-end-up-the-same">question</a> very interesting, and this is a follow up on it.</p> <p>Presumably, we'd want all the filters to converge towards some complementary set, where each filter fills as large a niche as possible (in terms of extracting useful information from the previous layer), without overlapping with another filter.</p> <p>A quick thought experiment tells me (please correct me if I'm wrong) that if two filters are identical down to maximum precision, then without adding in any other form of stochastic differentiation between them, their weights will be updated in the same way at each step of gradient descent during training. Thus, it would be a very bad idea to initialise all filters in the same way prior to training, as they would all be updated in exactly the same way (see footnote 1).</p> <p>On the other hand, a quick thought experiment isn't enough to tell me what would happen to two filters that are <em>almost</em> identical, as we continue to train the network. <strong>Is there some mechanism causing them to then diverge away from one another, thereby filling their own &quot;complementary niches&quot; in the layer?</strong> My intuition tells me that there must be, otherwise using many filters just wouldn't work. But during back-propagation, each filter is downstream, and so they don't have any way of communicating with one another. At the risk of anthropomorphising the network, I might ask &quot;How do the two filters collude with one another to benefit the network as a whole?&quot;</p> <hr /> <p>Footnotes:</p> <ol> <li>Why do I think this? Because the expession for the partial derivative of the <span class="math-container">$k$</span>th filter weights with respect to the cost <span class="math-container">$\partial W^k/\partial C$</span> will be identical for all <span class="math-container">$k$</span>. From the perspective of back-propagation, all paths through the filters look exactly the same.</li> </ol> Answer: <p>Yes, your thought experiment is correct, and the concept is known as <strong>breaking the symmetry</strong>. This is why biases can be initialized to <span class="math-container">$0$</span> (bias initialization doesn't matter), but weights should be randomly initialized to different numbers -- to break the symmetry. Otherwise, if not, the network will function as if it has <span class="math-container">$n-1$</span> filters (or however many filters that are unique) instead of the full <span class="math-container">$n$</span> filters.</p> <p>As for your main question, if two filters are initialized to very similar values, they may branch out as long as that is what minimizes the training loss. There is no collusion or coordination going on; each filter updates completely independently. You can even freeze all the other filters and only perform gradient descent on one filter at a time. Each filter just follows the direction of their gradient to minimize the training loss.</p> <p>Consider the backprop equations as defined by <a href="http://neuralnetworksanddeeplearning.com/chap2.html" rel="nofollow noreferrer">this</a> online book:</p> <p><a href="https://i.sstatic.net/D5xG0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/D5xG0.png" alt="enter image description here" /></a></p> <p>The gradient of the current layer's weights depends on</p> <ol> <li>The future layers' weights, errors, and activation function's derivatives</li> <li>The current layer's activation function's derivative, and</li> <li>The previous layer's outputs.</li> </ol> <p>Each weight in the layer (i.e. each filter in the layer) looks at different parts of these three components (indexed by <span class="math-container">$j$</span> and <span class="math-container">$k$</span> in equation <span class="math-container">$BP4$</span>). It is this different perspective that allows them to update their gradients in different directions, even if their initial weights are very similar to each other. Note that it is possible that they end up with the same gradient, but it is very unlikely.</p>
https://ai.stackexchange.com/questions/25464/is-there-anything-that-ensures-that-convolutional-filters-end-up-different-from
Question: <p>When we perform gradient descent, especially in an online setting where the training data is presented in a non-random order, a particular 1-dimensional parameter (such as an edge weight) may first travel in one direction, then turn around and travel the other way for a while, then turn around and travel back, and so forth. This is wasteful, and the problem is that the learning rate for that parameter was too high, making it overshoot the optimal point. We don't want parameters to oscillate as they are trained; instead, ideally, they should settle directly to their final values, like a critically damped spring.</p> <p>Is there an optimizer that sets learning rates based on this concept? Rprop seems related, in that it reduces the learning rate whenever the gradient changes direction. The problem with Rprop is that it only detects oscillations of period 2. What if the oscillation is longer, e.g. the parameter is moving in a sine wave with a period of dozens or hundreds of time steps? Looking for an optimizer that can suppress oscillations of any period length.</p> <p>Let's be specific. Say that <span class="math-container">$w$</span> is a parameter, receiving a sequence of gradient updates <span class="math-container">$g_0, g_1, g_2, ... $</span> . I am looking for an optimizer that would pass the following tests:</p> <ul> <li>If <span class="math-container">$g_t = sin(t) - w$</span>, then <span class="math-container">$w$</span> should settle to the value 0.</li> <li>If <span class="math-container">$g_t = sin(t) + 100 - 100 cos(0.00001t) - w$</span>, then <span class="math-container">$w$</span> should settle to the value 100.</li> <li>If <span class="math-container">$g_t = sin(t) - w$</span> for <span class="math-container">$0 &lt; t &lt; 1000000$</span>, and <span class="math-container">$g_t = sin(t) + 100 - w$</span> for <span class="math-container">$1000000 \leq t$</span>, then <span class="math-container">$w$</span> should at first settle to the value 0, and then not too long after time step <span class="math-container">$1000000$</span> it should settle to the value 100.</li> <li>If <span class="math-container">$g_t = sin(t) - w$</span> for <span class="math-container">$floor(t / 1000000)$</span> even, and <span class="math-container">$g_t = sin(t) + 100 - w$</span> for <span class="math-container">$floor(t / 1000000)$</span> odd, then <span class="math-container">$w$</span> should at first settle to the value 0, then not too long after time step <span class="math-container">$1000000$</span> it should settle to the value 100, and then not too long after step <span class="math-container">$2000000$</span> it should settle back to 0, but <em>eventually</em> after enough iterations it should settle to the value 50 and stop changing forever after.</li> </ul> Answer:
https://ai.stackexchange.com/questions/27117/optimizer-that-prevents-parameters-from-oscillating
Question: <p>In doing a project using neural networks with an input layer, 4 hidden layers and an output layer ,I used mini batch gradient descent. I noticed that the randomly initialised weights seemed to do a good performance and gave a low error. As the model started training after about 200 iterations there was large jump in error and then it came down slowly from there. I have also noticed that sometimes the cost just increases over a set of consecutive iterations. Can anyone explain why these happen? It is not like there are outliers or a new distribution as every iteration exposes it to the entire dataset. I used learning rate 0.01 and regularisation parameter 10. I also tried regularisation parameter 5 and also 1. And by the cost I mean, the sum of squared errors of all minibatches/2m plus regularisation term error. Further if this happens and my cost after the say 10000th iteration is more than my cost when I initialised with random weights (lol) can I just take the initial value? As those weights seem to be doing better.</p> <p>The large jumps are the most puzzling. </p> <p>This is the code</p> <p>Any help would be greatly appreciated. Thanks</p> Answer: <p>I would say just don't go for using regularization at first, try with lower <code>learning rate = 0.0001</code> see the behavior. Try to post entire architecture of your model so that one can better answer your problem.</p>
https://ai.stackexchange.com/questions/7362/behaviour-of-cost
Question: <p>I have a dataset with an input size of 155x155, with the output being 155 x 1 with a 3-4 layer neural net being used for regression. With such a small sample size, should I use full batch gradient descent (so all 155 samples) or use mini batch/stochastic gradient descent. I have read that using smaller mini batch sizes allows better generalisation, but as the batch size is very very small computationally it shouldn't be a burden to use BGD.</p> Answer:
https://ai.stackexchange.com/questions/26468/should-i-use-batch-gradient-descent-when-i-have-a-small-sample-size
Question: <p>Let’s say I have a neural net doing classification and I’m doing stochastic gradient descent to train it. If I know that my current approximation is a decent approximation, can I conclude that my gradient is a decent approximation of the gradient of the true classifier everywhere?</p> <p>Specifically, suppose that I have a true loss function, $f$, and an estimation of it, $f_k$. Is it the case that there exists a $c$ (dependent on $f_k$) such that for all $x$ and $\epsilon &gt; 0$ if $|f(x)-f_k(x)|&lt;\epsilon$ then $|\nabla f(x) - \nabla f_k(x)|&lt;c\epsilon$? This isn’t true for general functions, but it may be true for neural nets. If this exact statement isn’t true, is there something along these lines that is? What if we place some restrictions on the NN?</p> <p>The goal I have in mind is that I’m trying to figure out how to calculate how long I can use a particular sample to estimate the gradient without the error getting too bad. If I am in a context where resampling is costly, it may be worth reusing the same sample many times as long as I’m not making my error too large. My long-term goal is to come up with a bound on how much error I have if I use the same sample $k$ times, which doesn’t seem to be something in the literature as far as I’ve found.</p> Answer: <p>In general <span class="math-container">$|f(x) - f_k(x)| \leq \epsilon$</span> doesn't ensure <span class="math-container">$|\nabla f(x) - \nabla f_k(x)| \leq c\epsilon$</span>. And for neural networks there is no reason to believe it will happen either. </p> <p>You can also look at Sobolev Training Paper (<a href="https://arxiv.org/abs/1706.04859" rel="nofollow noreferrer">https://arxiv.org/abs/1706.04859</a>). In particular, note that Sobolev training was better than critic training, which indirectly may indicate approximating function may not be the same as approximating gradient and function. In Sobolev training, the network is trained to match gradient and function whereas in critic training network is trained to match function. They produce quite different results which might give us some hints about the above problem. </p> <p>In general, if two functions are arbitrary close, they might not be close in gradients.</p> <p>Edit: (Trying to come up with a negative example) Consider <span class="math-container">$f(x) = g(x) + \epsilon \sin (\frac {kx} {\epsilon}) $</span>. <span class="math-container">$g(x)$</span> is some neural network. Now, we train some another neural network <span class="math-container">$h(x)$</span> to fit <span class="math-container">$f(x)$</span> and after training we get <span class="math-container">$h(x) = g(x)$</span> (<span class="math-container">$h(x)$</span> and <span class="math-container">$g(x)$</span> have same weights precisely). However, <span class="math-container">$\nabla f_x =\nabla g_x + k\cos (\frac {kx} {\epsilon})$</span> is not arbitarariy close <span class="math-container">$\nabla g_x$</span>. </p> <p>I hope this example is enough to prove that a neural network that nicely approximates the function may not nicely approximate the gradients and no such result can be proved mathematically rigorously. However, considering the paper in the discussion, you might think for practical purposes it works. However, if you have both function and grad information available that is expected to work better. </p>
https://ai.stackexchange.com/questions/8080/do-good-approximations-produce-good-gradients
Question: <p>I've come across the concept of fitness landscape before and, in my understanding, a smooth fitness landscape is one where the algorithm can converge on the global optimum through incremental movements or iterations across the landscape.</p> <p>My question is: <strong>Does deep learning assume that the fitness landscape on which the gradient descent occurs is a smooth one? If so, is it a valid assumption?</strong></p> <p>Most of the graphical representations I have seen of gradient descent show a smooth landscape.</p> <p>This <a href="https://en.m.wikipedia.org/wiki/Fitness_landscape" rel="nofollow noreferrer">Wikipedia page</a> describes the fitness landscape.</p> Answer: <p>I'm going to take the fitness landscape to be the <a href="https://en.wikipedia.org/wiki/Graph_of_a_function#Definition" rel="nofollow noreferrer">graph</a> of the loss function, <span class="math-container">$\mathcal{G} = \{\left(\theta, L(\theta)\right) : \theta \in \mathbb{R}^n\}$</span>, where <span class="math-container">$\theta$</span> parameterises the network (i.e. it is the weights and biases) and <span class="math-container">$L$</span> is a given loss function; in other words, the surface you would get by plotting the loss function against its parameters.</p> <p>We always assume the loss function is differentiable in order to do backpropagation, which means at the very least the loss function is smooth enough to be continuous, but in principle it may not be infinitely differentiable<sup>1</sup>.</p> <p>You talk about using gradient descent to find the global minimiser. In general this is not possible: many functions have local minimisers which are not global minimisers. For an example, you could plot <span class="math-container">$y = x^2 \sin(1/x^2)$</span>: of course the situation is similar, if harder to visualise, in higher dimensions. A certain class of functions known as <strong>convex functions</strong> satisfy the property that any local minimiser is a global minimiser. Unfortunately, the loss function of a neural network is rarely convex.</p> <p>For some interesting pictures, see <a href="https://papers.nips.cc/paper/2018/file/a41b3bb3e6b050b6c9067c67f663b915-Paper.pdf" rel="nofollow noreferrer"><em>Visualizing the Loss Landscape of Neural Nets</em></a> by Li et al.</p> <hr /> <p><sup>1</sup> For a more detailed discussion on continuity and differentiability, any good text on mathematical analysis will do, for example Rudin's <em>Principles of Mathematical Analysis</em>. In general, any function <span class="math-container">$f$</span> that is differentiable on some interval is also continuous, but it need not be twice differentiable, i.e. <span class="math-container">$f''$</span> need not exist.</p>
https://ai.stackexchange.com/questions/27231/does-gradient-descent-in-deep-learning-assume-a-smooth-fitness-landscape