有沒有更快的方法來np.convolve(A, B)[::N]使用 Numpy?N - 1計算所有卷積然后扔掉感覺很浪費N......我可以做一個 for 回圈或串列理解,但我認為只使用本機 Numpy 方法會更快。
編輯
還是 Numpy 做惰性求值?我剛從一個 JS 庫中看到這個,對于 Numpy 來說也很棒:
// Get first 3 unique values
const arr = [1, 2, 2, 3, 3, 4, 5, 6];
const result = R.pipe(
arr,
R.map(x => {
console.log('iterate', x);
return x;
}),
R.uniq(),
R.take(3)
); // => [1, 2, 3]
/**
* Console output:
* iterate 1
* iterate 2
* iterate 2
* iterate 3
* /
uj5u.com熱心網友回復:
卷積是內核和陣列上的視窗的乘積,然后是總和。您可以使用滾動視窗手動實作相同的目的:
首先讓我們看一個虛擬示例
A = np.arange(30)
B = np.ones(6)
N = 3
out = np.convolve(A, B)[::N]
print(out)
輸出:[ 0. 6. 21. 39. 57. 75. 93. 111. 129. 147. 135. 57.]
現在我們對滾動視圖、填充和切片執行相同的操作:
from numpy.lib.stride_tricks import sliding_window_view as swv
out = (swv(np.pad(A, B.shape[0]-1), B.shape[0])[::N]*B).sum(axis=1)
print(out)
輸出:[ 0. 6. 21. 39. 57. 75. 93. 111. 129. 147. 135. 57.]
中間滑動視圖:
swv(np.pad(A, B.shape[0]-1), B.shape[0])
array([[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 1],
[ 0, 0, 0, 0, 1, 2],
[ 0, 0, 0, 1, 2, 3],
[ 0, 0, 1, 2, 3, 4],
[ 0, 1, 2, 3, 4, 5],
[ 1, 2, 3, 4, 5, 6],
[ 2, 3, 4, 5, 6, 7],
...
[24, 25, 26, 27, 28, 29],
[25, 26, 27, 28, 29, 0],
[26, 27, 28, 29, 0, 0],
[27, 28, 29, 0, 0, 0],
[28, 29, 0, 0, 0, 0],
[29, 0, 0, 0, 0, 0]])
# with slicing
swv(np.pad(A, B.shape[0]-1), B.shape[0])[::N]
array([[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 1, 2, 3],
[ 1, 2, 3, 4, 5, 6],
[ 4, 5, 6, 7, 8, 9],
[ 7, 8, 9, 10, 11, 12],
[10, 11, 12, 13, 14, 15],
[13, 14, 15, 16, 17, 18],
[16, 17, 18, 19, 20, 21],
[19, 20, 21, 22, 23, 24],
[22, 23, 24, 25, 26, 27],
[25, 26, 27, 28, 29, 0],
[28, 29, 0, 0, 0, 0]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/519630.html
標籤:Python麻木的
上一篇:如何計算列和分組中的值
