\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m arr \u001b[39m=\u001b[39m np\u001b[39m.\u001b[39marray([\u001b[39m10\u001b[39m,\u001b[39m8\u001b[39m,\u001b[39m30\u001b[39m,\u001b[39m40\u001b[39m])\n\u001b[0;32m 2\u001b[0m \u001b[39mprint\u001b[39m (arr)\n\u001b[0;32m 3\u001b[0m mask \u001b[39m=\u001b[39m arr \u001b[39m<\u001b[39m \u001b[39m9\u001b[39m \u001b[39m# construct a boolean array \u001b[39;00m\n","\u001b[1;31mNameError\u001b[0m: name 'np' is not defined"]}],"source":["arr = np.array([10,8,30,40])\n","print (arr)\n","mask = arr < 9 # construct a boolean array \n"," #where i-th eleement is True if the i-th element of arr is less than 9\n","mask"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"RUEwWwPjOmkj","outputId":"5d0069f3-dc75-4c0e-dd57-93d4cb5a0a11"},"outputs":[{"name":"stdout","output_type":"stream","text":["Values below 9: [8]\n"]}],"source":["print ('Values below 9:', arr[mask])"]},{"cell_type":"markdown","metadata":{"id":"48CcJr9LOmkj"},"source":["The index mask can be converted to position index using the `where` function"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"A5cU_GH6Omkk","outputId":"4b40c96a-6f31-4870-8003-21554b443b94"},"outputs":[{"name":"stdout","output_type":"stream","text":["[False True False False]\n"]},{"data":{"text/plain":["(array([1]),)"]},"execution_count":109,"metadata":{},"output_type":"execute_result"}],"source":["print (mask)\n","indices = np.where(mask)\n","indices"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"zvkWv1jKOmkk","outputId":"a4a92c24-45ae-4353-e9e2-b6a4752fc5be"},"outputs":[{"name":"stdout","output_type":"stream","text":["Resetting all values below 9 to 10...\n","[False True False False]\n","[10 10 30 40]\n"]},{"data":{"text/plain":["array([False, False, False, False], dtype=bool)"]},"execution_count":113,"metadata":{},"output_type":"execute_result"}],"source":["print ('Resetting all values below 9 to 10...')\n","print (arr < 9)\n","arr[arr < 9] = 10\n","print (arr)\n","arr < 9"]},{"cell_type":"markdown","metadata":{"id":"xnnHdMaZOmkk"},"source":["It is also possible to select using **integer arrays** that represent indexes."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"zzwyQPp6Omkk","outputId":"1049a74a-00d3-4632-ab0f-fe070f717ead"},"outputs":[{"name":"stdout","output_type":"stream","text":["[10 10 30 40]\n"]},{"data":{"text/plain":["array([10, 30, 40])"]},"execution_count":123,"metadata":{},"output_type":"execute_result"}],"source":["print (arr)\n","row_indices = [1, 2 ,3]\n","arr[row_indices]"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"vhHlXeFUOmkk","outputId":"684c6a7a-a7b4-429a-d44e-050ad0662f8f"},"outputs":[{"data":{"text/plain":["array([ 2., 2., 4., 8., 6., 4.])"]},"execution_count":126,"metadata":{},"output_type":"execute_result"}],"source":["a = np.array([2, 4, 6, 8], float) \n","b = np.array([0, 0, 1, 3, 2, 1], int) # the 0th, 0th, 1st, 3rd, 2nd, and 1st elements of a\n","a[b] "]},{"cell_type":"markdown","metadata":{"id":"N1q5HwSnOmkl"},"source":["For multidimensional arrays, we have to set up one one-dimensional integer array for each axis."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"WzpJjs5cOmkl","outputId":"d43eb2d1-1ba0-4efb-b758-821114713947"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 1. 4.]\n"," [ 9. 16.]]\n"]},{"data":{"text/plain":["array([ 1., 4., 16., 16., 9.])"]},"execution_count":127,"metadata":{},"output_type":"execute_result"}],"source":["a = np.array([[1, 4], [9, 16]], float) \n","print (a)\n","b = np.array([0, 0, 1, 1, 1], int) \n","c = np.array([0, 1, 1, 1, 0], int) \n","a[b,c] "]},{"cell_type":"markdown","metadata":{"id":"TrLrdV7nOmkl"},"source":["## Array Attributes and Methods\n","The information about the type of an array is contained in its *dtype* attribute:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"zJ_RXpCEOmkm","outputId":"097f40ff-97e7-4863-958d-51764b57a8a9"},"outputs":[{"data":{"text/plain":["numpy.ndarray"]},"execution_count":128,"metadata":{},"output_type":"execute_result"}],"source":["# arr is an object of the type ndarray that the numpy module provides.\n","type(arr)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"cSEnnLTWOmkm","outputId":"198b7abf-64f5-41d0-a02c-f22f6c0cc338"},"outputs":[{"data":{"text/plain":["dtype('int64')"]},"execution_count":129,"metadata":{},"output_type":"execute_result"}],"source":["arr.dtype"]},{"cell_type":"markdown","metadata":{"id":"IkVBQY4sOmkm"},"source":["The difference between the `arr` and `M` arrays is only their shapes. We can get information about the shape of an array by using the `ndarray.shape` property."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"AFxf8l97Omkm","outputId":"86eda82b-384d-4cff-84e7-5261bf91a1de"},"outputs":[{"name":"stdout","output_type":"stream","text":["[10 10 30 40]\n"]},{"data":{"text/plain":["(4,)"]},"execution_count":143,"metadata":{},"output_type":"execute_result"}],"source":["arr = np.array([10,10,30,40])\n","print (arr)\n","arr.shape"]},{"cell_type":"code","execution_count":null,"metadata":{"collapsed":true,"id":"Q57UHQVJOmkm"},"outputs":[],"source":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"6dEALPgNOmkm","outputId":"a7829aaa-2ec9-4f6e-88ba-6675e3fdf8ec"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 1 20 -1 40]\n"," [ 0 0 -1 0]]\n"]},{"data":{"text/plain":["(2, 4)"]},"execution_count":146,"metadata":{},"output_type":"execute_result"}],"source":["print( M)\n","M.shape"]},{"cell_type":"markdown","metadata":{"id":"OgrYX_FbOmkm"},"source":["** Don't confuse a matrix with only one row with a vector!!! **, the shapes are not equal!"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_xdb-Ba3Omkn","outputId":"6e6d7d76-25bd-468e-928e-37de4decffcb"},"outputs":[{"name":"stdout","output_type":"stream","text":["[10 10 30 40]\n","(4,)\n","[[10 10 30 40]]\n","(1, 4)\n"]}],"source":["a1 = np.array([[10,10,30,40]])\n","print (arr)\n","print (arr.shape)\n","print (a1)\n","print (a1.shape)"]},{"cell_type":"markdown","metadata":{"id":"2-Vrice9Omkn"},"source":["The number of elements in the array is available through the `ndarray.size` property:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"cM00LmQ9Omkn","outputId":"f6a14282-7838-4de5-b93d-2f0794de1f69"},"outputs":[{"data":{"text/plain":["8"]},"execution_count":151,"metadata":{},"output_type":"execute_result"}],"source":["M.size"]},{"cell_type":"markdown","metadata":{"id":"5QOIvi-mOmkn"},"source":["Equivalently, we could use the function `numpy.shape` and `numpy.size`"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"S-lvk1ZCOmko","outputId":"4209115e-7ffa-485c-ac8c-f08cdf1512a8"},"outputs":[{"data":{"text/plain":["(2, 4)"]},"execution_count":153,"metadata":{},"output_type":"execute_result"}],"source":["np.shape(M)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"dJcNYCHtOmko","outputId":"28e9adef-0758-4df7-974c-d3f070cd0ade"},"outputs":[{"data":{"text/plain":["8"]},"execution_count":154,"metadata":{},"output_type":"execute_result"}],"source":["np.size(M)"]},{"cell_type":"markdown","metadata":{"id":"4wYiQ7tcOmko"},"source":["### More atrributes "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"zE-m1pLCOmko","outputId":"28ab0288-0689-47ca-f921-9b93e628ca6b"},"outputs":[{"data":{"text/plain":["8"]},"execution_count":155,"metadata":{},"output_type":"execute_result"}],"source":["arr.itemsize # bytes per element, int64 -> (8bytes)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"-LXtmW9POmkt","outputId":"db0c3264-879f-4def-fb84-14b167cb9cfd"},"outputs":[{"data":{"text/plain":["32"]},"execution_count":156,"metadata":{},"output_type":"execute_result"}],"source":["arr.nbytes # number of bytes 8*4"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_YIOb24EOmkt","outputId":"0acdbce2-e292-4482-bd5f-03b06bd6421d"},"outputs":[{"name":"stdout","output_type":"stream","text":["Num dim arr: 1 Num dim M: 2\n"]}],"source":["print (\"Num dim arr:\", arr.ndim, \"Num dim M:\", M.ndim) # number of dimensions"]},{"cell_type":"markdown","metadata":{"id":"geDs67gTOmku"},"source":["### Useful Methods "]},{"cell_type":"markdown","metadata":{"id":"BAEp4UotOmku"},"source":["NumPy offers a large library of common mathematical functions that can be applied elementwise to arrays. Among these are the functions: abs,sign, sqrt, log, log10, exp, sin, cos, tan, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, and arctanh . \n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"6w5TTcutOmku","outputId":"22e0bd49-75be-43c1-c53d-105790dd7ce0"},"outputs":[{"data":{"text/plain":["array([ 1., 2., 3.])"]},"execution_count":158,"metadata":{},"output_type":"execute_result"}],"source":["a = np.array([1, 4, 9], float) \n","np.sqrt(a)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"XaqPKD-oOmku","outputId":"4ef8d34d-6288-4a8e-d271-cf00c49753c0"},"outputs":[{"name":"stdout","output_type":"stream","text":["[ 1. 4. 9.]\n","Minimum and maximum : 1.0 9.0\n","Sum and product of all elements : 14.0 36.0\n","Mean and standard deviation : 4.66666666667 3.29983164554\n"]}],"source":["print (a)\n","print ('Minimum and maximum :', a.min(), a.max())\n","print ('Sum and product of all elements :', a.sum(), a.prod())\n","print ('Mean and standard deviation :', a.mean(), a.std())"]},{"cell_type":"markdown","metadata":{"id":"IRtC0JXKOmku"},"source":["If we want to know which index is the maximum or minimum, it can be done using `argmax` and `argmin`"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"4v4xul6JOmku","outputId":"1e84ce3a-b95c-42e6-88ad-e23d8b26604a"},"outputs":[{"name":"stdout","output_type":"stream","text":["[ 1. 4. 9.]\n"]},{"data":{"text/plain":["2"]},"execution_count":160,"metadata":{},"output_type":"execute_result"}],"source":["print (a)\n","np.argmax(a)"]},{"cell_type":"markdown","metadata":{"id":"GJ_NjpDEOmkv"},"source":["For these methods, the above operations area all computed on all the elements of the array. But for a multidimensional array, it's possible to do the computation along a single dimension, by passing the `axis` parameter; for example:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"3BtNlE6pOmkv","outputId":"a40b90f1-0f01-431c-81c5-101240df47b5"},"outputs":[{"name":"stdout","output_type":"stream","text":["For the following array:\n"," [[ 1 20 -1 40]\n"," [ 0 0 -1 0]]\n","The sum of all elements is : 59\n","The sum of elements along the columns is : [ 1 20 -2 40]\n","The sum of elements along the rows is : [60 -1]\n"]}],"source":["print ('For the following array:\\n', M)\n","print ('The sum of all elements is :', M.sum())\n","print ('The sum of elements along the columns is :', M.sum(axis=0))\n","print ('The sum of elements along the rows is :', M.sum(axis=1))\n"]},{"cell_type":"markdown","metadata":{"id":"Vtja7psTOmkv"},"source":["To find unique values in array, we can use the `unique` function:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"YJjWInQzOmkv","outputId":"3a80356f-e9ce-4399-889e-e6399e3ae35f"},"outputs":[{"name":"stdout","output_type":"stream","text":["[10 10 30 40]\n"]},{"data":{"text/plain":["array([10, 30, 40])"]},"execution_count":163,"metadata":{},"output_type":"execute_result"}],"source":["print (arr)\n","np.unique(arr)"]},{"cell_type":"markdown","metadata":{"id":"sD-9wVtmOmkv"},"source":["### Reshaping, resizing and stacking arrays"]},{"cell_type":"markdown","metadata":{"id":"m3vJgRK8Omkv"},"source":["The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"xW6YzVnqOmkw","outputId":"05ece7e9-65fe-4da7-b23b-f8db82f3a193"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 1 20 -1 40]\n"," [ 0 0 -1 0]]\n"]},{"data":{"text/plain":["(2, 4)"]},"execution_count":164,"metadata":{},"output_type":"execute_result"}],"source":["print (M)\n","n, m = M.shape\n","n,m"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"MVbmfNSLOmkw","outputId":"39afd948-f3ab-44a1-d3b6-97bf0f22cc58"},"outputs":[{"name":"stdout","output_type":"stream","text":["(8,)\n"]},{"data":{"text/plain":["array([ 1, 20, -1, 40, 0, 0, -1, 0])"]},"execution_count":165,"metadata":{},"output_type":"execute_result"}],"source":["B = M.reshape(n*m) #matrix to array\n","print (B.shape)\n","B"]},{"cell_type":"markdown","metadata":{"id":"asutAXf0Omkw"},"source":["Using function `repeat`, `tile`, `vstack`, `hstack`, and `concatenate` we can create larger vectors and matrices from smaller ones:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_eIIZaEgOmkw","outputId":"71d13ddc-6239-4704-e2b1-42bc419421b0"},"outputs":[{"data":{"text/plain":["array([[1, 2],\n"," [3, 4]])"]},"execution_count":166,"metadata":{},"output_type":"execute_result"}],"source":["a = np.array([[1, 2], [3, 4]])\n","a"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_1WMixANOmkw","outputId":"92a1f699-4f41-4ea7-c3a6-d2ac79f54fa8"},"outputs":[{"data":{"text/plain":["array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])"]},"execution_count":167,"metadata":{},"output_type":"execute_result"}],"source":["# repeat each element 3 times\n","np.repeat(a, 3)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"uG10yjv1Omkw","outputId":"cb4a8311-8670-43c8-c4ea-73a79beb63ac"},"outputs":[{"data":{"text/plain":["array([[1, 2, 1, 2, 1, 2],\n"," [3, 4, 3, 4, 3, 4]])"]},"execution_count":168,"metadata":{},"output_type":"execute_result"}],"source":["# tile the matrix 3 times \n","np.tile(a, 3)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"mSMK0BuIOmkx","outputId":"e6a6d9f7-fded-43c2-9353-91c8d7803e74"},"outputs":[{"data":{"text/plain":["array([[1, 2],\n"," [3, 4],\n"," [5, 6]])"]},"execution_count":169,"metadata":{},"output_type":"execute_result"}],"source":["np.concatenate((a, np.array([[5, 6]])), axis=0)"]},{"cell_type":"markdown","metadata":{"id":"LO3V11TdOmkx"},"source":["For transposing a matrix, it can be done using the array property T :"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"GXTNcOTzOmkx","outputId":"e1aeae90-508b-4bee-f542-1592cac87465"},"outputs":[{"data":{"text/plain":["array([[1, 2, 5],\n"," [3, 4, 6]])"]},"execution_count":170,"metadata":{},"output_type":"execute_result"}],"source":["np.concatenate((a, np.array([[5, 6]]).T), axis=1)\n"]},{"cell_type":"markdown","metadata":{"id":"svWz4667Omkx"},"source":["**hstack** and **vstack** : shortcuts for concatenate horizontally and vertically"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"MIi3wV4VOmkx","outputId":"793d76d4-db5f-4ea0-e516-b4e93c2af05c"},"outputs":[{"data":{"text/plain":["array([[1, 2],\n"," [3, 4],\n"," [5, 6]])"]},"execution_count":171,"metadata":{},"output_type":"execute_result"}],"source":["np.vstack((a,np.array([[5, 6]])))"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"cp5YEl1fOmkx","outputId":"f9c448c7-0bfe-4cb8-85b1-a20bac7535e7"},"outputs":[{"data":{"text/plain":["array([[1, 2, 5],\n"," [3, 4, 6]])"]},"execution_count":172,"metadata":{},"output_type":"execute_result"}],"source":["np.hstack((a,np.array([[5, 6]]).T))"]},{"cell_type":"markdown","metadata":{"id":"aJTlqTT4Omkx"},"source":["## Copy and \"deep copy\""]},{"cell_type":"markdown","metadata":{"id":"wBZGl6VFOmky"},"source":["To achieve high performance, assignments in Python usually do not copy the underlaying objects. This is important for example when objects are passed between functions, to avoid an excessive amount of memory copying when it is not necessary (techincal term: pass by reference)."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"tXGf5-MWOmky","outputId":"64bb8adc-0cc0-4757-df5d-710b5e3b13b0"},"outputs":[{"data":{"text/plain":["array([[1, 2],\n"," [3, 4]])"]},"execution_count":173,"metadata":{},"output_type":"execute_result"}],"source":["A = np.array([[1, 2], [3, 4]])\n","A"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"TRu42MggOmky"},"outputs":[],"source":["# now B is referring to the same array data as A \n","B = A "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"tBxs9iY_Omky","outputId":"fc4b9728-6752-41c9-a528-a29c5248e4b3"},"outputs":[{"data":{"text/plain":["array([[10, 2],\n"," [ 3, 4]])"]},"execution_count":177,"metadata":{},"output_type":"execute_result"}],"source":["# changing B affects A\n","B[0,0] = 10\n","B"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"Nb3pUPoBOmky","outputId":"8ab0c96b-7803-42d6-9757-359464811a14"},"outputs":[{"data":{"text/plain":["array([[10, 2],\n"," [ 3, 4]])"]},"execution_count":178,"metadata":{},"output_type":"execute_result"}],"source":["A"]},{"cell_type":"markdown","metadata":{"id":"eJsQW91SOmkz"},"source":["If we want to avoid this behavior, so that when we get a new completely independent object B copied from A, then we need to do a so-called \"deep copy\" using the function copy:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"A8NEKeOMOmkz"},"outputs":[],"source":["B = np.copy(A)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"IBKnfSM1Omkz","outputId":"5cc3ecbf-f2fa-44ce-90e3-d620f632603f"},"outputs":[{"data":{"text/plain":["array([[-5, 2],\n"," [ 3, 4]])"]},"execution_count":181,"metadata":{},"output_type":"execute_result"}],"source":["# now, if we modify B, A is not affected\n","B[0,0] = -5\n","B"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"6goWGDcgOmkz","outputId":"e489d776-c63b-44fe-ad12-220f9a5038b4"},"outputs":[{"data":{"text/plain":["array([[10, 2],\n"," [ 3, 4]])"]},"execution_count":182,"metadata":{},"output_type":"execute_result"}],"source":["A"]},{"cell_type":"markdown","metadata":{"id":"IpLoqaVXOmkz"},"source":["## Operating with arrays\n","Arrays support all regular arithmetic operators, and the numpy library also contains a complete collection of basic mathematical functions that operate on arrays. It is important to remember that in general, all operations with arrays are applied *element-wise*, i.e., are applied to all the elements of the array at the same time. "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"c_yocYIROmkz","outputId":"701aebce-401b-481a-d9bf-77d8fb650e37"},"outputs":[{"data":{"text/plain":["array([0, 1, 2, 3])"]},"execution_count":183,"metadata":{},"output_type":"execute_result"}],"source":["v1 = np.arange(0, 4)\n","v1"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"N-AM2CIsOmkz","outputId":"fdde4232-b8b3-448f-ba93-f4ed4e0507df"},"outputs":[{"data":{"text/plain":["array([0, 2, 4, 6])"]},"execution_count":184,"metadata":{},"output_type":"execute_result"}],"source":["v1 * 2"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"9h1C9Ye1Omk0","outputId":"36c9b25a-73fd-4791-b6df-ad566d6d77b9"},"outputs":[{"data":{"text/plain":["array([2, 3, 4, 5])"]},"execution_count":185,"metadata":{},"output_type":"execute_result"}],"source":["v1 + 2"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"rSupK0i_Omk0","outputId":"1d001455-9f20-4781-9a00-e8249d3c0a78"},"outputs":[{"data":{"text/plain":["array([[ 2, 40, -2, 80],\n"," [ 0, 0, -2, 0]])"]},"execution_count":186,"metadata":{},"output_type":"execute_result"}],"source":["M*2"]},{"cell_type":"markdown","metadata":{"id":"u5WYQHDHOmk0"},"source":["When we add, subtract, multiply and divide arrays with each other, the default behaviour is **element-wise** operations:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"CerxJValOmk0","outputId":"78dc7da8-94d3-49ea-b86f-0e7ed07a0ef4"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 1 20 -1 40]\n"," [ 0 0 -1 0]]\n"]},{"data":{"text/plain":["array([[ 1, 400, 1, 1600],\n"," [ 0, 0, 1, 0]])"]},"execution_count":187,"metadata":{},"output_type":"execute_result"}],"source":["print (M)\n","M*M"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"asaa1T4vOmk0","outputId":"0c1913d3-21a7-4cc0-8180-04e1a2be3e17"},"outputs":[{"data":{"text/plain":["array([0, 1, 4, 9])"]},"execution_count":188,"metadata":{},"output_type":"execute_result"}],"source":["v1*v1"]},{"cell_type":"markdown","metadata":{"id":"6159t26cOmk0"},"source":["If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"xdpI01HEOmk1","outputId":"78858f7f-23d3-4509-eae8-5257f31ee397"},"outputs":[{"data":{"text/plain":["((2, 4), (4,))"]},"execution_count":189,"metadata":{},"output_type":"execute_result"}],"source":["M.shape, v1.shape"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"JsRWjmBrOmk1","outputId":"aa55f67d-ed2a-423a-e1be-aae087aa3858"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 1 20 -1 40]\n"," [ 0 0 -1 0]]\n","[0 1 2 3]\n"]},{"data":{"text/plain":["array([[ 0, 20, -2, 120],\n"," [ 0, 0, -2, 0]])"]},"execution_count":190,"metadata":{},"output_type":"execute_result"}],"source":["print (M)\n","print (v1)\n","M * v1"]},{"cell_type":"markdown","metadata":{"id":"I_H56z7WOmk1"},"source":["What about matrix mutiplication? We can use the `dot` function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments: "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"2ccP8mhGOmk1","outputId":"aa64b094-a78f-4d2e-c66d-447fff557921"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 1 20 -1 40]\n"," [ 0 0 -1 0]]\n","[0 1 2 3]\n"]},{"data":{"text/plain":["array([138, -2])"]},"execution_count":191,"metadata":{},"output_type":"execute_result"}],"source":["print (M)\n","print (v1)\n","np.dot(M,v1)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"lTx-or_yOmk2","outputId":"c29da683-c32b-4433-e7c9-b0388fb06271"},"outputs":[{"data":{"text/plain":["14"]},"execution_count":192,"metadata":{},"output_type":"execute_result"}],"source":["np.dot(v1,v1)"]},{"cell_type":"markdown","metadata":{"id":"tqghkS9SOmk2"},"source":["### Broadcasting "]},{"cell_type":"markdown","metadata":{"id":"I9Of8Z_lOmk2"},"source":["Broadcasting means that, in principle, arrays must always match in their dimensionality in order for an operation to be valid, numpy will *broadcast* dimensions when possible. Previous examples of operations with an scalar and a vector is broadcasting:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"GO8kXl0nOmk2","outputId":"ece5989a-8675-4eb1-a84e-facbea155c64"},"outputs":[{"name":"stdout","output_type":"stream","text":["[0 1 2 3]\n"]},{"data":{"text/plain":["array([5, 6, 7, 8])"]},"execution_count":193,"metadata":{},"output_type":"execute_result"}],"source":["print (v1)\n","v1 + 5 # broadcasting => [0 1 2 3] + [5 5 5 5]"]},{"cell_type":"markdown","metadata":{"id":"OOFwox_0Omk2"},"source":["We can also broadcast a 1D array to a 2D array, in this case adding a vector to all rows of a matrix:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"iMXSAwylOmk2","outputId":"ced84c72-8fa8-4d6f-e881-ba461e41461e"},"outputs":[{"data":{"text/plain":["array([[ 1., 2., 3., 4.],\n"," [ 1., 2., 3., 4.],\n"," [ 1., 2., 3., 4.],\n"," [ 1., 2., 3., 4.]])"]},"execution_count":194,"metadata":{},"output_type":"execute_result"}],"source":["np.ones((4, 4)) + v1 # broadcasting = np.ones(4,4) + np.tile(v1,4)"]},{"cell_type":"markdown","metadata":{"id":"af5UM4dxOmk2"},"source":["We can also broadcast in two directions at a time:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"s7QDnIdDOmk3","outputId":"0f7dec65-c0ee-4368-c3c9-6fa41bf496ab"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[0]\n"," [1]\n"," [2]\n"," [3]]\n","[0 1 2 3]\n"]},{"data":{"text/plain":["array([[0, 1, 2, 3],\n"," [1, 2, 3, 4],\n"," [2, 3, 4, 5],\n"," [3, 4, 5, 6]])"]},"execution_count":195,"metadata":{},"output_type":"execute_result"}],"source":["print (v1.reshape((4, 1)))\n","print (np.arange(4))\n","v1.reshape((4, 1)) + np.arange(4)"]},{"cell_type":"markdown","metadata":{"id":"0PrUHU9ZOmk3"},"source":["** Rules of Broadcasting **\n","\n","Broadcasting follows the next algorithm:\n","\n","1. If the two arrays differ in their number of dimensions, the shape of the array with fewer dimensions is padded with ones on its leading (left) side.\n","\n","2. If the shape of the two arrays does not match in any dimension, the array with shape equal to 1 in that dimension is stretched to match the other shape.\n","\n","3. If in any dimension the sizes disagree and neither is equal to 1, an error is raised.\n","\n","Note that all of this happens without ever actually creating the stretched arrays in memory! This broadcasting behavior is in practice enormously powerful, especially because when numpy broadcasts to create new dimensions or to `stretch` existing ones, it doesn't actually replicate the data. \n","\n","\n","In the first example: \n","\n"," v1 + 5\n","\n","the operation is carried as if the 5 was a 1-d array with 5 in all of its entries, but no actual array was ever created.\n","\n","In the example\n","\n"," v1.reshape((4, 1)) + np.arange(4)\n"," \n","- the second array is 'promoted' to a 2-dimensional array of shape (1, 4)\n","- the second array is 'stretched' to shape (4, 4)\n","- the first array is 'stretched' to shape (4, 4)\n","\n","Then the operation proceeds as if on two 4 $\\times$ 4 arrays."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"7OH1Y3dCOmk3","outputId":"0afca0d9-ec19-41c6-a2c9-4fa97ba43c05"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[0 1 2 3]\n"," [0 1 2 3]\n"," [0 1 2 3]\n"," [0 1 2 3]]\n","[[0 0 0 0]\n"," [1 1 1 1]\n"," [2 2 2 2]\n"," [3 3 3 3]]\n"]},{"data":{"text/plain":["array([[0, 1, 2, 3],\n"," [1, 2, 3, 4],\n"," [2, 3, 4, 5],\n"," [3, 4, 5, 6]])"]},"execution_count":196,"metadata":{},"output_type":"execute_result"}],"source":["#Broadcasting unrolled\n","print (np.tile(np.arange(4),(4,1)))\n","print (np.tile(v1.reshape((4,1)),4))\n","np.tile(np.arange(4),(4,1)) + np.tile(v1.reshape((4,1)),4)"]},{"cell_type":"markdown","metadata":{"id":"Cz_6AQLBOmk3"},"source":["### Visualizing Broadcasting\n","\n","\n","\n","([image source](http://www.astroml.org/book_figures/appendix/fig_broadcast_visual.html))"]},{"cell_type":"markdown","metadata":{"id":"338O6FNQOmk3"},"source":["Sometimes, however, we can use the ``newaxis`` constant to specify how we \n","want to broadcast:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"NrlLRl7oOmk3","outputId":"97e3aaed-cee8-4063-b03d-803c0e7bb1ae"},"outputs":[{"name":"stdout","output_type":"stream","text":["[[ 0. 0.]\n"," [ 0. 0.]] [-1. 3.]\n","[[-1. 3.]\n"," [-1. 3.]]\n","[[-1. 3.]\n"," [-1. 3.]]\n","[[-1. -1.]\n"," [ 3. 3.]]\n"]}],"source":["a = np.zeros((2,2), float) \n","b = np.array([-1., 3.], float) \n","print (a, b)\n","print\n","print (a + b) \n","print\n","print (a + b[np.newaxis,:]) \n","print\n","print (a + b[:,np.newaxis]) "]},{"cell_type":"markdown","metadata":{"id":"34nVkeTeOmk4"},"source":["# Further reading\n","\n","* http://numpy.scipy.org\n","* http://scipy.org/Tentative_NumPy_Tutorial\n","* http://scipy.org/NumPy_for_Matlab_Users - A Numpy guide for MATLAB users."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"KUZNE4mQOmk4"},"outputs":[],"source":[]},{"cell_type":"markdown","metadata":{"id":"hff_Y_wuOmk4"},"source":["# Exercises"]},{"cell_type":"markdown","metadata":{"id":"Mhe9EvavOmk4"},"source":["1) In the following table we have expression values for 5 genes at 4 time points. "]},{"cell_type":"code","execution_count":19,"metadata":{"id":"vflUdqRFOmk4","colab":{"base_uri":"https://localhost:8080/","height":52},"executionInfo":{"status":"ok","timestamp":1676634579607,"user_tz":-60,"elapsed":201,"user":{"displayName":"toni Monleon","userId":"05269440626861479105"}},"outputId":"9e0009cf-8753-4f63-ebdc-79c3dc274684"},"outputs":[{"output_type":"stream","name":"stdout","text":["cat: genes.csv: No such file or directory\n"]},{"output_type":"execute_result","data":{"text/plain":["/content/genes.csv"],"text/html":["Path (genes.csv) doesn't exist. It may still be in the process of being generated, or you may have the incorrect path."]},"metadata":{},"execution_count":19}],"source":["from IPython.lib import display\n","%cat 'genes.csv' \n","display.FileLink('genes.csv')\n"]},{"cell_type":"markdown","metadata":{"id":"PX-uj88kOmk5"},"source":[" - Create a single array for the data (4x4)\n"," - Find the mean expression value per gene\n"," - Find the mean expression value per time point\n"," - Which gene has the maximum mean expression value? (Use the ``tab`` help on an `array`)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"l6XRTigLOmk5"},"outputs":[],"source":["#Your Code Here"]},{"cell_type":"markdown","metadata":{"id":"Rrc_prZyOmk5"},"source":["`ipythonblocks` is a teaching tool that allows students to experiment with Python flow control concepts and immediately see the effects of their code represented in a colorful, attractive way. BlockGrid objects can be **indexed and sliced like 2D NumPy arrays** making them good practice for learning how to access arrays. "]},{"cell_type":"code","execution_count":20,"metadata":{"id":"TUsDAJAqOmk5","outputId":"c9a9a3cb-0908-437f-c4e9-f216784e1976","colab":{"base_uri":"https://localhost:8080/","height":235},"executionInfo":{"status":"error","timestamp":1676634588858,"user_tz":-60,"elapsed":169,"user":{"displayName":"toni Monleon","userId":"05269440626861479105"}}},"outputs":[{"output_type":"error","ename":"FileNotFoundError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mchdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'./modules/'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mipythonblocks\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mBlockGrid\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mipythonblocks\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mcolors\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: './modules/'"]}],"source":["import os\n","import numpy as np\n","os.chdir('./modules/')\n","from ipythonblocks import BlockGrid\n","from ipythonblocks import colors\n","os.chdir('..')\n","grid = BlockGrid(8, 8, fill=(123, 234, 123))\n","grid.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"vpQcQf1COmk5","outputId":"88281a99-49cf-4abb-e6bb-62a4c2ece3c8"},"outputs":[{"data":{"text/plain":["array([[0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0]])"]},"execution_count":199,"metadata":{},"output_type":"execute_result"}],"source":["a = np.array(np.zeros([8,8],dtype='int64'))\n","a"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"crfF7dIHOmk5","outputId":"2e7d087d-4896-44aa-840a-42ab331f5f22"},"outputs":[{"data":{"text/html":[""],"text/plain":["Block(123, 234, 123, size=20)"]},"execution_count":200,"metadata":{},"output_type":"execute_result"}],"source":["grid[0, 0] #access to [0,0] element"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"P14HvuedOmk5","outputId":"c33bebfb-3d32-40a3-b4c5-92c616287a93"},"outputs":[{"data":{"text/html":[""],"text/plain":[""]},"metadata":{},"output_type":"display_data"}],"source":["grid[0:2,:] = colors['Teal']\n","grid.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"FhTT2nnQOmk5","outputId":"fa2c602f-13b6-4d08-af3c-cafcd9c411eb"},"outputs":[{"data":{"text/plain":["array([[1, 1, 1, 1, 1, 1, 1, 1],\n"," [1, 1, 1, 1, 1, 1, 1, 1],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0],\n"," [0, 0, 0, 0, 0, 0, 0, 0]])"]},"execution_count":202,"metadata":{},"output_type":"execute_result"}],"source":["a[0:2,:] = 1\n","a"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"Wmou7EEVOmk6","outputId":"53b6ed9f-9d31-49f4-b11c-666d194eddfb"},"outputs":[{"data":{"text/html":[""],"text/plain":[""]},"metadata":{},"output_type":"display_data"}],"source":["grid[2,1:] = colors['Blue']\n","grid.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"BjPcKWxGOmk6"},"outputs":[],"source":["a[2,1:] = 2\n","a"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"aLB4QxcNOmk6"},"outputs":[],"source":["grid[:2,2:3] = colors['Peru']\n","grid.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"9OvagzXUOmk6"},"outputs":[],"source":["a[:2,2:3] = 3\n","a"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"C0NXb6APOmk6"},"outputs":[],"source":["grid[:,::2] = colors['Peru']\n","grid.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"pQph2OxZOmk6"},"outputs":[],"source":["a[:,::2] = 4\n","a"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"BfIdhTnAOmk6"},"outputs":[],"source":["grid[::2,::3] = colors['Red']\n","grid.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ON7tEiKBOmk7"},"outputs":[],"source":["a[::2,::3] = 5\n","a"]},{"cell_type":"markdown","metadata":{"id":"klGJsmOwOmk7"},"source":["2) Build a graphical representation of all multiple of 3 numbers from 0 to 49 by using exclusively the slicing operator (no iterations). "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"8NFsy7_lOmk7"},"outputs":[],"source":["grid = BlockGrid(50, 1, block_size=10, fill=(123, 234, 123))\n","grid\n","# Your solution here"]},{"cell_type":"markdown","metadata":{"id":"ExPrBbHSOmk7"},"source":["3) Build a graphical representation of a chessboard 8x8 by using exclusively the slicing operator (no iterations)."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"FN1JXE2VOmk7"},"outputs":[],"source":["grid = BlockGrid(8, 8, block_size=20, fill=(0, 0, 0))\n","# Your solution here"]},{"cell_type":"markdown","metadata":{"id":"U-gldXIVOmk8"},"source":["4) Build a graphical representation of the prime numbers from 0 to 4999. (Hint: Compute the list of prime numbers and map this list to the grid representation)."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ZxV62qVJOmk8"},"outputs":[],"source":["BlockGrid(50, 100, block_size=10, fill=(123, 234, 123))\n","# Your solution here"]}],"metadata":{"kernelspec":{"display_name":"Python 3.7.7rc1 64-bit","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.7.7"},"vscode":{"interpreter":{"hash":"5060c395ae64037ee8844c2173a43fa7410db02f7938ed2393fe6924352a78b7"}},"colab":{"provenance":[],"collapsed_sections":["-z1NA-L1OmkP","FmasiQbBOmkT","9oUp8vnpOmkY","aKjQ0Jn3OmkY","h9b07wtqOmkd","oBxy8rcCOmkg","NT8Kvw8ZOmki","TrLrdV7nOmkl","4wYiQ7tcOmko","geDs67gTOmku","sD-9wVtmOmkv","aJTlqTT4Omkx","IpLoqaVXOmkz","tqghkS9SOmk2","Cz_6AQLBOmk3"]}},"nbformat":4,"nbformat_minor":0} |