为什么tensorflow map_fn在循环方面比python慢

2024-10-01 07:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对形状为[batch, n_pts, 3]的张量中的每一批点应用独立旋转。我用两种不同的方式实现了它。第一个是将张量转换为numpy数组和基本python for循环。第二种方法使用tensorflowstf.map_fn()来消除for循环。然而,当我运行这个时,tensorflowmap_fn()慢了约100倍

我的问题是我是否在这里错误地使用了tf.map_fn()函数。使用tf.map_fn()比标准的numpy/python什么时候会有性能提升

如果我正确地使用它,那么我想知道为什么tensorflowtf.map_fn()要慢得多

我复制实验的代码是:

import time
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K


def rotate_tf(pc):

    theta = tf.random.uniform((1,)) * 2.0 * np.pi
    cosval = tf.math.cos(theta)[0]
    sinval = tf.math.sin(theta)[0]

    R = tf.Variable([
        [cosval, -sinval, 0.0],
        [sinval, cosval, 0.0],
        [0.0, 0.0, 1.0]
    ])

    def dot(p):
        return K.dot(R, tf.expand_dims(p, axis=-1))

    return tf.squeeze(tf.map_fn(dot, pc))


def rotate_np(pc):

    theta = np.random.uniform() * 2.0 * np.pi
    cosval = np.cos(theta)
    sinval = np.sin(theta)

    R = np.array([
        [cosval, -sinval, 0.0],
        [sinval, cosval, 0.0],
        [0.0, 0.0, 1.0]
    ])

    for idx, p in enumerate(pc):
        pc[idx] = np.dot(R, p)

    return pc


pts = tf.random.uniform((8, 100, 3))
n = 10

# Start tensorflow map_fn() method
start = time.time()

for i in range(n):
    pts = tf.map_fn(rotate_tf, pts)

print('processed tf in: {:.4f} s'.format(time.time()-start))

# Start numpy method
start = time.time()

for i in range(n):

    pts = pts.numpy()
    for i, p in enumerate(pts):
        pts[i] = rotate_np(p)
    pts = tf.Variable(pts)

print('processed np in: {:.4f} s'.format(time.time()-start))

其输出为:

processed tf in: 3.8427 s
processed np in: 0.0314 s

Tags: inimportnumpymapfortimetfnp