[英]Smoothing one-hot encoded matrix rows
Assuming that I have the following matrix consisting of one-hot encoded rows:假设我有以下由单热编码行组成的矩阵:
X = np.array([[0., 0., 0., 1., 0.], [1., 0., 0., 0., 0.], [0., 0., 1., 0., 0.]])
What I aim to do is smooth/expand the one-hot encoding in a way such that I will obtain the following output:我的目标是以某种方式平滑/扩展单热编码,以便我将获得以下输出:
Y = np.array([[0., 0., 1., 1., 1.], [1., 1., 0., 0., 0.], [0., 1., 1., 1., 0.]])
assuming that I want to smooth/expand 1 element to the left or the right of the one-hot element.假设我想平滑/扩展 1 个元素到 one-hot 元素的左侧或右侧。 Thank you for the help!
感谢您的帮助!
We can use convolution
-我们可以使用
convolution
-
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.]])
With binary-dilation
to be more memory-efficient -使用
binary-dilation
可以提高内存效率 -
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)
Or since we only 0s and 1s, uniform filter would also work and additionally we can use it along a generic axis (axis=1 in our case) and should be better on perf.或者因为我们只有 0s 和 1s,统一过滤器也可以工作,另外我们可以沿着通用轴(在我们的例子中轴=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)
You could convolve X
with an array of ones:您可以将
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.]])
Solution based on standard np.convolve
:基于标准
np.convolve
解决方案:
import numpy as np
np.array([np.convolve(x, np.array([1,1,1]), mode='same') for x in X])
Iterate rows using list comprehension to convolve, then convert back to np.array
使用列表理解迭代行进行卷积,然后转换回
np.array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.