【问题标题】:About reshaping numpy array关于重塑 numpy 数组
【发布时间】:2018-02-01 08:08:54
【问题描述】:
trainX.size == 43120000
trainX = trainX.reshape([-1, 28, 28, 1])

(1)reshape 是否接受列表作为参数而不是元组?

(2)以下两种说法是否等价?

trainX = trainX.reshape([-1, 28, 28, 1])
trainX = trainX.reshape((55000, 28, 28, 1))

【问题讨论】:

    标签: numpy multidimensional-array reshape


    【解决方案1】:

    尝试变化:

    In [1]: np.arange(12).reshape(3,4)
    Out[1]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    In [2]: np.arange(12).reshape([3,4])
    Out[2]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    In [3]: np.arange(12).reshape((3,4))
    Out[3]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    

    使用reshape 方法,形状可以是参数、元组或列表。在reshape 函数中必须在列表或元组中,以将它们与第一个数组参数分开

    In [4]: np.reshape(np.arange(12), (3,4))
    Out[4]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    

    是的,可以使用一个-1。重塑的总大小是固定的,因此可以从其他值中推导出一个值。

    In [5]: np.arange(12).reshape(-1,4)
    Out[5]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    

    方法文档有这样的注释:

    与免费功能numpy.reshape 不同,ndarray 上的此方法允许 要作为单独参数传入的 shape 参数的元素。 例如,a.reshape(10, 11) 等价于 a.reshape((10, 11)).

    这是一个内置函数,但签名看起来像x.reshape(*shape),只要值有意义,它就会尝试灵活。

    【讨论】:

    • 非常感谢你,hpaulj
    【解决方案2】:

    来自 numpy 文档:

    newshape : 整数或整数元组

    新形状应与原始形状兼容。如果 整数,则结果将是该长度的一维数组。一种形状 维度可以是-1。在这种情况下,该值是从 数组长度和剩余维度。

    所以是的,-1 一维很好,你的两个陈述是等价的。关于元组要求,

    >>> import numpy as np
    >>> a = np.arange(9)
    >>> a
    array([0, 1, 2, 3, 4, 5, 6, 7, 8])
    >>> a.reshape([3,3])
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])
    >>> 
    

    所以显然列表也很好。

    【讨论】:

    • 非常感谢您,Thomas Kuhn。
    猜你喜欢
    • 1970-01-01
    • 2016-02-10
    • 2020-07-11
    • 1970-01-01
    • 2013-12-13
    • 2020-10-25
    • 2021-03-03
    • 2013-01-06
    • 2017-08-15
    相关资源
    最近更新 更多