當n>1時,我很難理解 np.diff 的行為
該檔案給出了以下示例:
x = np.array([1, 2, 4, 7, 0])
np.diff(x)
array([ 1, 2, 3, -7])
np.diff(x, n=2)
array([ 1, 1, -10])
從第一個示例看來,我們將每個數字減去前一個數字 (x[i 1]-x[i]),所有結果都是有意義的。
第二次呼叫函式時,n=2,似乎我們在做 x[i 2]-x[i 1]-x[i] 和前面的兩個數字(1 和 1)結果陣列是有道理的,但我很驚訝最后一個數字不是-11(0 -7 -4)而是-10。
查看檔案我發現了這個解釋
第一個差異由 out[i] = a[i 1] - a[i] 沿給定軸給出,更高的差異通過遞回使用 diff 計算。
我無法理解這個“遞回”,所以如果有人有更清晰的解釋,我會很高興!
uj5u.com熱心網友回復:
np.diff(x, n=2)與np.diff(np.diff(x))(在這種情況下,這就是“遞回”的含義)相同。
uj5u.com熱心網友回復:
在這種情況下,“遞回”僅僅意味著它多次執行相同的操作,每次都在上一步產生的陣列上。所以:
x = np.array([1, 2, 4, 7, 0])
output = np.diff(x)
生產
output = [2-1, 4-2, 7-4, 0-7] = [1, 2, 3, -7]
如果你使用 n=2,它只會做同樣的事情 2 次:
output = np.diff(x, n=2)
# first step, you won't see this result
output = [2-1, 4-2, 7-4, 0-7] = [1, 2, 3, -7]
# and then again (this will be your actual output)
output = [2-1, 3-2, -7-3] = [1, 1, -10]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453064.html
