为什么使用下划线(' _')作为变量名?

时间:2018-05-26 02:36:13

标签: python tensorflow

我试图从一些tensorflow代码中理解这行代码

 _, l = session.run([optimizer, loss], feed_dict=feed_dict)

此行的上下文来自

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print('Initialized')
  average_loss = 0
  for step in range(num_steps):
    batch_data, batch_labels = generate_batch(
      batch_size, num_skips, skip_window)
    feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
    _, l = session.run([optimizer, loss], feed_dict=feed_dict)
    average_loss += l
    if step % 2000 == 0:
      if step > 0:
        average_loss = average_loss / 2000
      # The average loss is an estimate of the loss over the last 2000 batches.
      print('Average loss at step %d: %f' % (step, average_loss))
      average_loss = 0
    # note that this is expensive (~20% slowdown if computed every 500 steps)
    if step % 10000 == 0:
      sim = similarity.eval()
      for i in range(valid_size):
        valid_word = reverse_dictionary[valid_examples[i]]
        top_k = 8 # number of nearest neighbors
        nearest = (-sim[i, :]).argsort()[1:top_k+1]
        log = 'Nearest to %s:' % valid_word
        for k in range(top_k):
          close_word = reverse_dictionary[nearest[k]]
          log = '%s %s,' % (log, close_word)
        print(log)
  final_embeddings = normalized_embeddings.eval()

完整的代码在这里

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb

为什么下划线被用作变量?看起来像是一个奇怪的选择,但这是来自官方的Tensorflow github,所以必须有一个理由。

1 个答案:

答案 0 :(得分:4)

解压缩列表/元组时,_通常用于您以后不需要的值。如果仔细查看该代码,_变量实际上并未在任何地方使用。

请注意,在Python REPL中,_指的是最新结果。

>>> 2+2
4
>>> _
4