使用scipy.minimize

时间:2018-11-29 18:26:41

标签: python matrix scipy minimize

我正在尝试最小化(A_m-B*C_m)**2,其中A是固定矩阵,而B和C是可变矩阵。矩阵的形状分别为(3,3,512,512),(3,3,512,1)和(1,1,512,512)。

任何关于我要去哪里的建议,或关于如何执行此优化的一般建议,都值得赞赏。

代码

# objective function
def f(params, A):
    total = 0
    B, C = params
    for k in range(0,512):
        for m in range(0,512):
            for n in range(0,9):
                total += (A[k*m*n] - B[m*n] * C[k*m])**2
    print(total)
    return total

# create matrices
A = np.random.rand(3,3,512,512)
B = np.random.rand(3,3,512,1)
C = np.random.rand(1,1,512,512)

# flatten into 1d vectors
A = A.ravel()
B = B.ravel()
C = C.ravel()

# perform minimization
x = [B, C]
result = optimize.minimize(f, x, args=(A))

输出,经过几次迭代,我得到了“总计”的数字,然后它崩溃了:

407783.32968906895
407783.3247324555
407783.3244573258
407783.32968906895
2988640.705408569
2988640.705408569
2988640.797336188
2988640.7918476323
358476.57749339886
358476.57749339886
358476.57633670256
358476.5758499606
Traceback (most recent call last):
  File "minimize.py", line 148, in <module>
result = optimize.minimize(f, x, args=(A))
  File "/anaconda3/lib/python3.6/site-packages/scipy/optimize/_minimize.py", line 481, in minimize
return _minimize_bfgs(fun, x0, args, jac, callback, **options)
  File "/anaconda3/lib/python3.6/site-packages/scipy/optimize/optimize.py", line 994, in _minimize_bfgs
rhok = 1.0 / (numpy.dot(yk, sk))
ValueError: operands could not be broadcast together with shapes (4608,) (262144,) 

0 个答案:

没有答案