python numpy模块玩转矩阵与科学计算

来源:互联网 发布:路由器劫持软件 编辑:程序博客网 时间:2024/05/17 18:03

学生时代玩矩阵最爽的工具自然是matlab了。而且matlab天生就是为科学计算,为矩阵而生。matlab的一切对象皆可看成矩阵,最简单的一个整数,也是个1*1的矩阵。但是在公司里面以后,matlab就玩不转了。道理很简单,matlab虽然好用,但是正版软件非常贵。而且,matlab是闭源,跟现在开源的潮流也有些不大符合。。。
那在公司里面,怎么玩科学计算,怎么玩矩阵呢。其实很简单,涉及到数据处理的活,用python嘛。具体到矩阵计算,有大名鼎鼎的numpy模块。在python中,numpy是科学计算的基石,其他的高阶模块,如scipy,sklearn都建立在numpy的基础上。博主玩numpy的时间也不短了,抽空把numpy的一些基本用法给稍微总结一下,供有需要的同学参考。。

numpy大体上与matlab的使用方式很像。如果玩过matlab的同学们看numpy,那简直就是一样一样的。如果让我说numpy跟matlab的最大不同,那就是numpy的组织方式是以数组或多维数组为单位(当然numpy里也有矩阵),而matlab里的一切都是矩阵。。。

啥也不说先,先上代码,给大家一个大概的印象

1.最简单的构造矩阵的方法

import numpy as npdef array_test():    print "The version is:", np.version.version,"\n"    a = np.array([1,2,3])    print "a is:",a    print "type(a) is:",type(a),"\n"    b = np.array([[1,2],[3,4]])    print "b is:"    print b    print "type(b) is:",type(b),"\n"    c = np.array([1,2,3],dtype = float)    print "c is:",carray_test()

代码运行结果:

The version is: 1.8.0 a is: [1 2 3]type(a) is: <type 'numpy.ndarray'> b is:[[1 2] [3 4]]type(b) is: <type 'numpy.ndarray'> c is: [ 1.  2.  3.]

我的numpy版本是1.8.0。a是一个一维数组,b是一个二维数组,而c,则用dtype参数指定了数据类型为float。

再尝试用其他的方式生成数组对象

2.用其他方法构造矩阵

def other_pro_method():    print np.linspace(1,2,11)    print    print np.arange(15).reshape(5,3)array_test()

代码运行结果

[ 1.   1.1  1.2  1.3  1.4  1.5  1.6  1.7  1.8  1.9  2. ][[ 0  1  2] [ 3  4  5] [ 6  7  8] [ 9 10 11] [12 13 14]]

怎么样同学们,是不是好熟悉的样子,是不是跟matlab里很像
再来几个特殊矩阵

3.构造特殊矩阵

def special_matrix():    a = np.zeros((2,2))    print "type a is:",type(a)    print a,"\n"    b = np.ones((2,2))    print "type b is:",type(b)    print b,"\n"    c = np.eye(2,dtype=int)    print "type c is:",type(c)    print c,"\n"special_matrix()

运行结果如下:

type a is: <type 'numpy.ndarray'>[[ 0.  0.] [ 0.  0.]] type b is: <type 'numpy.ndarray'>[[ 1.  1.] [ 1.  1.]] type c is: <type 'numpy.ndarray'>[[1 0] [0 1]] 

如果我没有记错的话,matlab里也有这几个方法构造特殊矩阵。顾名思义,zeros(m,n)构造的是全0矩阵,ones(m,n)构造的是全1矩阵,而eys(n)构造的是单位阵。。。

4.矩阵求行列式,求逆,求特征值与特征向量

代码如下

import numpy as npdef get_some_trait():    mat = np.array([[1,2],[3,4]])    det = np.linalg.det(mat)    print "the det of mat is:",det,"\n"    inv_mat = np.linalg.inv(mat)    print "the inv_mat is:"    print inv_mat,"\n"    eig1,eig2 = np.linalg.eig(mat)    print "the eig of mat is:",eig1,"\n"    print "the feature vector of mat is:"    print eig2get_some_trait()

运行结果如下

the det of mat is: -2.0 the inv_mat is:[[-2.   1. ] [ 1.5 -0.5]] the eig of mat is: [-0.37228132  5.37228132] the feature vector of mat is:[[-0.82456484 -0.41597356] [ 0.56576746 -0.90937671]]

需要注意的是,eig方法返回的是一个元祖,包含有特征值与特征向量。所以童鞋们在使用的时候稍微注意即可。

0 0