0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

numpy.einsum

Posted at
a = np.arange(6).reshape(2,3)
b = np.arange(6).reshape(3,2)*2
print(a)
print(b)
print(np.dot(a,b))
print(np.einsum("ij,ji->i",a,b)) # sum(aij*bji)
print(np.einsum("ij,ji->j",a,b)) # sum(bij*aji)
print("====")
a = np.array([1,2,3,4]).reshape(2,2)
b = np.array([1,2,3,4]).reshape(2,2)*2
print(a)
print(b)
print(np.einsum("ii",a))
print(np.einsum("aa",a))
print(np.einsum("ij",a))
print(np.einsum("ii->i",a))
# print(np.einsum("ii->ii",a)) # invalid
print("====")
print(np.einsum("ab->a",a))
print(np.einsum("cd->dc",a))
print(np.einsum("ij,ji->i",a,b))
print(np.einsum("ij,ji->j",a,b))
# print(np.einsum("ij,ji->x",a,b))  # invalid
print("====i,j,k====")
print(np.einsum("ij,jk->k",a,b))
print(np.einsum("ij,jk->ik",a,b)) # ab
print("====")
# print(np.einsum("ii,ii",a,b)) # invalid
# print(np,einsum("ii,jj",a,b)) # invalid
print(np.einsum("ii,ii->i",a,b)) # (a11b11, a22b22): multiply diagonal components
print(np.einsum("ii,jj->j",a,b)) # (a11(b12+b21), a22(b12+b21)): multiply multiply a's diagonal matrix and b's anti-diagonal matrix

n = 2
A = np.random.uniform(0,1,(n,n))
B = np.random.uniform(0,1,(n,n))
print("====sum====")
s = time.time()
x = A * B.T
print(x)
print(np.sum(x, axis=1))
print("time:"+str(time.time()-s))
print("====einsum====")
s = time.time()
print(np.einsum("ij,ji->i", A, B)) 
print("time:"+str(time.time()-s))
[[0 1 2]
 [3 4 5]]
[[ 0  2]
 [ 4  6]
 [ 8 10]]
[[20 26]
 [56 80]]
[20 80]
[ 6 28 66]
====
[[1 2]
 [3 4]]
[[2 4]
 [6 8]]
5
5
[[1 2]
 [3 4]]
[1 4]
====
[3 7]
[[1 3]
 [2 4]]
[14 44]
[14 44]
====i,j,k====
[44 64]
[[14 20]
 [30 44]]
====
[ 2 32]
[10 40]
====sum====
[[ 0.11653899  0.12994759]
 [ 0.43544416  0.679387  ]]
[ 0.24648658  1.11483116]
time:0.00037097930908203125
====einsum====
[ 0.24648658  1.11483116]
time:0.00011920928955078125

Refs.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?