Skip to content

Commit fe45446

Browse files
basveelingmartinwicke
authored andcommitted
Mean of cross entropy vs sum in summaries tutorial (tensorflow#1358)
* Mean of cross entropy vs sum in summaries and softmax tutorial The `mnist_with_summaries.py` tutorial computes the sum of the cross_entropy over the data points in the batch. This is not in line with the more common approach of taking the mean, such as in https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist.py#L99 The current form works as a loss function, but might confuse newcomers who are figuring out how gradients are aggregated in TensorFlow (as experienced by me, see http://stackoverflow.com/questions/35731506/unaggregated-gradients-gradients-per-example-in-tensorflow :-)) * Updated learning rate and docs
1 parent 584955e commit fe45446

4 files changed

Lines changed: 19 additions & 23 deletions

File tree

‎tensorflow/examples/tutorials/mnist/mnist_softmax.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@
4343

4444
# Define loss and optimizer
4545
y_ = tf.placeholder(tf.float32, [None, 10])
46-
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
47-
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
46+
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
47+
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
4848

4949
# Train
5050
tf.initialize_all_variables().run()

‎tensorflow/examples/tutorials/mnist/mnist_with_summaries.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
4040
'for unit testing.')
4141
flags.DEFINE_integer('max_steps', 1000, 'Number of steps to run trainer.')
42-
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
42+
flags.DEFINE_float('learning_rate', 0.5, 'Initial learning rate.')
4343
flags.DEFINE_string('data_dir', '/tmp/data', 'Directory for storing data')
4444
flags.DEFINE_string('summaries_dir', '/tmp/mnist_logs', 'Summaries directory')
4545

@@ -69,7 +69,7 @@ def main(_):
6969
y_ = tf.placeholder(tf.float32, [None, 10], name='y-input')
7070
# More name scopes will clean up the graph representation
7171
with tf.name_scope('xent'):
72-
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
72+
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
7373
tf.scalar_summary('cross entropy', cross_entropy)
7474
with tf.name_scope('train'):
7575
train_step = tf.train.GradientDescentOptimizer(

‎tensorflow/g3doc/tutorials/mnist/beginners/index.md‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -311,18 +311,14 @@ y_ = tf.placeholder(tf.float32, [None, 10])
311311
Then we can implement the cross-entropy, \\(-\sum y'\log(y)\\):
312312

313313
```python
314-
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
314+
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
315315
```
316316

317317
First, `tf.log` computes the logarithm of each element of `y`. Next, we multiply
318-
each element of `y_` with the corresponding element of `tf.log(y)`. Finally,
319-
`tf.reduce_sum` adds all the elements of the tensor.
320-
321-
Note that this isn't just the cross-entropy of the truth with a single
322-
prediction, but the sum of the cross-entropies for all the images we looked at.
323-
In this example, we have 100 images in each batch: how well we are doing on 100
324-
data points is a much better description of how good our model is than a single
325-
data point.
318+
each element of `y_` with the corresponding element of `tf.log(y)`. Then
319+
`tf.reduce_sum` adds the elements in the second dimension of y, due to the
320+
`reduction_indices=[1]` parameter. Finally, `tf.reduce_mean` computes the mean
321+
over all the examples in the batch.
326322

327323
Now that we know what we want our model to do, it's very easy to have TensorFlow
328324
train it to do so.
@@ -334,11 +330,11 @@ minimize. Then it can apply your choice of optimization algorithm to modify the
334330
variables and reduce the cost.
335331

336332
```python
337-
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
333+
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
338334
```
339335

340336
In this case, we ask TensorFlow to minimize `cross_entropy` using the gradient
341-
descent algorithm with a learning rate of 0.01. Gradient descent is a simple
337+
descent algorithm with a learning rate of 0.5. Gradient descent is a simple
342338
procedure, where TensorFlow simply shifts each variable a little bit in the
343339
direction that reduces the cost. But TensorFlow also provides
344340
[many other optimization algorithms]
@@ -415,7 +411,7 @@ Finally, we ask for our accuracy on our test data.
415411
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
416412
```
417413

418-
This should be about 91%.
414+
This should be about 92%.
419415

420416
Is that good? Well, not really. In fact, it's pretty bad. This is because we're
421417
using a very simple model. With some small changes, we can get to

‎tensorflow/g3doc/tutorials/mnist/pros/index.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,11 @@ easily. Our cost function will be the cross-entropy between the target and the
157157
model's prediction.
158158

159159
```python
160-
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
160+
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
161161
```
162162

163-
Note that `tf.reduce_sum` sums across all images in the minibatch, as well as
164-
all classes. We are computing the cross entropy for the entire minibatch.
163+
Note that `tf.reduce_sum` sums across all classes and `tf.reduce_mean` takes
164+
the average over these sums.
165165

166166
## Train the Model
167167

@@ -174,10 +174,10 @@ TensorFlow has a variety of
174174
[builtin optimization algorithms]
175175
(../../../api_docs/python/train.md#optimizers).
176176
For this example, we will use steepest gradient descent, with a step length of
177-
0.01, to descend the cross entropy.
177+
0.5, to descend the cross entropy.
178178

179179
```python
180-
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
180+
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
181181
```
182182

183183
What TensorFlow actually did in that single line was to add new operations to
@@ -224,7 +224,7 @@ accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
224224
```
225225

226226
Finally, we can evaluate our accuracy on the test data. This should be about
227-
91% correct.
227+
92% correct.
228228

229229
```python
230230
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
@@ -370,7 +370,7 @@ additional parameter `keep_prob` in `feed_dict` to control the dropout rate;
370370
and we will add logging to every 100th iteration in the training process.
371371

372372
```python
373-
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
373+
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
374374
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
375375
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
376376
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

0 commit comments

Comments
 (0)