Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Rewrite for-loop vectorized using Numpy

$
0
0

I have the following code:

def obj(f, pis, rs):    out = np.zeros(f.size)    for pi, r in zip(pis, rs):        out += r * pi / (1 + np.dot(r, f))    return outp = np.array([0.42, 0.08, 0.42, 0.08])r = np.array([[-1.0, 7.0, -1.0, 0.4],              [-1.0, 7.0, 0.5, -1.0],              [0.2, -1.0, -1.0, 0.4],              [0.2, -1.0, 0.5, -1.0]              ])f = np.array([0.25, 0.25, 0.25, 0.25])

I want to vectorize this function.Why is the below implementation not giving the same output:

def obj_vec(f, pis, rs):    out = rs * pis / (1 + np.dot(r, f))    return np.sum(out, axis=1)

How should obj_vec() be defined?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>