【问题标题】:Reshaping function in numpynumpy中的重塑功能
【发布时间】:2021-04-21 00:49:12
【问题描述】:

我正在尝试为图像分类目的重塑数据。我想将形状 (32,32,3) 转换为 (1,3,32,32)。我使用了两种方法进行整形,得到了不同的结果。第一个是 numpy reshape 方法。其他代码是我写的。

def res(t):
    n = np.zeros((3,32,32))

    for j in range(3):
        for k in range(32):
            for l in range(32):
                n[j][k][l]=t[k][l][j]

    n=n.reshape(1,3,32,32)
    return n

我无法理解这两种方法之间的区别。

【问题讨论】:

  • 这行得通吗? t.T.reshape((1,) + t.T.shape)?

标签: python image numpy pytorch reshape


【解决方案1】:

这就是你想要在transpose 之后对np.reshape 执行的操作-

new = original.transpose(2,0,1).reshape(1,3,32,32)
#(32,32,3)->(3,32,32)->(1,3,32,32)

##OR##

new = original.transpose(2,0,1)[None,...]
#(32,32,3)->(3,32,32)->(1,3,32,32)

完整的代码,比较你的函数和转置方法的结果。

t = np.random.random((32,32,3))

def res(t):
    n = np.zeros((3,32,32))

    for j in range(3):
        for k in range(32):
            for l in range(32):
                n[j,k,l]=t[k,l,j]  #<--- fixed indexing

    n=n.reshape(1,3,32,32)
    return n

## METHOD Transpose and Reshape
np.allclose(t.transpose(2,0,1).reshape(1,3,32,32), res(t))
#True

## METHOD Transpose and new axis
np.allclose(t.transpose(2,0,1)[None,...], res(t))
#True

【讨论】:

  • arr[][][][] 是 numpy 的主要反模式。它创建了许多中间数组,这是非常低效的。 总是使用arr[1, 2, 3, 4]而不是arr[1][2][3][4]
  • 我的修复只是说明了具有相同语法的 OP 代码的问题。但你是对的,我应该两者都做(说明和改进)。现在修好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2015-05-07
  • 2021-01-08
相关资源
最近更新 更多