簡體   English   中英

如何在 1 的任一側用 1 填充長度為 n 的一個熱數組

[英]How to pad a one hot array of length n with a 1 on either side of the 1

例如我有以下數組: [0, 0, 0, 1, 0, 0, 0]我想要的是[0, 0, 1, 1, 1, 0, 0]

如果 1 在末尾,例如[1, 0, 0, 0]它應該只在一側添加[1, 1, 0, 0]

如何在保持數組長度相同的同時在任一側添加 1? 我看過 numpy 焊盤 function,但這似乎不是正確的方法。

您可以使用np.pad創建數組的兩個移位副本:一個向左移動 1 次(例如0 1 0 -> 1 0 0 ),一個向右移動 1 次(例如0 1 0 -> 0 0 1 )。

然后您可以將所有三個 arrays 加在一起:

  0 1 0
  1 0 0
+ 0 0 1
-------
  1 1 1

代碼:

output = a + np.pad(a, (1,0))[:-1] + np.pad(a, (0,1))[1:]
# (1, 0) says to pad 1 time at the start of the array and 0 times at the end
# (0, 1) says to pad 0 times at the start of the array and 1 time at the end

Output:

# Original array
>>> a = np.array([1, 0, 0, 0, 1, 0, 0, 0])
>>> a
array([1, 0, 0, 0, 1, 0, 0, 0])

# New array
>>> output = a + np.pad(a, (1,0))[:-1] + np.pad(a, (0,1))[1:]
>>> output
array([1, 1, 0, 1, 1, 1, 0, 0])

使用numpy.convolve with mode == "same"的一種方法:

np.convolve([0, 0, 0, 1, 0, 0, 0], [1,1,1], "same")

Output:

array([0, 0, 1, 1, 1, 0, 0])

與其他示例:

np.convolve([1,0,0,0], [1,1,1], "same")
# array([1, 1, 0, 0])
np.convolve([0,0,0,1], [1,1,1], "same")
# array([0, 0, 1, 1])
np.convolve([1,0,0,0,1,0,0,0], [1,1,1], "same")
# array([1, 1, 0, 1, 1, 1, 0, 0])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM