这个教程是翻译自Justin Johnson,在斯坦福的课程cs231n中的Tutorial。Ipython Notebook版本来自cs228的Volodymyr Kuleshov和Isaac Caswell。
在cs231n中会有多Python来做所有的作业。Python是一个比较通用且简单的语言,但是由于有很多流行的框架(numpy,scipy,matplotlib)使它成为了一个很强大的科学计算工具。
接下来我们会有一个关于python语言和科学计算的快速介绍。如果你之前有matlab的基础,这里有numpy for Matlab users可以参考。
An example of classic quicksort
Python是高级语言,代码看起来更像是伪代码,因为它可以用很短的几行易读的代码来实现一些非常有力的观点。这里是一个用Python实现快排的简单例子。
|
|
[1, 1, 2, 3, 6, 8, 10]
[1, 1, 2, 3, 6, 8, 10]
Python versions
现在Python主要有两个版本,2.7和3.5(3.6)。因为3.0以后有很多改变,所以2.7版本的代码是不能在3以上版本上运行的。这个教程用的3.6版本。这里也有一个2.7版本的英文教程。
你可以在命令行输入python --version
来查看自己的Python版本。
Basic data types
更绝大多数编程语言一样,Python有基本的数据类型,包括整型,浮点型,布尔型和字符串。这些数据类型在表现上和其他编程语言相似。
数字
整型和浮点型
|
|
<class 'int'>
3
4
2
6
9
4
8
<class 'float'>
2.5 3.5 5.0 6.25
注意:跟其他的很多语言不一样,Python没有x++
和x--
。
还有其他一些复杂的数字类型,可以看官方文档
布尔
Python有很多基础的布尔逻辑运算符,都是用英文表示而不是像其他语言一样用符号$$
,||
等等
|
|
<class 'bool'>
False
True
False
True
字符串
Python对于字符串有着很好的支持
|
|
hello
5
hello world
hello world 12
字符串有很多有用的方法,比如:
还有一些可以参见官方文档
|
|
Hello
HELLO
hello
hello
he(ell)(ell)o
world
Containers
Python有很多内建的容器类型:lists,dictionaries,sets和tuples
列表(lists)
Python的一个列表相当于是数组,但是可以改变大小且能存储不同的数据类型。
|
|
[3, 1, 2] 2
2
[3, 1, 'foo']
[3, 1, 'foo', 'bar']
bar [3, 1, 'foo']
As usual, you can find all the gory details about lists in the documentation.
Slicing
In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
|
|
|
|
Loops
You can loop over the elements of a list like this:
|
|
|
|
If you want access to the index of each element within the body of a loop, use the built-in enumerate
function:
|
|
|
|
List comprehensions:
When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:
|
|
|
|
You can make this code simpler using a list comprehension:
|
|
|
|
List comprehensions can also contain conditions:
|
|
|
|
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map
in Java or an object in Javascript. You can use it like this:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
You can find all you need to know about dictionaries in the documentation.
It is easy to iterate over the keys in a dictionary:
|
|
|
|
If you want access to keys and their corresponding values, use the iteritems method:
|
|
|
|
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:
|
|
|
|
Sets
A set is an unordered collection of distinct elements. As a simple example, consider the following:
|
|
|
|
|
|
|
|
|
|
|
|
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
|
|
|
|
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:
|
|
|
|
Tuples
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
|
|
|
|
|
|
|
|
|
|
Functions
Python functions are defined using the def
keyword. For example:
|
|
|
|
We will often define functions to take optional keyword arguments, like this:
|
|
|
|
Classes
The syntax for defining classes in Python is straightforward:
|
|
|
|
Numpy
Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this tutorial useful to get started with Numpy.
To use Numpy, we first need to import the numpy
package:
|
|
Arrays
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
We can initialize numpy arrays from nested Python lists, and access elements using square brackets:
|
|
|
|
|
|
|
|
|
|
|
|
Numpy also provides many functions to create arrays:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Array indexing
Numpy offers several ways to index into arrays.
Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:
|
|
|
|
A slice of an array is a view into the same data, so modifying it will modify the original array.
|
|
|
|
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:
|
|
|
|
Two ways of accessing the data in the middle row of the array.
Mixing integer indexing with slices yields an array of lower rank,
while using only slices yields an array of the same rank as the
original array:
|
|
|
|
|
|
|
|
|
|
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:
|
|
|
|
|
|
|
|
One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:
|
|
|
|
|
|
|
|
|
|
|
|
Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:
|
|
|
|
|
|
|
|
For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation.
Datatypes
Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:
|
|
|
|
You can read all about numpy datatypes in the documentation.
Array math
Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Note that unlike MATLAB, *
is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:
|
|
|
|
|
|
|
|
|
|
|
|
Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum
:
|
|
|
|
You can find the full list of mathematical functions provided by numpy in the documentation.
Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:
|
|
|
|
|
|
|
|
Broadcasting
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.
For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:
|
|
|
|
This works; however when the matrix x
is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x
is equivalent to forming a matrix vv
by stacking multiple copies of v
vertically, then performing elementwise summation of x
and vv
. We could implement this approach like this:
|
|
|
|
|
|
|
|
Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:
|
|
|
|
The line y = x + v
works even though x
has shape (4, 3)
and v
has shape (3,)
due to broadcasting; this line works as if v actually had shape (4, 3)
, where each row was a copy of v
, and the sum was performed elementwise.
Broadcasting two arrays together follows these rules:
- If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
- The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
- The arrays can be broadcast together if they are compatible in all dimensions.
- After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
- In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension
If this explanation does not make sense, try reading the explanation from the documentation or this explanation.
Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the documentation.
Here are some applications of broadcasting:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible.
This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the numpy reference to find out much more about numpy.
Matplotlib
Matplotlib is a plotting library. In this section give a brief introduction to the matplotlib.pyplot
module, which provides a plotting system similar to that of MATLAB.
|
|
By running this special iPython command, we will be displaying plots inline:
|
|
Plotting
The most important function in matplotlib
is plot, which allows you to plot 2D data. Here is a simple example:
|
|
|
|
With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:
|
|
|
|
Subplots
You can plot different things in the same figure using the subplot function. Here is an example:
|
|
You can read much more about the subplot
function in the documentation.