12/3/2023 0 Comments Numpy permute![]() Omitting a letter from the output means that values along that axis will be summed.This will only work if the axis labelled by j is the same length in both arrays (or the length is 1 in either array). This means that we’re multiplying each row of A with each column of B. In this case, we used the letter j twice: once for A and once for B. The products make up the values for the output array. Repeating letters between input arrays means that values along those axes will be multiplied together.To understand how the output array is calculated, remember these three rules: array (,, ])ĭrawing on the labels, our matrix multiplication with np.einsum('ij,jk->ik', A, B) looks like this: In other words, we’re putting two 2D arrays in and we want a new 2D array out.Ī = np. ![]() The right-hand part of the string labels the axes of the single output array with the letters 'ik'. The left-hand part labels the axes of the input arrays: 'ij' labels A and 'jk' labels B. What does this string mean? Think of 'ij,jk->ik' as split in two at the arrow ->. For two 2D arrays A and B, matrix multiplication can be done with np.einsum('ij,jk->ik', A, B). For simplicity, we’ll stick to the strings (this appears to be the more commonly used of the two options).Ī good example to look at is matrix multiplication, which involves multiplying rows with columns and then summing the products. The function lets us do that in one of two ways: using a string of letters, or using lists of integers. The key is to choose the correct labelling for the axes of the inputs arrays and the array that we want to get out. Even for this tiny example, I timed einsum to be about three times faster. Instead, einsum simply summed the products along the rows as it went. Why better? In short because we didn’t need to reshape A at all and, most importantly, the multiplication didn’t create a temporary array like A * B did. Then there’s a good chance einsum will help us do this much faster and more memory-efficiently that combinations of the NumPy functions multiply, sum and transpose would allow.Īs a small example of the function’s power, here are two arrays that we want to multiply element-wise and then sum along axis 1 (the rows of the array):
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |