Python Numpy 筆記

此次機器學習的做業能夠用第三方庫了,果斷拋棄 MATLAB 改用 Python
可是操做數組的 Numpy 以前一直沒用過,今天先看看官方教程入個門html

The Basics

Numpy 中主要的對象是同類元素組成的多維數組,能夠經過一個正整數的元組進行索引。
在 Numpy 中維度(dimension)稱爲軸(axes),軸的數量稱爲秩rankpython

[[1., 0., 0.], [0., 1., 2.]] :rank=2
the first dimension has a length of 2, the second dimension has a length of 3數組

Numpy 的數組類叫作 ndarray or array
attributes:dom

  1. ndarray.ndim
  2. ndarray.shape
  3. ndarray.size
  4. ndarray.dtypendarray.dtype.name 返回字符串表示的類型名稱
  5. ndarray.data

Example:機器學習

>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>> type(a)
<type 'numpy.ndarray'>
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
<type 'numpy.ndarray'>

Array Creation

  1. create from list/tupe:學習

    • a = np.array([1, 2, 3])
    • b = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)
  2. create with shape:ui

    • zeros: np.zeros((3, 4))
    • ones: np.ones((2, 4, 3))
    • empty: np.empty((2, 3)) uninitialized
  3. create sequences of number (similar to range()):spa

    • arange: np.arange(10, 30, 5) syntax is the same as range() but returns arraycode

      接受浮點數,可是因爲精度影響,輸出的元素個數不肯定。這種狀況應使用 linspace
    • linspace: np.linspace(0, 2, 9) return an array contains 9 numbers from 0 to 2

Basic Operations

  1. 算數操做對於 array 是按元素運算的,並返回一個新的 array
>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False], dtype=bool)
>>> A = np.array( [[1,1],
...             [0,1]] )
>>> B = np.array( [[2,0],
...             [3,4]] )
>>> A*B                         # elementwise product
array([[2, 0],
       [0, 4]])

# 兩種矩陣乘法
>>> A.dot(B)
array([[5, 4],
       [3, 4]])
>>> np.dot(A, B)
array([[5, 4],
       [3, 4]])
  1. 一元運算 (sum, min, max)
>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021,  0.34556073,  0.39676747],
       [ 0.53881673,  0.41919451,  0.6852195 ]])
>>> a.sum()
2.5718191614547998
>>> a.min()
0.1862602113776709
>>> a.max()
0.6852195003967595
>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>
>>> b.sum(axis=0)                            # sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1)                            # min of each row
array([0, 4, 8])

Indexing, slicing and iterating

相關文章
相關標籤/搜索