2

I'm trying to define a simple function ddf() that outputs the Hessian matrix of a particular mathematical function, given a 2D vector, x as the input :

import numpy as np

def ddf(x):
    dd11 = 2*x[1]+8
    dd12 = 2*x[0]-8*x[1]-8
    dd21 = 2*x[0]-8*x[1]-8
    dd22 = -8*x[0]+2
   return np.array([[dd11, dd12], [dd21, dd22]])

x0 = np.zeros((2,1))
G = ddf(x0)
print(G)

I expect the output to be a 2x2 square array/matrix, however it yields what appears to be a 4x1 column instead. Stranger still, using

G.shape

yields (2L, 2L, 1L), not (2L,2L) as expected. My objective is to obtain G in 2x2 form. Can anyone assist? Thanks

0

2 Answers 2

1

Your input to the function ddf() is a 2x1 matrix, meaning all of x[0] and x[1] are vectors not scalers(floats or ints). So each element of your output matrix are 1-sized vectors, as all operations in numpy are applied elements wise if arrays are passed to the functions. Couple of things, you can do :

  • It seems that you expect x[0], x[1] to be scalars, so change the input to shape (2,) in x0 = np.zeros((2,)).
  • Or reshape the output as G.reshape((2,2)) to remove the extra dimension.
Sign up to request clarification or add additional context in comments.

Comments

1

I'm very new to python, but I think that will work:

...
G = ddf(x0)  
G = np.reshape(G, (2,2))  
print(G)

It yields a (2,2) as you wanted.

1 Comment

It does indeed, thank you very much. I also found that reshaping the 2x1 vector (x) as a 1x2 vector does the job

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.