1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
|
{
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"cell_type": "markdown",
"metadata": {
"lang": "en"
},
"source": [
"## Introduction to Einstein Notation\n",
"\n",
"This notation allows for expressing an extraordinary number of operations concisely. This section is not\n",
"necessary for the following but it is an interesting intellectual exercise.\n",
"\n",
"The basic idea is to sum the terms of an equation when the same index appears twice and is not defined elsewhere. Thus:\n",
"\n",
"$$ A_{i,i} \\quad \\textrm{means} \\quad \\sum_{i=1}^N A_{i,i} \\; \\textrm{(the trace of the matrix)}$$\n",
"\n",
"If we look at the matrix multiplication $A\\, B$, for every index (i,j) of the result we have:\n",
"\n",
"$$ C_{i,j} = A_{i,k} \\, B_{k,j} \\quad \\textrm{i.e.} \\quad C_{i,j} = \\sum_{k=1}^N A_{i,k} \\, B_{k,j} $$ \n",
"\n",
"The full name of the Einstein notation being the Einstein summation convention, the Numpy function is [`einsum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html). Here is how it works for our first 2 examples:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Trace 'ii' : 12 \n",
"\n",
"Multiplication matricielle A A 'ij,jk->ik' :\n",
"[[ 15 18 21]\n",
" [ 42 54 66]\n",
" [ 69 90 111]]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"A = np.arange(9).reshape(3,3)\n",
"\n",
"print(\"Trace 'ii' : \", np.einsum('ii', A), '\\n') # 0 + 4 + 8 = 12\n",
"\n",
"print(\"Multiplication matricielle A A 'ij,jk->ik' :\")\n",
"print(np.einsum('ij,jk->ik', A, A)) # notez que j'ai nommé différement les indices"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 15, 18, 21],\n",
" [ 42, 54, 66],\n",
" [ 69, 90, 111]])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A.dot(A) # on vérifie"
]
},
{
"cell_type": "markdown",
"metadata": {
"lang": "en"
},
"source": [
"It is noted that the arguments of `einsum` are:\n",
"\n",
"* the summation rule in a string with a comma to separate each component\n",
"* the components on which the rule applies\n",
"\n",
"We can go a little further with Numpy. Here are all the rules that `einsum` uses:\n",
"\n",
"#### Basic and additional rules\n",
"\n",
"1. a repeated index implies summation over that index unless that index is mentioned in the result<br/>(see example of the diagonal of A below for the exception)\n",
"2. indices that repeat from one component to another imply that the referenced elements will be multiplied together<br/> (see example of the matrix product)\n",
"3. a letter omitted in the result (after `->`) implies summation over that index<br/> (see example of summing the elements of a vector below)\n",
"4. if you don't put the arrow, einsum will put it for you with on the right all the indices that are not doubled arranged in alphabetical order<br/> (see example of the transpose below)"
]
},
{
"cell_type": "markdown",
"metadata": {
"lang": "en"
},
"source": [
"Here is a list of operations taken from the [blog of Dr. Goulu](https://www.drgoulu.com/2016/01/17/einsum):\n",
"\n",
"<table align=\"center\">\n",
"<tbody>\n",
"<tr>\n",
"<th>einsum Signature</th>\n",
"<th>Numpy Equivalent</th>\n",
"<th>Description</th>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('i->', v)</code></td>\n",
"<td><code>sum(v)</code></td>\n",
"<td>sum of values of vector v</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('i,i->i', u, v)</code></td>\n",
"<td><code>u \\* v</code></td>\n",
"<td>element-wise multiplication of vectors u and v</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('i,i', u, v)</code></td>\n",
"<td><code>inner(u, v)</code></td>\n",
"<td>dot product of u and v</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('i,j', u, v)</code></td>\n",
"<td><code>outer(u, v)</code></td>\n",
"<td>dyadic product of u and v</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij', A)</code></td>\n",
"<td><code>A</code></td>\n",
"<td>returns matrix A</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ji', A)</code></td>\n",
"<td><code>A.T</code></td>\n",
"<td>transpose of A</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ii->i', A)</code></td>\n",
"<td><code>diag(A)</code></td>\n",
"<td>diagonal of A</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ii', A)</code></td>\n",
"<td><code>trace(A)</code></td>\n",
"<td>sum of the diagonal of A</td>\n",
"</tr>\n",
"<tr>\n",
"<td class=\"tg-031e\"><code>('ij->', A)</code></td>\n",
"<td class=\"tg-031e\"><code>sum(A)</code></td>\n",
"<td class=\"tg-031e\">sum of values of A</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij->j', A)</code></td>\n",
"<td><code>sum(A, axis=0)</code></td>\n",
"<td>sum of columns of A</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij->i', A)</code></td>\n",
"<td><code>sum(A, axis=1)</code></td>\n",
"<td>sum of rows of A</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij,ij->ij', A, B)</code></td>\n",
"<td><code>A \\* B</code></td>\n",
"<td>element-wise transposed matrix multiplication of A and B</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij,jk', A, B)</code></td>\n",
"<td><code>dot(A, B)</code></td>\n",
"<td>dot product of A and B</td> </tr>\n",
"<tr>\n",
"<td><code>('ij,jk->ij', A, B)</code></td>\n",
"<td><code>inner(A, B)</code></td>\n",
"<td>inner product of A and B</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij,jk->ijk', A, B)</code></td>\n",
"<td><code>A[:, None] \\* B</code></td>\n",
"<td>each row of A multiplied by B</td>\n",
"</tr>\n",
"<tr>\n",
"<td><code>('ij,kl->ijkl', A, B)</code></td>\n",
"<td><code>A[:, :, None, None] \\* B</code></td>\n",
"<td>each value of A multiplied by B</td>\n",
"</tr>\n",
"</tbody>\n",
"</table>\n",
"\n",
"The `None` in the last two lines is a way to reshape an array. So `np.arange(6)` is a 1-dimensional array, `np.arange(6)[:]` is the same 1-dimensional array, while `np.arange(6)[:,None]` is a 2-dimensional array namely `6 x 1` when `np.arange(6)[None,:,None]` has 3 dimensions: `1 x 6 x 1`."
]
},
{
"cell_type": "markdown",
"metadata": {
"lang": "en"
},
"source": [
"## Practical Application\n",
"\n",
"We will compare the performance of `einsum` and the corresponding Numpy functions. To do this, calculate\n",
"\n",
"* the cube of each element of a vector\n",
"* of a square matrix, $A^3$,\n",
"\n",
"with `einsum` and without. Compare the execution speed in all cases with 10000 elements."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# a vous de jouer\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Solution :"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11.5 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n",
"15.2 µs ± 131 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
]
}
],
"source": [
"u = np.random.random(10000)\n",
"\n",
"%timeit u*u*u\n",
"%timeit np.einsum('i,i,i->i', u,u,u)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"138 µs ± 9.48 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n",
"134 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"A = u.reshape(100,100)\n",
"\n",
"%timeit A.dot(A).dot(A)\n",
"%timeit np.einsum('ij,jk,kl->il', A, A, A)"
]
},
{
"cell_type": "markdown",
"metadata": {
"lang": "en"
},
"source": [
"We observe that `einsum` is slower (\\*). But looking on the web, we see that this has not always been the case and that it is related to the version of the Numpy library. In conclusion, if we want performance, we should test our code beforehand to choose the fastest method.\n",
"\n",
"(\\*) slightly slower for vector calculation but 1000 times slower on my laptop for `A.dot(A)` (all my processors are running at 100% while the calculation by `einsum` is only done on 1 processor). The `A.dot(A)` version is much faster thanks to the MKL library used by Numpy on my machine."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}
|