TensorFlow 与 Theano 性能对比

TensorFlow vs. Theano Performance

在一些神经网络研究的背景下,我正在评估几种关于如何实现这些或使用什么库的方法。目前我正在比较 Tensorflow 和 Theano,我正在努力获得 TenorFlow 表现良好。这是我的简单 Hello-Gradient-Benchmark,它只是优化了一个系数为 1 的标量乘法。

import time

class Timer:

   def __init__(self, what):
      self.what = what

   def __enter__(self):
      self.t1 = time.time()
      return self

   def __exit__(self,t,v,tb):
      t2 = time.time()
      print("{0} runs {1:.4f} seconds".format(self.what, t2-self.t1))


def run_tensorflow():

   import tensorflow as tf

   x = tf.placeholder(tf.float32)
   y = tf.placeholder(tf.float32)
   a = tf.Variable([1.], tf.float32)

   sess = tf.Session()
   sess.run(tf.global_variables_initializer())

   loss = (y-a*x)**2
   step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

   def one_step():
      sess.run(step, {x:1.,y:0.})

   with Timer('tensorflow') as t:
      result = [ one_step() for n in range(1000) ]


def run_theano():

   import theano as th

   x = th.tensor.dscalar()
   y = th.tensor.dscalar()
   a = th.tensor.dscalar()
   l = a*x

   loss = (y-l)**2
   dloss = th.tensor.grad(loss, a)
   dloss_f = th.function([x,y,a], dloss)

   a = [1.]

   def one_step():
      a[0] -= 0.01 * dloss_f(1.,0.,a[0])

   with Timer('theano') as t:
      result = [ one_step() for n in range(1000) ]


run_tensorflow()
run_theano()

我 运行 这个程序在 CPU 上,软件包是通过 pip 安装的。 运行 TensorFlow 和 Theano 的时间分别为 0.36 和 0.043 秒。对于矩阵乘法开销应该占主导地位的真实网络,我看到了类似的性能差异,但 TensorFlow 仍然明显较慢。

我想知道我是否错误地使用了 Tensorflow 来做我想做的事情。我不应该在循环中调用 run() 方法吗?

  1. TF 和 Theano 专为处理大型对象而设计,大约为 1M 元素。对标量的处理进行基准测试并不是特别相关。

  2. 这是一个苹果与橘子的比较:使用 TF,您正在计时编译和 运行 时间,而在 Theano 中,您只计时 运行 时间!这是因为当您调用 theano.function 时,它会进行所有编译。 OTOH 在 TF 中,大部分工作都转移到您 第一次 调用 sess.run 时。

也就是说,也有 TF 比 Theano 慢的现实场景。