当前位置:  开发笔记 > 编程语言 > 正文

为什么张量流中的随机数生成器tf.random_uniform比numpy等价物快得多

如何解决《为什么张量流中的随机数生成器tf.random_uniform比numpy等价物快得多》经验,为你挑选了1个好方法。

以下代码是我用来测试性能的代码:

import time
import numpy as np
import tensorflow as tf

t = time.time()
for i in range(400):
    a = np.random.uniform(0,1,(1000,2000))
print("np.random.uniform: {} seconds".format(time.time() - t))

t = time.time()
for i in range(400):
    a = np.random.random((1000,2000))
print("np.random.random:  {} seconds".format(time.time() - t))

t = time.time()
for i in range(400):
    a = tf.random_uniform((1000,2000),dtype=tf.float64);
print("tf.random_uniform: {} seconds".format(time.time() - t))

所有三个段均以双精度400次生成均匀随机的1000*2000矩阵.时间差异是惊人的.在我的Mac上,

np.random.uniform: 10.4318959713 seconds
np.random.random:  8.76161003113 seconds
tf.random_uniform: 1.21312117577 seconds

为什么tensorflow比numpy快得多?



1> ely..:

tf.random_uniform在这种情况下,返回一个tensorflow.python.framework.ops.Tensor评估的Tensor类型,如果你设置一个会话上下文来评估a这个tf.random_uniform案例,你会发现它也需要一段时间.

例如,在tf我添加的情况下sess.run(在仅CPU的机器上),评估和实现需要大约16秒,这对于在输出上编组为numpy数据类型的一些开销是有意义的.

In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:import time
import numpy as np
import tensorflow as tf

t = time.time()
for i in range(400):
    a = np.random.uniform(0,1,(1000,2000))
print("np.random.uniform: {} seconds".format(time.time() - t))

t = time.time()
for i in range(400):
    a = np.random.random((1000,2000))
print("np.random.random:  {} seconds".format(time.time() - t))

sess = tf.Session()
t = time.time()
for i in range(400):
    a = sess.run(tf.random_uniform((1000,2000),dtype=tf.float64))
print("tf.random_uniform: {} seconds".format(time.time() - t))::::::::::::::::::
:--
np.random.uniform: 11.066569805145264 seconds
np.random.random:  9.299575090408325 seconds
2018-10-29 18:34:58.612160: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2018-10-29 18:34:58.612191: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2018-10-29 18:34:58.612210: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
tf.random_uniform: 16.619441747665405 seconds

推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有