Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python fmin(find minimum) for a vector function

Tags:

python

numpy

I would like to find the minimum of 3dvar function defined as:

J(x)=(x-x_b)B^{-1}(x-x_b)^T + (y-H(x)) R^{-1} (y-H(x))^T (latex code)

with B,H,R,x_b,y given. I would like to find the argmin(J(x)). However it seems fmin in python does not work. (the function J works correctly)

Here is my code:

import numpy as np

from scipy.optimize import fmin

import math


def dvar_3(x):

    B=np.eye(5)
    H=np.ones((3,5))
    R=np.eye(3)
    xb=np.ones(5)
    Y=np.ones(3)

    Y.shape=(Y.size,1)

    xb.shape=(xb.size,1)


    value=np.dot(np.dot(np.transpose(x-xb),(np.linalg.inv(B))),(x-xb)) +np.dot(np.dot(np.transpose(Y-np.dot(H,x)),(np.linalg.inv(R))),(Y-np.dot(H,x)))    

    return value[0][0]


ini=np.ones(5) #
ini.shape=(ini.size,1) #change initial to vertical vector

fmin(dvar_3,ini) #start at initial vector

I receive this error:

ValueError: operands could not be broadcast together with shapes (5,5) (3,3) 

How can I solve this problem? Thank you in advance.

like image 737
Sibo CHENG Avatar asked Dec 20 '25 07:12

Sibo CHENG


1 Answers

reshape argument x in the function dvar_3, the init argument of fmin() needs a one-dim array.

import numpy as np   
from scipy.optimize import fmin   
import math

def dvar_3(x):
    x = x[:, None]
    B=np.eye(5)
    H=np.ones((3,5))
    R=np.eye(3)
    xb=np.ones(5)
    Y=np.ones(3)

    Y.shape=(Y.size,1)

    xb.shape=(xb.size,1)


    value=np.dot(np.dot(np.transpose(x-xb),(np.linalg.inv(B))),(x-xb)) +np.dot(np.dot(np.transpose(Y-np.dot(H,x)),(np.linalg.inv(R))),(Y-np.dot(H,x)))    

    return value[0][0]


ini=np.ones(5) #
fmin(dvar_3,ini) #start at initial vector
like image 189
HYRY Avatar answered Dec 21 '25 21:12

HYRY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!