Python 平滑一个热编码矩阵行
假设我有以下由一个热编码行组成的矩阵:Python 平滑一个热编码矩阵行,python,numpy,Python,Numpy,假设我有以下由一个热编码行组成的矩阵: X = np.array([[0., 0., 0., 1., 0.], [1., 0., 0., 0., 0.], [0., 0., 1., 0., 0.]]) 我的目标是平滑/扩展one hot编码,以便获得以下输出: Y = np.array([[0., 0., 1., 1., 1.], [1., 1., 0., 0., 0.], [0., 1., 1., 1., 0.]]) 假设我希望平滑/扩展一个热元素的左侧或右侧的一个元素。谢谢你的帮助 我们
X = np.array([[0., 0., 0., 1., 0.], [1., 0., 0., 0., 0.], [0., 0., 1., 0., 0.]])
我的目标是平滑/扩展one hot编码,以便获得以下输出:
Y = np.array([[0., 0., 1., 1., 1.], [1., 1., 0., 0., 0.], [0., 1., 1., 1., 0.]])
假设我希望平滑/扩展一个热元素的左侧或右侧的一个元素。谢谢你的帮助 我们可以使用
卷积
-
In [22]: from scipy.signal import convolve2d
In [23]: convolve2d(X,np.ones((1,3)),'same')
Out[23]:
array([[0., 0., 1., 1., 1.],
[1., 1., 0., 0., 0.],
[0., 1., 1., 1., 0.]])
使用二进制扩展
提高内存效率-
In [43]: from scipy.ndimage.morphology import binary_dilation
In [46]: binary_dilation(X,np.ones((1,3), dtype=bool)).view('i1')
Out[46]:
array([[0, 0, 1, 1, 1],
[1, 1, 0, 0, 0],
[0, 1, 1, 1, 0]], dtype=int8)
或者,因为我们只有0和1,所以统一过滤器也可以工作,此外,我们可以沿着通用轴使用它(在我们的例子中,轴=1),并且在性能上应该更好-
In [47]: from scipy.ndimage import uniform_filter1d
In [50]: (uniform_filter1d(X,size=3,axis=1)>0).view('i1')
Out[50]:
array([[0, 0, 1, 1, 1],
[1, 1, 0, 0, 0],
[0, 1, 1, 1, 0]], dtype=int8)
您可以将
X
与一个数组进行卷积:
from scipy.signal import convolve2d
convolve2d(X, np.ones((1,3)), mode='same')
array([[0., 0., 1., 1., 1.],
[1., 1., 0., 0., 0.],
[0., 1., 1., 1., 0.]])
基于标准卷积的解决方案
import numpy as np
np.array([np.convolve(x, np.array([1,1,1]), mode='same') for x in X])
使用列表理解迭代行以进行卷积,然后转换回np.array