在 Python 2.7 中使用 NumPy : Matrix Calculation & npy Files

来源:互联网 发布:旋转矩阵中6保6 编辑:程序博客网 时间:2024/06/06 12:50

Differs from Matlab, NumPy does not apply matrix computation when dealing with
multi-dimensional arraies by default. However, NumPy does provide class
matrix which share lots of similarities with Matlab.

Anyway, it is not recommanded to use matrix objects too frequentyly since it
would lead to ambiguous codes. There are alternatives to be used with
ndarray.

a = array([1,2,3])b = a.reshape((-1,1))aarray([1, 2, 3])barray([[1],       [2],       [3]])dot(a,b)array([14])

Besides dot(), Numpy also provides inner() and outer().

inner() is similar to dot() when dealing with one or two dimensionaly
arraies. Computation of n ( n>2) dimensional arraies is beyond our
discussion.

outer() will always transfer arraies of any dimension to one dimentional
arraies.

There are some complicate function in numpy.linalg . For example, inv()
can compute the inverse matrix, solve() can be used to solve linear
equations.

a = np.random.rand(10,10)b = np.random.rand(10)x = np.linalg.solve(a,b)xarray([ 0.09607134,  0.31188452, -0.93567715,  0.88842109, -0.80243643,        1.00334004, -0.21698236,  0.64968009, -0.24445889,  0.37982568])

ax=b

lstsq() is more general than solve() that can find the least-square
solution that minimizes |bax|.

Now, let’s talk about how to save the valuable variables to files. One of the
simplest ways is save() and load():

a = np.array([[1,2,3],[4,5,6]])np.save("var_a.npy",a)c = np.load("var_a.npy")carray([[1, 2, 3],       [4, 5, 6]])

If you wanna save a couple of variables, savez() cannot be neglected.

b = np.arange(0,1.0,0.1)c = np.sin(b)np.savez("results.npz",a,b,sin_array = c)r = np.load("results.npz")r["arr_0"]array([[1, 2, 3],       [4, 5, 6]])r["arr_1"]array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])r['sin_array']array([ 0.        ,  0.09983342,  0.19866933,  0.29552021,  0.38941834,        0.47942554,  0.56464247,  0.64421769,  0.71735609,  0.78332691])carray([ 0.        ,  0.09983342,  0.19866933,  0.29552021,  0.38941834,        0.47942554,  0.56464247,  0.64421769,  0.71735609,  0.78332691])

Well, that’s enough today.

原创粉丝点击