Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Application of Dot Product

I want to apply a function that would generate the result of this in general cases:

np.dot(np.dot(np.dot(D3, theta2), D2), theta1)

That is, instead of specifying D3, theta2, etc., it would be done in general case like

if n==1:
   answer = np.dot(params['D'+str(n)], params['theta'+str(n - 1)])
else:
   answer = ? 

Do you have any ideas how I can do this?

like image 401
Alger Remirata Avatar asked Dec 21 '25 23:12

Alger Remirata


1 Answers

Like already mentioned by @wwii you can use functools.reduce instead of recursion:

import functools

def dot(a, b):
    return 'dot({}, {})'.format(a, b)

>>> functools.reduce(dot, ['theta2', 'D2', 'theta1'], 'D3')
'dot(dot(dot(D3, theta2), D2), theta1)'

Just replace the variables with the actual function and variables:

functools.reduce(np.dot, [D3, theta2, D2, theta1])
like image 187
MSeifert Avatar answered Dec 24 '25 12:12

MSeifert



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!