在Python(numpy)中修改ndarray的正确方法是什么?

时间:2017-05-03 20:26:40

标签: python numpy image-processing computer-vision

我发现修改/分配numpy.ndarray如:     X [j,...,c] =某事。 没有像我期望的那样工作。请参阅以下代码段和随附的输出

X_train_norm = np.zeros_like(X_train)
for j in range(100, 102):
   for c in range(X_train.shape[-1]):
      X_train_norm[j,...,c] = X_train[j,...,c] - means[j, c]
      print(j, c, np.mean(X_train_norm[j,...,c]), np.mean(X_train[j,...,c] - means[j,c]))


100 0 152.491210938 0.0
100 1 153.384765625 0.0
100 2 164.598632812 0.0
101 0 148.837890625 0.0
101 1 151.559570312 0.0
101 2 162.604492188 0.0

(means is a Nx3 array and X_train is a Nx32x32x3 array)

创建输出的正确方法是什么?

编辑:我使用了这样的代码片段:

z = X_train[j,...] - means[j,]
if X_train_norm is None:
    X_train_norm = np.array(z, ndmin=4)
else:
    X_train_norm = np.vstack([X_train_norm, np.array(z, ndmin=4)])

我确信有一种更有效率和pythonic的方式来做到这一点。谢谢你的期待!

1 个答案:

答案 0 :(得分:0)

咄!这是一个类型问题。

X_train was uint8.
X_train_norm = np.zeros_like(X_train,dtype='float64')
X_train_norm = X_train_norm.astype(float)
for j in range(100, 102):
   z = X_train[j,...] - means[j,]
   print(z.shape, z.mean())
   X_train_norm[j] = z
   print(X_train_norm[j].shape, X_train_norm[j].mean())

正确打印

(32, 32, 3) 0.0
(32, 32, 3) 0.0
(32, 32, 3) 0.0
(32, 32, 3) 0.0