2024-04-25 22:12:24 发布
网友
使用tf.expand_dims()或tf.squeeze()有什么性能改进吗。。。等而不是tf.reshape()?在
tf.expand_dims()
tf.squeeze()
tf.reshape()
为了可读性,tf.reshape()通常是最佳选择,因为您可以在一行中执行任意数量/组合的整形步骤,并且您绝对确定最终的形状。在
但是,我读过tf.reshape()在内部复制数据。tf.expand_dims()或{}不执行此操作吗?有没有使用竞争对手的性能改进或其他原因来tf.reshape()?在
在TF1.x中,特别是在TF1.12.0中,所有方法在CPU上具有相同的性能:
TF1.x
TF1.12.0
import tensorflow as tf with tf.device('cpu:0'): tensor = tf.random.normal(shape=(1, 3, 2)) newaxis = tensor[tf.newaxis, ...] expanded_dims = tf.expand_dims(tensor, 0) reshaped = tf.reshape(tensor, (1, ) + tuple(tensor.get_shape().as_list())) squeezed = tf.squeeze(tensor) reshaped2 = tf.reshape(tensor, (3, 2)) sess = tf.Session() %timeit -n 10000 sess.run(newaxis) # 84.3 µs ± 767 ns per loop %timeit -n 10000 sess.run(expanded_dims) # 83.3 µs ± 837 ns per loop %timeit -n 10000 sess.run(reshaped) # 83.5 µs ± 946 ns per loop %timeit -n 10000 sess.run(squeezed) # 81.9 µs ± 852 ns per loop %timeit -n 10000 sess.run(reshaped2) # 83.9 µs ± 852 ns per loop
在GPU上,tf.newaxis和{}是最快的:
tf.newaxis
在TF2.0tf.expand_dims()中,添加维度和tf.squeeze()是最快的(CPU):
TF2.0
import tensorflow as tf tensor = tf.random.normal(shape=(1, 3, 2)) %timeit -n 10000 tf.expand_dims(tensor, 0) # 7.07 µs ± 162 ns per loop %timeit -n 10000 tf.reshape(tensor, (1, ) + tuple(tensor.shape.as_list())) # 21.3 µs ± 326 ns per loop %timeit -n 10000 tensor[tf.newaxis, ...] # 42.9 µs ± 565 ns per loop %timeit -n 10000 tf.squeeze(tensor) # 9.85 µs ± 166 ns per loop %timeit -n 10000 tf.reshape(tensor, shape=(3, 2)) # 18.2 µs ± 386 ns per loop
在
TF1.x
中,特别是在TF1.12.0
中,所有方法在CPU上具有相同的性能:在GPU上,}是最快的:
^{pr2}$tf.newaxis
和{在
TF2.0
tf.expand_dims()
中,添加维度和tf.squeeze()
是最快的(CPU):相关问题 更多 >
编程相关推荐