-4

I have two numpy arrays

import numpy as np
x = np.linspace(1e10, 1e12, num=50) # 50 values
y = np.linspace(1e5, 1e7, num=50)   # 50 values
x.shape # output is (50,)
y.shape # output is (50,)

I would like to create a function which returns an array shaped (50,50) such that the first x value x0 is evaluated for all y values, etc.

The current function I am using is fairly complicated, so let's use an easier example. Let's say the function is

def func(x,y):
    return x**2 + y**2

How do I shape this to be a (50,50) array? At the moment, it will output 50 values. Would you use a for loop inside an array?

Something like:

np.array([[func(x,y) for i in x] for j in y)

but without using two for loops. This takes forever to run.


EDIT: It has been requested I share my "complicated" function. Here it goes:

There is a data vector which is a 1D numpy array of 4000 measurements. There is also a "normalized_matrix", which is shaped (4000,4000)---it is nothing special, just a matrix with entry values of integers between 0 and 1, e.g. 0.5567878. These are the two "given" inputs.

My function returns the matrix multiplication product of transpose(datavector) * matrix * datavector, which is a single value.

Now, as you can see in the code, I have initialized two arrays, x and y, which pass through a series of "x parameters" and "y parameters". That is, what does func(x,y) return for value x1 and value y1, i.e. func(x1,y1)?

The shape of matrix1 is (50, 4000, 4000). The shape of matrix2 is (50, 4000, 4000). Ditto for total_matrix.

normalized_matrix is shape (4000,4000) and id_mat is shaped (4000,4000).

normalized_matrix
print normalized_matrix.shape #output (4000,4000)

data_vector = datarr
print datarr.shape #output (4000,)

def func(x, y):
    matrix1 = x [:, None, None] * normalized_matrix[None, :, :]
    matrix2 = y[:, None, None] * id_mat[None, :, :]
    total_matrix = matrix1 + matrix2
    # transpose(datavector) * matrix * datavector
    # by matrix multiplication, equals single value
    return  np.array([ np.dot(datarr.T,  np.dot(total_matrix, datarr) )  ])

If I try to use np.meshgrid(), that is, if I try

x = np.linspace(1e10, 1e12, num=50) # 50 values
y = np.linspace(1e5, 1e7, num=50)   # 50 values

X, Y = np.meshgrid(x,y)

z = func(X, Y)

I get the following value error: ValueError: operands could not be broadcast together with shapes (50,1,1,50) (1,4000,4000).

ShanZhengYang
  • 16,511
  • 49
  • 132
  • 234
  • I'm confused about exactly what output you want. If the output 50 × 50 matrix is M, what is the formula you expect for `M[i, j]`? – Curt F. Jul 09 '15 at 00:48
  • `x0` evaluated at `y0` to `y49`, then `x1` evaluated at `y0` to `y49`, etc. – ShanZhengYang Jul 09 '15 at 00:49
  • I think [numpy.apply_along_axis()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html) is something that may interest you. – Curt F. Jul 09 '15 at 00:50
  • So it should be a 50 by 50 matrix, where each matrix entry is an (x,y) pair evaluated in the function. – ShanZhengYang Jul 09 '15 at 00:51
  • So `M[i, j] = f(x[i], y[j])`? – Curt F. Jul 09 '15 at 00:53
  • 2
    this is deja vu and has been answered in its alternate incarnation http://stackoverflow.com/questions/31304733/contour-plot-typeerror-length-of-y-must-be-number-of-rows-in-z –  Jul 09 '15 at 01:24
  • @DanPatterson Unfortunately my function is far far more complicated than above (I haven't posted it because it's an entire file). So, technically, this is a separate question. `np.meshgrid()` will lead to broadcasting errors. – ShanZhengYang Jul 09 '15 at 02:22
  • 1
    You Tried ```np.meshgrid``` and it did not work? – wwii Jul 09 '15 at 03:15
  • @wwii It's confusing, but yes. The function I am using is not the above function, but something far more complicated/too long to post. However, it does take two arguments and return a single output. – ShanZhengYang Jul 09 '15 at 03:23
  • 1
    The edited question, with more detailed `func` is helpful. But you should indicate where the `ValueError` occurs. People like to give negative votes for omitting that kind of information. See my 2nd answer. – hpaulj Jul 11 '15 at 04:44
  • @hpaulj I understand, thanks. Next time I'll try to include that. – ShanZhengYang Jul 13 '15 at 14:15

5 Answers5

3

reshape in numpy as different meaning. When you start with a (100,) and change it to (5,20) or (10,10) 2d arrays, that is 'reshape. There is anumpy` function to do that.

You want to take 2 1d array, and use those to generate a 2d array from a function. This is like taking an outer product of the 2, passing all combinations of their values through your function.

Some sort of double loop is one way of doing this, whether it is with an explicit loop, or list comprehension. But speeding this up depends on that function.

For at x**2+y**2 example, it can be 'vectorized' quite easily:

In [40]: x=np.linspace(1e10,1e12,num=10)
In [45]: y=np.linspace(1e5,1e7,num=5)
In [46]: z = x[:,None]**2 + y[None,:]**2
In [47]: z.shape
Out[47]: (10, 5)

This takes advantage of numpy broadcasting. With the None, x is reshaped to (10,1) and y to (1,5), and the + takes an outer sum.

X,Y=np.meshgrid(x,y,indexing='ij') produces two (10,5) arrays that can be used the same way. Look at is doc for other parameters.

So if your more complex function can be written in a way that takes 2d arrays like this, it is easy to 'vectorize'.

But if that function must take 2 scalars, and return another scalar, then you are stuck with some sort of double loop.

A list comprehension form of the double loop is:

np.array([[x1**2+y1**2 for y1 in y] for x1 in x])

Another is:

z=np.empty((10,5))
for i in range(10):
   for j in range(5):
      z[i,j] = x[i]**2 + y[j]**2

This double loop can be sped up somewhat by using np.vectorize. This takes a user defined function, and returns one that can take broadcastable arrays:

In [65]: vprod=np.vectorize(lambda x,y: x**2+y**2)

In [66]: vprod(x[:,None],y[None,:]).shape
Out[66]: (10, 5)

Test that I've done in the past show that vectorize can improve on the list comprehension route by something like 20%, but the improvement is nothing like writing your function to work with 2d arrays in the first place.

By the way, this sort of 'vectorization' question has been asked many times on SO numpy. Beyond these broad examples, we can't help you without knowning more about that more complicated function. As long as it is a black box that takes scalars, the best we can help you with is np.vectorize. And you still need to understand broadcasting (with or without meshgrid help).

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thank you for the comprehensive answer. It looks like I'm stuck with two for loops, unless I somehow change the meshgrid – ShanZhengYang Jul 09 '15 at 13:04
  • 1
    `meshgrid` easily converts your `x` and `y` into `(50,50)` arrays, but it's up to your code to combine them into the desired output. `numpy` functions and operators do this rapidly for some common operations, like `+`,`*`, and all the `ufunc` functions. But the trick is to express your function in those terms. – hpaulj Jul 09 '15 at 17:09
  • I think my function above is basically a `ufunc` I'm afraid I'm somehow confusing myself. We have (in essence) 50 matrices shaped (4000,4000). The function then does matrix multiplication, and results in 50 values, one for each matrix, i.e.` func(x1,y1), func(x2,y2), func(x3,y3), etc.` I am trying to figure out how to create an output of shape (50,50), such that `func(x1,y1), func(x1,y2), func(x1,y3),... func(x2,y1), func(x2,y2), func(x2,y3),... func(x3,y1), func(x3,y2), func(x3,y3),....` I think meshgrid is the correct way to do this...somehow – ShanZhengYang Jul 09 '15 at 17:26
0

I think there is a better way, it is right on the tip of my tongue, but as an interim measure:

You are operating on 1x2 windows of a meshgrid. You can use as_strided from numpy.lib.stride_tricks to rearrange the meshgrid into two-element windows, then apply your function to the resultant array. I like to use a generic nd solution, sliding_windows (http://www.johnvinyard.com/blog/?p=268) (Not mine) to transform the array.

import numpy as np
a = np.array([1,2,3])
b = np.array([.1, .2, .3])
z= np.array(np.meshgrid(a,b))
def foo((x,y)):
    return x+y

>>> z.shape
(2, 3, 3)
>>> t = sliding_window(z, (2,1,1))
>>> t
array([[ 1. ,  0.1],
       [ 2. ,  0.1],
       [ 3. ,  0.1],
       [ 1. ,  0.2],
       [ 2. ,  0.2],
       [ 3. ,  0.2],
       [ 1. ,  0.3],
       [ 2. ,  0.3],
       [ 3. ,  0.3]])
>>> v = np.apply_along_axis(foo, 1, t)
>>> v
array([ 1.1,  2.1,  3.1,  1.2,  2.2,  3.2,  1.3,  2.3,  3.3])
>>> v.reshape((len(a), len(b)))
array([[ 1.1,  2.1,  3.1],
       [ 1.2,  2.2,  3.2],
       [ 1.3,  2.3,  3.3]])
>>>

This should be somewhat faster.

You may need to modify your function's argument signature.

If the link to the johnvinyard.com blog breaks, I've posted the the sliding_window implementation in other SO answers - https://stackoverflow.com/a/22749434/2823755

Search around and you'll find many other tricky as_strided solutions.

Community
  • 1
  • 1
wwii
  • 23,232
  • 7
  • 37
  • 77
0

In response to your edited question:

normalized_matrix
print normalized_matrix.shape #output (4000,4000)

data_vector = datarr
print datarr.shape #output (4000,)

def func(x, y):
    matrix1 = x [:, None, None] * normalized_matrix[None, :, :]
    matrix2 = y[:, None, None] * id_mat[None, :, :]
    total_matrix = matrix1 + matrix2
    # transpose(datavector) * matrix * datavector
    # by matrix multiplication, equals single value
    # return  np.array([ np.dot(datarr.T,  np.dot(total_matrix, datarr))])
    return np.einsum('j,ijk,k->i',datarr,total_matrix,datarr)

Since datarr is shape (4000,), transpose does nothing. I believe you want the result of the 2 dots to be shape (50,). I'm suggesting using einsum. But it can be done with tensordot, or I think even np.dot(np.dot(total_matrix, datarr),datarr). Test the expression with smaller arrays, focusing on getting the shapes right.

x = np.linspace(1e10, 1e12, num=50) # 50 values
y = np.linspace(1e5, 1e7, num=50)   # 50 values
z = func(x,y)

# X, Y = np.meshgrid(x,y)
# z = func(X, Y)

X,Y is wrong. func takes x and y that are 1d. Notice how you expand the dimensions with [:, None, None]. Also you aren't creating a 2d array from an outer combination of x and y. None of your arrays in func is (50,50) or (50,50,...). The higher dimensions are provided by nomalied_matrix and id_mat.

When showing us the ValueError you should also indicate where in your code that occurred. Otherwise we have to guess, or recreate the code ourselves.

In fact when I run my edited func(X,Y), I get this error:

----> 2         matrix1 = x [:, None, None] * normalized_matrix[None, :, :]
      3         matrix2 = y[:, None, None] * id_mat[None, :, :]
      4         total_matrix = matrix1 + matrix2
      5         # transpose(datavector) * matrix * datavector

ValueError: operands could not be broadcast together with shapes (50,1,1,50) (1,400,400) 

See, the error occurs right at the start. normalized_matrix is expanded to (1,400,400) [I'm using smaller examples]. The (50,50) X is expanded to (50,1,1,50). x expands to (50,1,1), which broadcasts just fine.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks for the response. The `ValueError` occurs with the inclusion of the grid. I'm not sure why you get an error with your function---I do not. In your function above, `matrix1` multiplies x shaped `(50,)` and with `normalized_matrix` shaped `(4000,4000)`. The resulting `matrix1` is of shape `(50,4000,4000)`. There's no problem when I run the code. – ShanZhengYang Jul 13 '15 at 14:10
  • Ah, I understand what you are saying now. x is expanded to `(50, 1, 1)`, which works. Using the grid creates an input shaped `(50,50)`, which doesn't. – ShanZhengYang Jul 13 '15 at 14:17
0

To address the edit and the broadcasting error in the edit:

Inside your function you are adding dimensions to arrays to try to get them to broadcast.

    matrix1 = x [:, None, None] * normalized_matrix[None, :, :]

This expression looks like you want to broadcast a 1d array with a 2d array.

The results of your meshgrid are two 2d arrays:

X,Y = np.meshgrid(x,y)

>>> X.shape, Y.shape
((50, 50), (50, 50))
>>>

When you try to use X in in your broadcasting expression the dimensions don't line up, that is what causes the ValueError - refer to the General Broadcasting Rules:

>>> x1 = X[:, np.newaxis, np.newaxis]
>>> nm = normalized_matrix[np.newaxis, :, :]
>>> x1.shape
(50, 1, 1, 50)
>>> nm.shape
(1, 4000, 4000)
>>> 
wwii
  • 23,232
  • 7
  • 37
  • 77
  • Thanks. I understand now why there's a broadcasting error. Now, to figure out how to figure out how to create a matrix of outputs, `(x1,y1), (x1,y2), (x1,y3),... (x2,y1), (x2,y2), ....` – ShanZhengYang Jul 13 '15 at 14:30
  • @ShanZhengYang see my other answer below - using ```numpy.meshgrid``` and a *sliding window* function based on ```numpy.lib.stride_tricks.as_strided```. – wwii Jul 13 '15 at 16:10
-1

You're on the right track with your list comprehension, you just need to add in an extra level of iteration:

np.array([[func(i,j) for i in x] for j in y])
maxymoo
  • 35,286
  • 11
  • 92
  • 119