Numpy: How to Vectorize Functional Form Parameters of a Function Applied to a Dataset

Ultimately, I want to remove all explicit loops in the code below to take advantage of numpy vectorization and function calls in C instead of python.

The following is a simplified use of numpy in python. I have the following quadratic function:

def quadratic_func(a,b,c,x):
    return a*x*x + b*x + c

I am trying to optimize the selection of a, b, c of input data x and output y of the same size (of course, this should be done using linear regression ... but with humor). Let's say len (x) = 100. It is easy to vectorize with scalars a, b, c to return a result of length 100.

Let's say that we know that a, b, c must be inside [-10,10], and I optimize by building a grid and choosing a point with a square error of the minimum amount.

a=np.arange(-10.0, 10.01, 2.0)
nodes=np.array(np.meshgrid(a,a,a)).T.reshape(-1,3) #3-d cartesian product with array of nodes

1331, 1331 100 .

res=[]
x=np.random.uniform(-5.0,5.0, 100)
for node in nodes:
    res.append(quadratic_func(*node, x=x))

, 1331 , 100 , quadratic_func x? , .., , . , quadratic_func - , , my_func (* node, x = x).

, . , "" - , , !

+4
1

broadcasting np.einsum -

np.einsum('ij,jk->ik',nodes,x**np.array([2,1,0])[:,None])

, np.dot -

nodes.dot(x**np.array([2,1,0])[:,None])
+1

Source: https://habr.com/ru/post/1658256/


All Articles