Skip to content

Instantly share code, notes, and snippets.

@Cysu
Created January 20, 2017 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cysu/b45242c1e22311118d01dba4d8bf2c3a to your computer and use it in GitHub Desktop.
Save Cysu/b45242c1e22311118d01dba4d8bf2c3a to your computer and use it in GitHub Desktop.
[ELEG5491] Python Tutorial
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Numpy\n",
"\n",
"Numpy is an important scientific computing library for python. It allows you to use vector, matrix, and high-dimensional tensors easily, with lots of math operations supported."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1 2 3]\n",
" [4 5 6]]\n",
"(2, 3)\n",
"[1 2 3]\n",
"1\n",
"[1 4]\n",
"[[1]\n",
" [4]]\n",
"[[False False True]\n",
" [ True True True]]\n",
"[3 4 5 6]\n",
"int64\n",
"[[1 2 3]\n",
" [4 5 6]]\n",
"float32\n",
"[[ 1.10000002 2. 3. ]\n",
" [ 4. 5. 6. ]]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"a = np.asarray([[1,2,3], [4,5,6]]) # construct a 2x3 matrix, row-major\n",
"print a\n",
"print a.shape\n",
"print a[0]\n",
"print a[0,0]\n",
"print a[:, 0] # first column, but results in a 1-d vector\n",
"print a[:, 0:1] # also first column, but results in a 2x1 matrix\n",
"print a > 2 # a binary mask\n",
"print a[a > 2] # select the elements, results in a 1-d vector\n",
"\n",
"print a.dtype # underlying data type to be stored\n",
"a[0,0] = 1.1 # try to set a floating number to a np.int64 matrix\n",
"print a # it doesn't work, but will be truncated to an int\n",
"\n",
"a = a.astype(np.float32) # convert to np.float32\n",
"print a.dtype\n",
"a[0,0] = 1.1 # try again\n",
"print a # it works"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0. 0.]\n",
" [ 0. 0.]]\n",
"[[ 1. 1.]]\n",
"[[7 7]\n",
" [7 7]]\n",
"[[ 1. 0.]\n",
" [ 0. 1.]]\n",
"[[ 0.9091952 0.90574782]\n",
" [ 0.13972143 0.21049777]]\n"
]
}
],
"source": [
"# Commonly used initialization functions, courtesy of cs231n\n",
"a = np.zeros((2,2)) # Create an array of all zeros\n",
"print a # Prints \"[[ 0. 0.]\n",
" # [ 0. 0.]]\"\n",
" \n",
"b = np.ones((1,2)) # Create an array of all ones\n",
"print b # Prints \"[[ 1. 1.]]\"\n",
"\n",
"c = np.full((2,2), 7) # Create a constant array\n",
"print c # Prints \"[[ 7. 7.]\n",
" # [ 7. 7.]]\"\n",
"\n",
"d = np.eye(2) # Create a 2x2 identity matrix\n",
"print d # Prints \"[[ 1. 0.]\n",
" # [ 0. 1.]]\"\n",
" \n",
"e = np.random.random((2,2)) # Create an array filled with random values\n",
"print e # Might print \"[[ 0.91940167 0.08143941]\n",
" # [ 0.68744134 0.87236687]]\""
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 0]\n",
" [0 0]]\n",
"[[ 1 4]\n",
" [ 9 16]]\n",
"[[1 1]\n",
" [1 1]]\n",
"[[ 1. 2.]\n",
" [ 3. 4.]]\n",
"[[ 7 10]\n",
" [15 22]]\n",
"[[10 14]\n",
" [14 20]]\n",
"[0 1 2]\n",
"[3 4 5]\n",
"14\n",
"10\n",
"[4 6]\n",
"[[3]\n",
" [7]]\n",
"2.5\n",
"1.11803398875\n"
]
}
],
"source": [
"# Math functions\n",
"a = np.asarray([[1,2], [3,4]]) # 2x2 matrix\n",
"b = a.copy() # clone it (to a different data storage),\n",
" # otherwise will share the same data\n",
"\n",
"# elementwise operations\n",
"print a - b\n",
"print a * b\n",
"print a / b\n",
"print np.sqrt(a * b)\n",
"\n",
"# matrix-matrix multiplication\n",
"print a.dot(b)\n",
"print a.T.dot(b) # transpose of a, then times b\n",
"\n",
"# vector-vector inner product\n",
"a = np.arange(3) # = np.asarray([0,1,2])\n",
"b = np.arange(3, 6) # = np.asarray([3,4,5])\n",
"print a\n",
"print b\n",
"print a.dot(b) # inner product\n",
"\n",
"# sum / mean / std\n",
"a = np.asarray([[1,2], [3,4]])\n",
"print a.sum() # sum of all the elements, results in a scalar\n",
"print a.sum(axis=0) # sum over rows, results in a 1-d vector\n",
"print a.sum(axis=1, keepdims=True) # sum over columns, results in a nRows x 1 matrix\n",
"print a.mean()\n",
"print a.std()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Broadcasting\n",
"\n",
"Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array. (courtesy of cs231n)\n",
"\n",
"Suppose\n",
"\n",
"A.shape = (3,5,7,4)\n",
"\n",
"B.shape = (7,4)\n",
"\n",
"then A + B will first implictly pad dummy dimensions in front of B, resulting in\n",
"\n",
"B.shape = (1,1,7,4)\n",
"\n",
"and the data will be implictly repeated (just a concept, no extra cost) on the dimension with size=1 for the elementwise adding."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 1 2 3 4]\n",
" [5 6 7 8 9]]\n",
"[0 1 2 3 4]\n",
"[[ 0 2 4 6 8]\n",
" [ 5 7 9 11 13]]\n",
"[0 1]\n",
"[[ 0 1 2 3 4]\n",
" [ 6 7 8 9 10]]\n",
"[[ 0 1 2 3 4]\n",
" [ 6 7 8 9 10]]\n",
"[[ 4 5]\n",
" [ 8 10]\n",
" [12 15]]\n",
"[[ 4 5]\n",
" [ 8 10]\n",
" [12 15]]\n",
"[[ 0. 0.18257418 0.36514837 0.54772252 0.73029673]\n",
" [ 0.31311214 0.37573457 0.438357 0.50097942 0.56360185]]\n"
]
}
],
"source": [
"# Broadcasting\n",
"a = np.arange(10).reshape(2, 5)\n",
"print a\n",
"\n",
"# add vector to each row\n",
"b = np.arange(5)\n",
"print b\n",
"print a + b\n",
"\n",
"# add vector to each column\n",
"c = np.arange(2) # c.shape = (2,)\n",
"print c\n",
"print (a.T + c).T # a.T.shape = (5,2), c is broadcasted\n",
"print a + c.reshape(2, 1) # a.shape = (2,5), c is reshaped then broadcasted\n",
"\n",
"# outer product of two vectors\n",
"a = np.asarray([1,2,3])\n",
"b = np.asarray([4,5])\n",
"print a.reshape(3, 1) * b # shape: (3, 1) * (2,), will pad b.shape to (1, 2),\n",
" # then both a and b will be broadcasted to (3, 2)\n",
"print a[:, np.newaxis] * b # same as a.reshape(3, 1)\n",
"\n",
"# l2-normalize each row\n",
"a = np.arange(10).reshape(2, 5).astype(np.float32)\n",
"a /= np.linalg.norm(a, axis=1, keepdims=True)\n",
"print a"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment