首页 > 解决方案 > 堆叠具有多维python的多个数组

问题描述

我正在尝试在 python 中创建和堆叠多个多维数组,但我似乎无法正确处理。

我有:

   y_0 = np.random.uniform(-1.0,1.0, size=(1,1,s_conn.weights.shape[0],1))
   y_1 = np.random.uniform(-500.0, 500.0, size=(1,1,s_conn.weights.shape[0],1))
   y_2 = np.random.uniform(-50.,50., size=(1,1,s_conn.weights.shape[0],1))
   y_3 = np.random.uniform(-6.0, 6.0, size=(1,1,s_conn.weights.shape[0],1))
   y_4 = np.random.uniform(-20.0, 20.0, size=(1,1,s_conn.weights.shape[0],1))
   y_5 = np.random.uniform(-500.,500., size=(1,1,s_conn.weights.shape[0],1))

其中 s.conn 是 NxN 矩阵。

每个数组都有暗淡: (1, 1, 10, 1) 我需要的是一个形状数组: (1, 6, 10, 1)

我怎么得到它?我尝试了 np.stack 和手动创建和重塑,但我不断得到奇怪/不正确的结果。

我将不胜感激。

js

标签: pythonarraysnumpy

解决方案


np.stack 沿新轴连接一系列数组,因此它将为您的矩阵创建一个不需要的维度,请考虑使用 np.concatenate。

np.concatenate([y_0,y_1,y_2,y_3,y_4,y_5],axis = 1)

请注意,您还可以使用 Array.squeeze() 删除不需要的尺寸(在使用 np.stach 而不使用整形时可能会出现这种情况,例如可以通过以下方式获得相同的结果:

np.stack([y_0,y_1,y_2,y_3,y_4,y_5],axis = 1).squeeze(axis=2)

推荐阅读