{"nbformat_minor": 0, "metadata": {"signature": "sha256:b6d9a476086558374345fba41b5b6add09f54f82264a9d446b8d4b3cd49dee53", "name": ""}, "nbformat": 3, "worksheets": [{"metadata": {}, "cells": [{"source": ["# numpy: Broadcasting"], "metadata": {}, "cell_type": "markdown"}, {"metadata": {}, "cell_type": "code", "outputs": [], "language": "python", "collapsed": false, "input": ["import numpy as np"], "prompt_number": 1}, {"metadata": {}, "cell_type": "code", "outputs": [{"output_type": "stream", "stream": "stdout", "text": ["(3, 3)\n", "[[0 1 2]\n", " [3 4 5]\n", " [6 7 8]]\n", "(3, 3)\n", "[[ 4 5 6]\n", " [ 7 8 9]\n", " [10 11 12]]\n"]}], "language": "python", "collapsed": false, "input": ["a = np.arange(9).reshape(3, 3)\n", "print(a.shape)\n", "print(a)\n", "b = np.arange(4, 4+9).reshape(3, 3)\n", "print(b.shape)\n", "print(b)"], "prompt_number": 2}, {"metadata": {}, "cell_type": "code", "outputs": [{"output_type": "pyout", "metadata": {}, "text": ["array([[ 4, 6, 8],\n", " [10, 12, 14],\n", " [16, 18, 20]])"], "prompt_number": 3}], "language": "python", "collapsed": false, "input": ["a+b"], "prompt_number": 3}, {"source": ["So this is easy and one-to-one.\n"], "metadata": {}, "cell_type": "markdown"}, {"source": ["---\n", "\n", "What if the shapes do not match?"], "metadata": {}, "cell_type": "markdown"}, {"metadata": {}, "cell_type": "code", "outputs": [{"output_type": "stream", "stream": "stdout", "text": ["(3, 3)\n", "[[0 1 2]\n", " [3 4 5]\n", " [6 7 8]]\n", "(3,)\n", "[0 1 2]\n"]}], "language": "python", "collapsed": false, "input": ["a = np.arange(9).reshape(3, 3)\n", "print(a.shape)\n", "print(a)\n", "b = np.arange(3)\n", "print(b.shape)\n", "print(b)"], "prompt_number": 4}, {"source": ["What will this do?"], "metadata": {}, "cell_type": "markdown"}, {"metadata": {}, "cell_type": "code", "outputs": [{"output_type": "pyout", "metadata": {}, "text": ["array([[ 0, 2, 4],\n", " [ 3, 5, 7],\n", " [ 6, 8, 10]])"], "prompt_number": 5}], "language": "python", "collapsed": false, "input": ["a+b"], "prompt_number": 5}, {"source": ["It has *broadcast* along the last axis!"], "metadata": {}, "cell_type": "markdown"}, {"source": ["---\n", "\n", "Can we broadcast along the *first* axis?"], "metadata": {}, "cell_type": "markdown"}, {"metadata": {}, "cell_type": "code", "outputs": [{"output_type": "pyout", "metadata": {}, "text": ["array([[ 0, 1, 2],\n", " [ 4, 5, 6],\n", " [ 8, 9, 10]])"], "prompt_number": 6}], "language": "python", "collapsed": false, "input": ["a+b.reshape(3, 1)"], "prompt_number": 6}, {"source": ["Rules:\n", "\n", "* Shapes are matched axis-by-axis from last to first.\n", "* A length-1 axis can be *broadcast* if necessary."], "metadata": {}, "cell_type": "markdown"}]}]}