我想通过屏蔽一些我知道在计算中不需要为零的值来优化Python中的矩阵乘法(权衡回归)。它们仍然会存在,因为我不想更改矩阵的大小。矩阵是浮点数。
Python(keras / tensorflow?)是否会以不同的方式处理这些乘法并显着加快该过程,或者将花费相似的时间,从而使这种掩盖变得毫无意义?
答案 0 :(得分:1)
不,乘以零等于乘以任何其他数字
>>> def times_zero(x):
... return x * 0
...
>>> import dis
>>> dis.dis(times_zero)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (0)
6 BINARY_MULTIPLY
7 RETURN_VALUE
>>> def times_four(x):
... return x * 4
...
>>> dis.dis(times_four)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (4)
6 BINARY_MULTIPLY
7 RETURN_VALUE
答案 1 :(得分:0)
我给他们计时:
from timeit import default_timer as timer
import itertools
my_toggle = itertools.cycle(range(2))
for x in range(20):
current_number = my_toggle.__next__()
start = timer()
y = 1 * current_number
end = timer()
print(f"{end - start:.10f} seconds for {current_number}")
但是我不确定结果如何:
0.0000002555 seconds for 0
0.0000002555 seconds for 1
0.0000002555 seconds for 0
0.0000002555 seconds for 1
0.0000002555 seconds for 0
0.0000000000 seconds for 1
0.0000000000 seconds for 0
0.0000002555 seconds for 1
0.0000000000 seconds for 0
0.0000000000 seconds for 1
0.0000000000 seconds for 0
0.0000002555 seconds for 1
0.0000002555 seconds for 0
0.0000000000 seconds for 1
0.0000002555 seconds for 0
0.0000000000 seconds for 1
0.0000000000 seconds for 0
0.0000002555 seconds for 1
0.0000000000 seconds for 0
0.0000000000 seconds for 1