Почему генератор случайных чисел tf.random_uniform в тензорном потоке намного быстрее, чем числовой эквивалент - PullRequest
0 голосов
/ 30 октября 2018

Следующий код - это то, что я использовал для проверки производительности:

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))

Все три сегмента генерируют равномерно случайную матрицу 1000 * 2000 с двойной точностью 400 раз. Различия во времени поразительны. На моем Mac

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

Почему тензорный поток намного быстрее, чем numpy?

Ответы [ 2 ]

0 голосов
/ 30 октября 2018

Вы только что создали вычислительный граф, который генерирует операцию для вывода случайных чисел. Чтобы значения были рассчитаны, вы должны выполнить график в виде tf.Session.

// build the graph
a = tf.random_uniform((1000,2000))

// run the graph
with tf.Session() as sess:
    t = time.time()
    for i in range(400):
        computed_rand_values = sess.run(a)
    //print(...)

Я не проверял это, но я уверен, что время расчета будет больше, чем результат до

0 голосов
/ 30 октября 2018

tf.random_uniform в этом случае возвращает неоцененный тип тензора, tensorflow.python.framework.ops.Tensor, и если вы настроите контекст сеанса для оценки a в случае tf.random_uniform, вы Понимаете, это тоже требует времени.

Например, здесь, в случае tf, я добавил sess.run (на машине с центральным процессором), и для оценки и материализации требуется ~ 16 секунд, что имеет смысл, учитывая некоторые накладные расходы, которые необходимо собрать в данные с большим количеством элементов. введите на выходе.

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
...