Is there a fast way to store (pack) multiple matrices (with different shapes) into one N-D array (N does not matter), and then unpack it back when needed?
是否有快速方法将多个矩阵(具有不同形状)存储(打包)到一个N-D阵列中(N无关紧要),然后在需要时将其解包?
Here is my quick and dirty solution:
这是我快速而肮脏的解决方案:
def pack(*matrices):
return np.concatenate([a.flatten() for a in matrices])
def unpack(container):
shapes = [ (64, 25), (64, 1), (25, 64), (25, 1) ] #Example
sections = [ np.prod(shape) for shape in shapes ]
arrays = np.split(x, np.cumsum(sections))
return [ np.reshape(a, shape) for a, shape in zip(arrays, shapes)]
Context
I am using scipy.optimize.fmin_l_bfgs_b
which takes an 'initial guess' parameter x0. Internally, x = array(x0, float64)
is executed, which means that a sequence of (elements convertible to) floats is expected. If x0 = [ matrix1, matrix2, matrix3, ... ] then exception rises:
我正在使用scipy.optimize.fmin_l_bfgs_b,它采用'初始猜测'参数x0。在内部,x = array(x0,float64)被执行,这意味着期望一系列(元素可转换为)浮点数。如果x0 = [matrix1,matrix2,matrix3,...]则异常上升:
ValueError: setting an array element with a sequence.
Hence all these matrices need to be packed into a sequence of floats and then unpacked when needed.
因此,所有这些矩阵都需要打包成一系列浮点数,然后在需要时解压缩。
1 个解决方案
#1
For me, the most efficient way to do this would be to rewrite the function scipy.optimize.fmin_l_bfgs_b
. It shouldn't be difficult
对我来说,最有效的方法是重写函数scipy.optimize.fmin_l_bfgs_b。这应该不难
You can find the source code here : github
你可以在这里找到源代码:github
#1
For me, the most efficient way to do this would be to rewrite the function scipy.optimize.fmin_l_bfgs_b
. It shouldn't be difficult
对我来说,最有效的方法是重写函数scipy.optimize.fmin_l_bfgs_b。这应该不难
You can find the source code here : github
你可以在这里找到源代码:github