ruphz
ruphz

Reputation: 31

Numpy array function returns inconsistent shapes

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

Upvotes: 2

Views: 308

Answers (2)

karstean
karstean

Reputation: 11

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.

Upvotes: 1

Deepak Saini
Deepak Saini

Reputation: 2900

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.

Upvotes: 1

Related Questions