【问题标题】:Flatten and merge arrays and then split them back展平和合并数组,然后将它们拆分回来
【发布时间】:2021-07-06 09:40:15
【问题描述】:

假设我有 3 个矩阵 w2、w3 和 w4,形状为 (5,5) (5,5) 和 (5,1)

是否有任何有效的方法来创建形状为(55,1) 或(55,) 的这3 个矩阵的扁平数组(进行一些计算),然后将这个新数组拆分回3 个形状与原始矩阵相同的矩阵?

我已经这样做了:

theta=w2.flatten()
theta=np.append(theta,w3)
theta=np.append(theta,w4)

然后:

w2=theta[0:25].reshape(5,5)
w3=theta[25:50].reshape(5,5)
w3=theta[50:].reshape(5,1)

但这似乎很慢。有没有更有效的方法?

【问题讨论】:

  • 不确定这应该做什么,但可以尝试的一件事是通过np.concatenate 或类似方法一次连接所有数组。
  • 您能否提供更多有关您正在计算的内容的见解?因为加快第一个进程的唯一方法是预先分配theta 中的空间,然后将结果直接写入带有w3[:] = theta[0:25].reshape(5, 5) 的原始数组中。但这两种操作都不会花费很多时间。

标签: python-3.x numpy flatten


【解决方案1】:

函数flatten 执行复制,append 创建一个新的 Numpy 数组,而 reshape 不这样做。

您可以使用np.concatenate 后跟np.array_split 和一些reshape。方法如下:

# Flatten the matrices and concatenate the value in one new array.
theta = np.concatenate((w2.reshape(25), w3.reshape(25), w4.reshape(5)))

# Extract the 3 matrices and reshape them.
# Do not copy data, this just build 3 array views.
w2, w3, w4 = np.array_split(theta, [25, 50])
w2, w3, w4 = w2.reshape(5,5), w3.reshape(5,5), w4.reshape(5,1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 2017-08-13
    • 2018-05-01
    • 2012-09-25
    • 2021-01-04
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多