How does Tensorflow's reduce_sum work in a loop?












1














I cannot understand the working of reduce_sum when the optimizer is run in a loop.



I have 30 samples in my train_x and train_y lists. I run my optimizer in a loop by feeding one sample from both at an iteration. My cost function computes the sum of the difference of predicted and actual values for all samples using the tensorflow's reduce_sum method. According to the graph the optimzer depends on the cost function and so the cost will be computed for every x and y. I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time. Here n_samples is 30. I also need to know whether the weights and bias will be updated for each epoch or for each x and y.



X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

W = tf.Variable(np.random.randn(), name='weights')
B = tf.Variable(np.random.randn(), name='bias')

pred = X * W + B

cost = tf.reduce_sum((pred - Y) ** 2) / (2 * n_samples)

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sesh:
sesh.run(init)

for epoch in range(epochs):
for x, y in zip(train_x, train_y):
sesh.run(optimizer, feed_dict={X: x, Y: y})

if not epoch % 20:
c = sesh.run(cost, feed_dict={X: train_x, Y: train_y})
w = sesh.run(W)
b = sesh.run(B)
print(f'epoch: {epoch:04d} c={c:.4f} w={w:.4f} b={b:.4f}')









share|improve this question







New contributor




Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    1














    I cannot understand the working of reduce_sum when the optimizer is run in a loop.



    I have 30 samples in my train_x and train_y lists. I run my optimizer in a loop by feeding one sample from both at an iteration. My cost function computes the sum of the difference of predicted and actual values for all samples using the tensorflow's reduce_sum method. According to the graph the optimzer depends on the cost function and so the cost will be computed for every x and y. I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time. Here n_samples is 30. I also need to know whether the weights and bias will be updated for each epoch or for each x and y.



    X = tf.placeholder(tf.float32)
    Y = tf.placeholder(tf.float32)

    W = tf.Variable(np.random.randn(), name='weights')
    B = tf.Variable(np.random.randn(), name='bias')

    pred = X * W + B

    cost = tf.reduce_sum((pred - Y) ** 2) / (2 * n_samples)

    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

    init = tf.global_variables_initializer()

    with tf.Session() as sesh:
    sesh.run(init)

    for epoch in range(epochs):
    for x, y in zip(train_x, train_y):
    sesh.run(optimizer, feed_dict={X: x, Y: y})

    if not epoch % 20:
    c = sesh.run(cost, feed_dict={X: train_x, Y: train_y})
    w = sesh.run(W)
    b = sesh.run(B)
    print(f'epoch: {epoch:04d} c={c:.4f} w={w:.4f} b={b:.4f}')









    share|improve this question







    New contributor




    Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      1












      1








      1


      1





      I cannot understand the working of reduce_sum when the optimizer is run in a loop.



      I have 30 samples in my train_x and train_y lists. I run my optimizer in a loop by feeding one sample from both at an iteration. My cost function computes the sum of the difference of predicted and actual values for all samples using the tensorflow's reduce_sum method. According to the graph the optimzer depends on the cost function and so the cost will be computed for every x and y. I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time. Here n_samples is 30. I also need to know whether the weights and bias will be updated for each epoch or for each x and y.



      X = tf.placeholder(tf.float32)
      Y = tf.placeholder(tf.float32)

      W = tf.Variable(np.random.randn(), name='weights')
      B = tf.Variable(np.random.randn(), name='bias')

      pred = X * W + B

      cost = tf.reduce_sum((pred - Y) ** 2) / (2 * n_samples)

      optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

      init = tf.global_variables_initializer()

      with tf.Session() as sesh:
      sesh.run(init)

      for epoch in range(epochs):
      for x, y in zip(train_x, train_y):
      sesh.run(optimizer, feed_dict={X: x, Y: y})

      if not epoch % 20:
      c = sesh.run(cost, feed_dict={X: train_x, Y: train_y})
      w = sesh.run(W)
      b = sesh.run(B)
      print(f'epoch: {epoch:04d} c={c:.4f} w={w:.4f} b={b:.4f}')









      share|improve this question







      New contributor




      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I cannot understand the working of reduce_sum when the optimizer is run in a loop.



      I have 30 samples in my train_x and train_y lists. I run my optimizer in a loop by feeding one sample from both at an iteration. My cost function computes the sum of the difference of predicted and actual values for all samples using the tensorflow's reduce_sum method. According to the graph the optimzer depends on the cost function and so the cost will be computed for every x and y. I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time. Here n_samples is 30. I also need to know whether the weights and bias will be updated for each epoch or for each x and y.



      X = tf.placeholder(tf.float32)
      Y = tf.placeholder(tf.float32)

      W = tf.Variable(np.random.randn(), name='weights')
      B = tf.Variable(np.random.randn(), name='bias')

      pred = X * W + B

      cost = tf.reduce_sum((pred - Y) ** 2) / (2 * n_samples)

      optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

      init = tf.global_variables_initializer()

      with tf.Session() as sesh:
      sesh.run(init)

      for epoch in range(epochs):
      for x, y in zip(train_x, train_y):
      sesh.run(optimizer, feed_dict={X: x, Y: y})

      if not epoch % 20:
      c = sesh.run(cost, feed_dict={X: train_x, Y: train_y})
      w = sesh.run(W)
      b = sesh.run(B)
      print(f'epoch: {epoch:04d} c={c:.4f} w={w:.4f} b={b:.4f}')






      tensorflow






      share|improve this question







      New contributor




      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked yesterday









      Gautham Pughazhendhi

      61




      61




      New contributor




      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Gautham Pughazhendhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          1 Answer
          1






          active

          oldest

          votes


















          0















          I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time.




          tf.reduce_sum is an operation and as such it does not have any implicit mutable state. The result of tf.reduce_sum is fully defined by the model parameters (W and B) and the placeholder values explicitly provided in the feed_dict argument to the sess.run(cost, feed_dict={...}) call.



          If you would like to aggregate the value of a metric across all batches check out tf.metrics:



          y_pred = tf.placeholder(tf.float32)
          y_true = tf.placeholder(tf.float32)
          mse, update_op = tf.metrics.mean_squared_error(y_true, y_pred)
          init = tf.local_variables_initializer() # MSE state is local!
          sess = tf.Session()
          sess.run(init)

          # Update the metric and compute the value after the update.
          sess.run(update_op, feed_dict={y_pred: [0.0], y_true: [42.0]}) # => 1764.0
          # Get current value.
          sess.run(mse) # => 1764.0



          I also need to know whether the weights and bias will be updated for each epoch or for each x and y.




          Each sess.run(optimizer, ...) call will compute the gradients of the trainable variables and apply these gradients to the variable values. See GradientDescentOptimizer.minimize.






          share|improve this answer





















          • Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
            – Gautham Pughazhendhi
            14 hours ago










          • The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
            – Sergei Lebedev
            8 hours ago











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Gautham Pughazhendhi is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53943659%2fhow-does-tensorflows-reduce-sum-work-in-a-loop%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0















          I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time.




          tf.reduce_sum is an operation and as such it does not have any implicit mutable state. The result of tf.reduce_sum is fully defined by the model parameters (W and B) and the placeholder values explicitly provided in the feed_dict argument to the sess.run(cost, feed_dict={...}) call.



          If you would like to aggregate the value of a metric across all batches check out tf.metrics:



          y_pred = tf.placeholder(tf.float32)
          y_true = tf.placeholder(tf.float32)
          mse, update_op = tf.metrics.mean_squared_error(y_true, y_pred)
          init = tf.local_variables_initializer() # MSE state is local!
          sess = tf.Session()
          sess.run(init)

          # Update the metric and compute the value after the update.
          sess.run(update_op, feed_dict={y_pred: [0.0], y_true: [42.0]}) # => 1764.0
          # Get current value.
          sess.run(mse) # => 1764.0



          I also need to know whether the weights and bias will be updated for each epoch or for each x and y.




          Each sess.run(optimizer, ...) call will compute the gradients of the trainable variables and apply these gradients to the variable values. See GradientDescentOptimizer.minimize.






          share|improve this answer





















          • Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
            – Gautham Pughazhendhi
            14 hours ago










          • The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
            – Sergei Lebedev
            8 hours ago
















          0















          I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time.




          tf.reduce_sum is an operation and as such it does not have any implicit mutable state. The result of tf.reduce_sum is fully defined by the model parameters (W and B) and the placeholder values explicitly provided in the feed_dict argument to the sess.run(cost, feed_dict={...}) call.



          If you would like to aggregate the value of a metric across all batches check out tf.metrics:



          y_pred = tf.placeholder(tf.float32)
          y_true = tf.placeholder(tf.float32)
          mse, update_op = tf.metrics.mean_squared_error(y_true, y_pred)
          init = tf.local_variables_initializer() # MSE state is local!
          sess = tf.Session()
          sess.run(init)

          # Update the metric and compute the value after the update.
          sess.run(update_op, feed_dict={y_pred: [0.0], y_true: [42.0]}) # => 1764.0
          # Get current value.
          sess.run(mse) # => 1764.0



          I also need to know whether the weights and bias will be updated for each epoch or for each x and y.




          Each sess.run(optimizer, ...) call will compute the gradients of the trainable variables and apply these gradients to the variable values. See GradientDescentOptimizer.minimize.






          share|improve this answer





















          • Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
            – Gautham Pughazhendhi
            14 hours ago










          • The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
            – Sergei Lebedev
            8 hours ago














          0












          0








          0







          I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time.




          tf.reduce_sum is an operation and as such it does not have any implicit mutable state. The result of tf.reduce_sum is fully defined by the model parameters (W and B) and the placeholder values explicitly provided in the feed_dict argument to the sess.run(cost, feed_dict={...}) call.



          If you would like to aggregate the value of a metric across all batches check out tf.metrics:



          y_pred = tf.placeholder(tf.float32)
          y_true = tf.placeholder(tf.float32)
          mse, update_op = tf.metrics.mean_squared_error(y_true, y_pred)
          init = tf.local_variables_initializer() # MSE state is local!
          sess = tf.Session()
          sess.run(init)

          # Update the metric and compute the value after the update.
          sess.run(update_op, feed_dict={y_pred: [0.0], y_true: [42.0]}) # => 1764.0
          # Get current value.
          sess.run(mse) # => 1764.0



          I also need to know whether the weights and bias will be updated for each epoch or for each x and y.




          Each sess.run(optimizer, ...) call will compute the gradients of the trainable variables and apply these gradients to the variable values. See GradientDescentOptimizer.minimize.






          share|improve this answer













          I need to know whether the reduce_sum will wait for all the 30 samples or take one sample (x, y) at a time.




          tf.reduce_sum is an operation and as such it does not have any implicit mutable state. The result of tf.reduce_sum is fully defined by the model parameters (W and B) and the placeholder values explicitly provided in the feed_dict argument to the sess.run(cost, feed_dict={...}) call.



          If you would like to aggregate the value of a metric across all batches check out tf.metrics:



          y_pred = tf.placeholder(tf.float32)
          y_true = tf.placeholder(tf.float32)
          mse, update_op = tf.metrics.mean_squared_error(y_true, y_pred)
          init = tf.local_variables_initializer() # MSE state is local!
          sess = tf.Session()
          sess.run(init)

          # Update the metric and compute the value after the update.
          sess.run(update_op, feed_dict={y_pred: [0.0], y_true: [42.0]}) # => 1764.0
          # Get current value.
          sess.run(mse) # => 1764.0



          I also need to know whether the weights and bias will be updated for each epoch or for each x and y.




          Each sess.run(optimizer, ...) call will compute the gradients of the trainable variables and apply these gradients to the variable values. See GradientDescentOptimizer.minimize.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          Sergei Lebedev

          1,484918




          1,484918












          • Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
            – Gautham Pughazhendhi
            14 hours ago










          • The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
            – Sergei Lebedev
            8 hours ago


















          • Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
            – Gautham Pughazhendhi
            14 hours ago










          • The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
            – Sergei Lebedev
            8 hours ago
















          Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
          – Gautham Pughazhendhi
          14 hours ago




          Do the cost be computed for every x and y instead for every epoch?. Then what's the use of reduce_sum if the cost is computed for every x and y.
          – Gautham Pughazhendhi
          14 hours ago












          The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
          – Sergei Lebedev
          8 hours ago




          The purpose of tf.reduce_sum is to sum the tensor along the specified axis. It is conceptually similar to np.sum. As noted above, if you are looking for aggregate metrics, use tf.metrics.*.
          – Sergei Lebedev
          8 hours ago










          Gautham Pughazhendhi is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Gautham Pughazhendhi is a new contributor. Be nice, and check out our Code of Conduct.













          Gautham Pughazhendhi is a new contributor. Be nice, and check out our Code of Conduct.












          Gautham Pughazhendhi is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53943659%2fhow-does-tensorflows-reduce-sum-work-in-a-loop%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'