{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Einstein summation in numpy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It turns out that `numpy` actually has several more mini-languages embedded in it. This next example is borrowed and slightly generalized from mathematics, where it is called Einstein summation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Recall that matrix-matrix multiplication can be expressed by:\n", "$$\n", "(AB)_{ij} = \\sum_k A_{ik} B_{kj}$$\n", "\n", "Einstein summation is a relatively natural way of generalizing this to arrays with multiple dimensions. The above matrix-matrix multiplication expression, for example, becomes:\n", "\n", "$$ A_{ij} = B_{ik} C_{kj}$$\n", "\n", "Where the implied rule is that repeated indices that are not part of the output will be summed over.\n", "\n", "numpy simply takes this convention and turns it into a way of expressing array operations:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "A = np.random.randn(15, 20)\n", "B = np.random.randn(20, 25)\n", "\n", "AB1 = A.dot(B)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.21357255039e-14\n" ] } ], "source": [ "AB2 = np.einsum(\"ik,kj->ij\", A, B)\n", "\n", "print(np.linalg.norm(AB1 - AB2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "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.5.0+" } }, "nbformat": 4, "nbformat_minor": 0 }