python - 平滑独热编码矩阵行

标签 python numpy

假设我有以下由 one-hot 编码行组成的矩阵:

X = np.array([[0., 0., 0., 1., 0.], [1., 0., 0., 0., 0.], [0., 0., 1., 0., 0.]])

我的目标是以一种方式平滑/扩展独热编码,以便获得以下输出:

Y = np.array([[0., 0., 1., 1., 1.], [1., 1., 0., 0., 0.], [0., 1., 1., 1., 0.]])

假设我想将 1 个元素平滑/扩展到独热元素的左侧或右侧。谢谢您的帮助!

最佳答案

我们可以使用卷积 -

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,均匀过滤器也可以工作,此外我们可以沿着通用轴(在我们的例子中 axis=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)

关于python - 平滑独热编码矩阵行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60452083/

相关文章:

python - 如何在python中为大型数据集制作朴素贝叶斯分类器

python - NumPy 多维数组形状直觉

python - 交替开关开/关?

python - 从 scikit-learn 逻辑回归模型计算残差

python-3.x - 按降序对两列最频繁的组合进行排序

python - `--` 值在 numpy 数组中意味着什么?

python - -1 在 numpy reshape 中是什么意思?

python - 如何根据多个条件从 numpy 数组中删除行?

python - 读取任何 PC 兼容的赛车方向盘输入

Python:删除重复代码以在 Selenium 中重复操作