在numpy的数组元素的安排 [英] Elements arrangement in a numpy array
问题描述
导入numpy的是NP数据= np.array([0,0,1,1,2,2],
[1,0,0,1,2,2],
[1,0,1,0,0,0],
[1,1,0,0,2,0]])
我怎么可以做以下?
在2×2的补丁程序:
如果任何元素为2:2放
如果任何元素为1:1把
如果所有的元素都是0:0放
预期的结果是:
np.array([1,1,2]
[1,1,2]])
使用 extract_patches
从scikit学习,你可以这样写如下(复制和粘贴,能够code):
导入numpy的是NP
从sklearn.feature_extraction.image进口extract_patches数据= np.array([0,0,1,1,2,2],
[1,0,0,1,2,2],
[1,0,1,0,0,0],
[1,1,0,0,2,0]])补丁= extract_patches(数据,patch_shape =(2,2),extraction_step =(2,2))
输出= patches.max(轴= -1)的.max(轴= -1)
说明: extract_patches
让你在你的阵列的补丁视图,大小 patch_shape
,躺在 extraction_step
。其结果是一个四维阵列,其中所述第一二轴索引贴片和最后两个轴索引贴片内的像素。然后,我们评估在过去的两轴,最大限度地获得每个色块的最大值。
修改这实际上涉及非常多的this问题
import numpy as np
data = np.array([[0, 0, 1, 1, 2, 2],
[1, 0, 0, 1, 2, 2],
[1, 0, 1, 0, 0, 0],
[1, 1, 0, 0, 2, 0]])
How can I do the followings?
Within 2 by 2 patch:
if any element is 2: put 2
if any element is 1: put 1
if all elements are 0: put 0
The expected result is:
np.array([[1, 1, 2],
[1, 1, 2]])
Using extract_patches
from scikit-learn you can write this as follows (copy and paste-able code):
import numpy as np
from sklearn.feature_extraction.image import extract_patches
data = np.array([[0, 0, 1, 1, 2, 2],
[1, 0, 0, 1, 2, 2],
[1, 0, 1, 0, 0, 0],
[1, 1, 0, 0, 2, 0]])
patches = extract_patches(data, patch_shape=(2, 2), extraction_step=(2, 2))
output = patches.max(axis=-1).max(axis=-1)
Explanation: extract_patches
gives you a view on patches of your array, of size patch_shape
and lying on a grid of extraction_step
. The result is a 4D array where the first two axes index the patch and the last two axes index the pixels within the patch. We then evaluate the maximum over the last two axes to obtain the maximum per patch.
EDIT This is actually very much related to this question
这篇关于在numpy的数组元素的安排的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!