2017-06-02 106 views
1

我的数据是numpy ndarray与形状(2,3,4)以下: 我已尝试通过sklearn标准化规范每个列的0-1比例。正常化numpy ndarray数据

from sklearn.preprocessing import normalize 

x = np.array([[[1, 2, 3, 4], 
     [2, 2, 3, 4], 
     [3, 2, 3, 4]], 
     [[4, 2, 3, 4], 
     [5, 2, 3, 4], 
     [6, 2, 3, 4]]]) 

x.shape ==> (2,3,4) 

x = normalize(x, norm='max', axis=0,) 

不过,我赶上了错误:

ValueError: Found array with dim 3. the normalize function expected <= 2. 

我该如何解决这个问题?

谢谢。

回答

1

看来scikit-learn预计至多有两个昏暗的ndarrays。因此,要解决这将是重塑到2D,将其提供给normalize这给了我们一个2D阵列,它可以重塑回了原形 -

from sklearn.preprocessing import normalize 

normalize(x.reshape(x.shape[0],-1), norm='max', axis=0).reshape(x.shape) 

另外,它与NumPy的更加简单,与正常工作generic ndarrays -

x/np.linalg.norm(x, ord=np.inf, axis=0, keepdims=True) 
+0

非常感谢!但是,上面的代码不适用于逐列,而是适用于整个数据。应该应用哪个选项? –

+0

@ChrisJoo不知道你是什么意思的列到列。也许你的意思是沿轴= 1而不是轴= 0使用它? – Divakar

+0

例如。第1列[[1,2,3],[4,5,6]]应为[[0.1667,0.33333,0.5000], [0.6667,0.8333,1.0000]]和第2列(2,2,2,2 ,2,2)应该是[1,1,1,1,1,1]。 –