Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python 3.x - Triple for-loop in a vector

I have a simple numpy array (3xN) like:

v = np.array([[-3.33829, -3.42467, -3.53332],
   [-2.67681, -2.6082 , -3.49502],
   [-3.49497, -2.73177, -2.61499],
   [-2.76056, -3.57753, -2.67334],
   [-1.96801, -3.47521, -3.51974],
   [-1.25571, -2.69451, -3.45554],
   [-1.94568, -2.59504, -2.72568],
   [-1.28991, -3.47927, -2.73176],
   [-0.51201, -3.50684, -3.40448],
   [ 0.22398, -2.70244, -3.43421]])

Here, N = 10, but it is much larger than here (+500) in my real case. Each row is a point - Euclidean coordinate.

I would like to carry out:

enter image description here

where i, j and k indicate different rows from v.

How can I implement it on Python in a fast way?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using numpy broadcasting operations:

diffs = ((v[:, None] - v) ** 2).sum(-1)
d = np.exp(diffs + diffs[:, None]).sum((0, 1))
print(d)

# [3.08316899e+11 2.37020625e+07 4.05357364e+12 8.22697743e+08
#  8.85209202e+04 2.55340202e+05 7.33879459e+04 1.88175133e+05
#  8.10134295e+08 6.62122925e+12]

Even for an array of size 500, the result is computed in just a few seconds:

%%time
v = np.random.rand(500, 3)
diffs = np.sum((v[:, None] - v) ** 2, -1)
d = np.exp(diffs + diffs[:, None]).sum((0, 1))

# CPU times: user 2.74 s, sys: 5.5 ms, total: 2.75 s
# Wall time: 2.75 s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...