【发布时间】:2017-07-30 20:46:36
【问题描述】:
我正在计算 numpy 中的均值和标准差。为了提高性能,我在 Tensorflow 中尝试了相同的方法,但 Tensorflow 至少慢了约 10 倍。我在 Tensorflow 中尝试了 2 种方法(代码如下)。第一种方法使用tf.nn.moments(),它有一个错误导致它有时会返回负值作为方差。在第二种方法中,我通过其他 Tensorflow 函数计算方差。
我尝试了纯 CPU 和 GPU; numpy 总是更快。
在使用 GPU 时,我使用 time.time() 而不是 time.clock() 来测量挂钟时间。
为什么 TensorFlow 变慢了?我认为这可能是由于将数据传输到 GPU 造成的,但即使对于非常小的数据集(传输时间应该可以忽略不计)以及仅使用 CPU 时,TF 也会更慢。这是因为初始化 TF 需要额外的时间吗?
import tensorflow as tf
import numpy
import time
import math
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.interval = self.end - self.start
inData = numpy.random.uniform(low=-1, high=1, size=(40000000,))
with Timer() as t:
mean = numpy.mean(inData)
print 'python mean', mean, 'time', t.interval
with Timer() as t:
stdev = numpy.std(inData)
print 'python stdev', stdev, 'time', t.interval
# Approach 1 (Note tf.nn.moments() has a bug)
with Timer() as t:
with tf.Graph().as_default():
meanTF, varianceTF = tf.nn.moments(tf.constant(inData), axes=[0])
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
mean, variance = sess.run([meanTF, varianceTF])
sess.close()
print 'variance', variance
stdev = math.sqrt(variance)
print 'tensorflow mean', mean, 'stdev', stdev, 'time', t.interval
# Approach 2
with Timer() as t:
with tf.Graph().as_default():
inputVector = tf.constant(inData)
meanTF = tf.reduce_mean(inputVector)
length = tf.size(inputVector)
varianceTF = tf.divide(tf.reduce_sum(tf.squared_difference(inputVector, mean)), tf.to_double(length))
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
mean, variance = sess.run([meanTF, varianceTF])
sess.close()
print 'variance', variance
stdev = math.sqrt(variance)
print 'tensorflow mean', mean, 'stdev', stdev, 'time', t.interval
【问题讨论】:
-
I thought it might be due to transferring data into the GPU, but TF is slower even for very small datasets这看起来,就像你交换了一些东西。我想说您的计算类型很简单,因此由于专用功能和BLAS 的使用,numpy 非常好地达到了极限(这可能会根据您的 BLAS 设置并行运行;例如 Ubuntu 中的默认值)。 Tensorflow 不能做得更好(同时保证相同的准确性)。 -
在我的测试中,Tensorflow 始终比 Numpy 慢得多。 Tensorflow 不应该更快,因为它使用 GPU 而 Numpy 只使用 CPU?我正在运行 Ubuntu,并且没有更改任何影响 BLAS 的内容(据我所知)。
-
这总是取决于任务。有些算法很好地并行完成,有些则不是(你已经提到了其他参数,如传输,还有 dtypes 和 co。)。对 GPU 来说,并不是所有的工作都很好。
标签: performance numpy tensorflow