这里是作者使用python, numpy 以及 scipy时经常忘记的一些有用的小技巧,记录在这里。
斜体字为作者自己的理解,仅供参考,欢迎指教。
参考网址:Python Numpy Tutorial,Numpy and Scipy Documentation,Python 3.5.2 documentation,The Matplotlib API。
Python
- 基本运算
1.1. x**y表示指数计算
1.2. 没有++x,x++,–x,x– - string的函数
2.1. s.capitalize() string第一个字符大写
2.2. s.upper() 所有字符大写
2.3. s.rjust(int) 右对齐
2.4. s.center(int) 居中 - 列表list
3.1. list中的元素不要求类型一致
3.2. list.pop()删除并返回最后一个元素
3.3. slicing: -1,1:3(只能slicing,不能integer index,与numpy.ndarray对应)
3.4. enumerate: for index,value in enumerate(list)
3.5. list comprehension: [x**2 for x in list if x > 0] - 字典dictionary
4.1. dict.get(key,default_value),如果存在key,则返回相应value,否则返回default_value。
4.2. for key in dict:
4.3. for key,value in dict.iteritems():
4.4. dict comprehension:{x:x**2 for x in list] - 集合set
5.1. value in set返回Boolean
5.2. for index,value in enumerate(set):
5.3. set comprehension: {x**2 for x in dict}
Numpy
- 列表内的元素需要同类型,array.dtype用于表示类型
- np.full(size,constant)返回shape=size,都是constant的元素,等价于np.ones(size)*constant
- np.empty_like(x),返回和x一个shape的空矩阵。
- 索引方式:slicing, integer array index, boolean array index
- slicing 和list相同,直接integer索引的区别在于slicing不会降维(比较a[1:2,:] VS a[1,:])
- Integer array index: 假设X的秩为D,shape=[d1,d2,…,dD],那么整形列表的索引值的shape=[N,D’],其中D’<=D,返回[N,d(D’+1),d(D’+2),…,dD]的numpy.ndarray,等价于N个索引拼接在一起。一个例子是X[np.arange(X.shape[0]),label]。
- Boolean array index: 假设X的秩为D, shape=[d1,d2,…,dD],那么Boolean array shape=[d1,d2,…,dD’],其中D’<=D,相应位置为True,则返回相应位置的值。即返回值为[np.sum(index),d(D’+1),d(D’+2),…,dD]。例如print a[a>2]。
- np.tile 在v上面复制多个v的样本。
- Broadcasting: 发生在众多universal function的时候,例如元素对应相加、相乘、相除等等。进行universal function的时候首先判断两个队列是否compatible;如果compatible,如果一个队列相应维数为1,另一个维数大于1,则对于前者在该维进行拓展,最终两个队列shape相同,再进行操作,返回的也是拓展后shape的队列(这个是可以想象为如此操作,但是实际实现中,并没有复制)。对于判断是否compatible,需要从最后一维开始判断,如果都大于一且不相等,则不匹配,否则都是匹配。
SciPy
- scipy.misc.imread(filename)读取图片,返回ndarray
- scipy.misc.imsave(filename,image)存储图片
- scipy.misc.imresize(filename,shape)重新改变大小。
- scipy.io.loadmat读取mat
- scipy.io.savemat存储mat
- scipy.spatial.distance.pdist 用于返回跟定点集中的点对的距离
- scipy.spatial.distance.cdist 用于给定两个点集中两两点对的距离
Matplotlib
- matplotlib.pyplot.plot作图
- matplotlib.pyplot.show展示
- matplotlib.pyplot.xlable/ylabel坐标轴标签
- matplotlib.pyplot.title作图标题
- matplotlib.pyplot.legend legend名称
- matplotlib.pyplot.subplot图片分格作图