如果weigths
和features
大小相同的numpy的陣列,可以實現elementwise乘法:
values = np.sum(weights * features + bias)
如果要避免增加偏壓到產品陣列的每個元素,可以做
values = np.sum(weights * features) + bias * weights.size
你甚至可以使用Python的內置sum
功能:
values = sum(weights * features + bias)
或
values = sum(weights * features) + bias * weights.size
之所以這樣工作原理是,表達式weights * features
和weights * features + bias
都是臨時numpy的陣列,其是可迭代沿着其第一尺寸並且因此可以被傳遞給sum
。
時序
我跑的IPython以下定時測試:
%timeit weights.dot(features)
The slowest run took 145.86 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 649 ns per loop
%timeit np.sum(weights * features)
The slowest run took 17.09 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.83 µs per loop
使用ndarray.dot
是五倍量級比在產品使用np.sum
更快。但是,警告表明,在您第一次運行代碼時,這可能不正確。 0.649μs* 145.86 =94.66μs,而2.83μs* 17.09 =48.36μs。
這個答案是正確的,也是很好的,但最重要的答案在一個點上有更多的細節,包括複雜性解決方案 –
我並不反對'dot'在這裏是更好的解決方案,但你是什麼意思的「複雜性解決方案」? –
我已經添加了關於哪些方法可以更好地執行的評論 –