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$
新聞熱點
疑難解答