「python」常用语法和函数
文件操作
读取.mat数据集
.mat means the data has been saved in a native Octave or Matlab matrix format. But powerful python can read it by using the loadmat function within the scipy.io module. Then it returns a dictionary字典,键值对
组合路径
import os |
Data is the name of folder, dataset1 is the name of the file.
索引方法
For array of numpy, we can use either y[0, 0] or y[0][0] to index the value.
For array not of numpy, we can only use y[0][0] to index the element.
To check an array is numpy type or not:
import numpy as np |
unroll矩阵
For two-dimension array or matrix, we can use numpy.ravel() to unroll it from matrix to vector.
y = np.array([[1,2,3],[4,5,6]]) |
字典查找
X = data['X'] # find the value of key"X" and assign it to X |
随机选取
np.random.choice(400, 100, replace=false) |
组合矩阵
X_t = np.concatenate([np.ones((5, 1)), np.arange(1, 16).reshape(5, 3, order='F')/10.0], axis=1) |
np.arange(j, k): generate an array(vector). From j to (k - 1), step = 1.
.reshape(5, 3, order='F'): reshape the matrix to 5 by 3 dimension. Order means the way to reshape it. F means according to the column; C means according to the row.
np.concatenate: connect several matrices to a new matrix. axis=1 means according to the column.
矩阵乘法

For numpy array, we can use some pretty useful function:
A.dot(B.T) |
查看文件夹
import os |
随机排列
indices = np.random.permutation(m) |
If inputting a real number, it will return a random array consisting of from 0 to m - 1
If inputting an array, it will retuan a random permutation of the array
矩阵滚动
np.roll(Theta2, 1, axis=0) |







