NumPy是python下的计算库,被非常广泛地应用,尤其是近来的深度学习的推广。在这篇文章中,将会介绍使用numpy进行一些最为基础的计算。
NumPy vs SciPy
NumPy和SciPy都可以进行运算,主要区别如下
最近比较热门的深度学习,比如在神经网络的算法,多维数组的使用是一个极为重要的场景。如果你熟悉tensorflow中的tensor的概念,你会非常清晰numpy的作用。所以熟悉Numpy可以说是使用python进行深度学习入门的一个基础知识。
安装
liumiaocn:tmp liumiao$ pip install numpyCollecting numpy Downloading https://files.pythonhosted.org/packages/b6/5e/4b2c794fb57a42e285d6e0fae0e9163773c5a6a6a7e1794967fc5d2168f2/numpy-1.14.5-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.7MB) 100% |████████████████████████████████| 4.7MB 284kB/s Installing collected packages: numpySuccessfully installed numpy-1.14.5liumiaocn:tmp liumiao$
确认
liumiaocn:tmp liumiao$ pip show numpyName: numpyVersion: 1.14.5Summary: NumPy: array processing for numbers, strings, records, and objects.Home-page: http://www.numpy.orgAuthor: Travis E. Oliphant et al.Author-email: NoneLicense: BSDLocation: /usr/local/lib/python2.7/site-packagesRequires: Required-by: liumiaocn:tmp liumiao$
使用
使用numpy的数组
使用如下例子简单来理解一下numpy的数组的使用:
liumiaocn:tmp liumiao$ cat np-1.py #!/usr/local/bin/pythonimport numpy as nparr = [1,2,3,4]print("array arr: ", arr)np_arr = np.array(arr)print("numpy array: ", np_arr)print("doulbe calc : ", 2 * np_arr)print("ndim: ", np_arr.ndim)liumiaocn:tmp liumiao$ python np-1.py ('array arr: ', [1, 2, 3, 4])('numpy array: ', array([1, 2, 3, 4]))('doulbe calc : ', array([2, 4, 6, 8]))('ndim: ', 1)liumiaocn:tmp liumiao$
多维数组&ndim/shape
ndim在numpy中指的是数组的维度,如果是2维值则为2,在下面的例子中构造一个步进为2的等差数列,然后将其进行维度的转换同时输出数组的ndim和shape的值以辅助对于ndim和shape含义的理解。
liumiaocn:tmp liumiao$ cat np-2.py #!/usr/local/bin/pythonimport numpy as nparithmetic = np.arange(0,16,2)print(arithmetic)print("ndim: ",arithmetic.ndim," shape:", arithmetic.shape)#resize to 2*4 2-dim arrayarithmetic.resize(2,4)print(arithmetic)print("ndim: ",arithmetic.ndim," shape:", arithmetic.shape)#resize to 2*2*2 3-dim arrayarray = arithmetic.resize(2,2,2)print(arithmetic)print("ndim: ",arithmetic.ndim," shape:", arithmetic.shape)liumiaocn:tmp liumiao$ python np-2.py [ 0 2 4 6 8 10 12 14]('ndim: ', 1, ' shape:', (8,))[[ 0 2 4 6] [ 8 10 12 14]]('ndim: ', 2, ' shape:', (2, 4))[[[ 0 2] [ 4 6]] [[ 8 10] [12 14]]]('ndim: ', 3, ' shape:', (2, 2, 2))liumiaocn:tmp liumiao$
新闻热点
疑难解答