在python中对二维numpy数组进行下采样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34231244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Downsampling a 2d numpy array in python
提问by Neo Streets
I'm self learning python and have found a problem which requires down sampling a feature vector. I need some help understanding how down-sampling a array. in the array each row represents an image by being number from 0
to 255
. I was wonder how you apply down-sampling to the array? I don't want to scikit-learn
because I want to understand how to apply down-sampling.
If you could explain down-sampling too that would be amazing thanks.
我正在自学 python 并发现了一个需要对特征向量进行下采样的问题。我需要一些帮助来理解如何对数组进行下采样。在数组中,每一行通过从0
到的数字表示一个图像255
。我想知道你如何对数组应用下采样?我不想,scikit-learn
因为我想了解如何应用下采样。如果您也能解释下采样,那将是非常感谢。
the feature vector is 400x250
特征向量是 400x250
采纳答案by Bart
If with downsampling you mean something like this, you can simply slice the array. For a 1D example:
如果下采样的意思是这样的,你可以简单地对数组进行切片。对于一维示例:
import numpy as np
a = np.arange(1,11,1)
print(a)
print(a[::3])
The last line is equivalent to:
最后一行相当于:
print(a[0:a.size:3])
with the slicing notation as start:stop:step
切片符号为 start:stop:step
Result:
结果:
[ 1 2 3 4 5 6 7 8 9 10]
[ 1 4 7 10]
[ 1 2 3 4 5 6 7 8 9 10]
[ 1 4 7 10]
For a 2D array the idea is the same:
对于二维数组,思路是一样的:
b = np.arange(0,100)
c = b.reshape([10,10])
print(c[::3,::3])
This gives you, in both dimensions, every third item from the original array.
这为您提供了两个维度中来自原始数组的每三个项目。
Or, if you only want to down sample a single dimension:
或者,如果您只想对单个维度进行下采样:
d = np.zeros((400,250))
print(d.shape)
e = d[::10,:]
print(e.shape)
(400, 250)
(40, 250)
(400, 250)
(40, 250)
The are lots of other examples in the Numpy manual
Numpy 手册中有很多其他示例
回答by ashkan
I assume that you want to remove every other rows and columns of matrix. Here is simple example with a 2-D numpy array:
我假设您要删除矩阵的所有其他行和列。这是一个带有二维 numpy 数组的简单示例:
import numpy as np
a=np.arange(0,16).reshape(4,4)
dc=a[:,range(0,a.shape[1],2)]
drdc=dc[range(0,a.shape[0],2),:]
print(a)
print(drdc)
The output is:
输出是:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[ 0 2]
[ 8 10]]