Knjižnica NumPy je rezultat potreb po numeričnem računanju v Pytonu in vsebuje večino znanstvenih pomožnih knjižnic kot so
- fft: Fast Fourrier Transform
- random: tvorjenje naključnih števil
- linalg: linearna algebra (Lapack, ATLAS ali MKL v ozadju + BLAS)
- distutils: paket za pomoč pri distribuciji programov Python, ki uporabljajo numpy
- f2py: paket za vključevanje fortranske kode v Python/numpy
NumPy vsebuje dva osnovna objekta na katerih se izvajajo algoritmi:
- ndarray: Večdimenzijska polja
- ufunc: Univerzalve funkcije, ki delujejo na poljih. Običajno se te funkcije aplicirajo na vsak element v polju.
ndarray
Vsebuje ima naslednja dva argumenta pri kreiranju
- shape: Tuple that gives the number of points in each dimension
- dtype: Data type (int32, int64, float32, complex32,. . . )
Funkcije za tvorjenje ndarray so lahko
- Empty, zeros and ones
- zeros(shape[, dtype, order]): Returns an array filled with zeros
- ones(shape[, dtype, order]): Returns an array filled with ones
- empty(shape[, dtype, order]): Returns an allocated but empty array
- something_like(a): Returns an array like a and filled with zeros, ones or not filled according to “something”
- From existing data
- array(object): Returns an array from a list or an existing array
- loadtxt(fname[, dtype, comments, delimiter, . . . ]): Returns an array from a text file
- fromstring(string[, dtype, count, sep]): Returns an array from a Python string
- Numerical ranges
- linspace(start, stop[, num, endpoint, retstep]): Returns an array of evenly spaced numbers over a specified interval
- arange([start], stop[, step, dtype]): like linspace but with the definition of a step instead of a number of points
- logspace(start, stop[, num, endpoint, base]): Returns an array of numbers spaced evenly on a log scale
- meshgrid(x, y): Returns coordinate matrices from two coordinate vectors
- Matrices
- mat(data[, dtype]): Interprets the input as a matrix
- diag(v[, k]): Extracts a diagonal or constructs a diagonal array
- tri(N[, M, k, dtype]): An array with ones at and below the given diagonal and zeros elsewhere
- vander(x[, N]): Generates a Van der Monde matrix
Primeri uporabe NumPy
Kreiranje enk in ničel
>>> import numpy as np
>>> a = np.zeros(5)
>>> print ( a )
[ 0. 0. 0. 0. 0 . ]
>>> b = np.zeros ( ( 2 , 5 ) , dtype=int )
>>> print ( b )
[ [ 0 0 0 0 0]
[0 0 0 0 0 ] ]
>>> c = np.ones_like ( b )
>>> print ( c )
[ [ 1 1 1 1 1]
[1 1 1 1 1 ] ]
>>> print ( a.dtype )
float64
>>> print ( b.dtype )
int32
>>> print ( a.shape )
( 5 , )
>>> print ( b.shape )
(2 ,5)
Kreiranje iz obstoječih podatkov
>>> l =[0,1,2,3,4]
>>> print ( l )
[0 , 1 , 2 , 3 , 4]
>>> print ( type ( l ) )
>>> a = np.array ( l )
>>> print ( a )
[0 1 2 3 4]
>>> print ( type ( a ) )
>>> s = ” 1 2 3 4 5 ”
>>> b = np.fromstring (s , dtype=int , sep= ’ ’ )
>>> print ( b )
[1 2 3 4 5]
>>> print ( type ( b ) )
>>> print ( type ( s ) )
Kreiranje z numeričnimi območji
>>> a = np.linspace (0.0 ,1.0 ,10)
>>> print ( a )
[ 0. 0.11111111 0.22222222 0.33333333 0.44444444
0.55555556 0.66666667 0.77777778 0.88888889 1. ]
>>> a , dx = np.linspace (0.0 ,1.0 ,10 , endpoint=False , retstep=True )
>>> print ( a )
[ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0 . 9 ]
>>> print ( dx )
0.1
>>> x = np.logspace (-1 ,0 ,5) # start = 10∗∗−1 stop =10ˆ0
>>> print ( x )
[ 0.1 0.17782794 0.31622777 0.56234133 1. ]
>>> y = np.logspace (0 ,6 ,5 , base =2.0) # start = 2∗∗0 stop =2ˆ6
>>> print ( y )
[ 1. 2.82842712 8. 22.627417 64. ]
Tvorjenje matrik
>>> m = np.diag ( np.arange ( 6 ) )
>>> print (m)
[ [ 0 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 2 0 0 0]
[0 0 0 3 0 0]
[0 0 0 0 4 0]
[0 0 0 0 0 5 ] ]
>>> m = np.tri (6 , k=-2)
>>> print (m)
[ [ 0. 0. 0. 0. 0. 0. ]
[ 0. 0. 0. 0. 0. 0. ]
[ 1. 0. 0. 0. 0. 0. ]
[ 1. 1. 0. 0. 0. 0. ]
[ 1. 1. 1. 0. 0. 0. ]
[ 1. 1. 1. 1. 0. 0. ] ]
>>> print type (m)
>>> matrix = np.mat (m)
>>> print type ( matrix )
Manipulacija z obliko ndarray
- reshape(shape[, order]): Returns a view of the array with a new shape
- resize(new shape[, refcheck]): Changes shape and size of array in-place
- transpose(*axes): Returns a view of the array with axes transposed
- swapaxes(axis1, axis2): Returns a view of the array with axis1 and axis2 interchanged
- flatten([order]): Returns a copy of the array collapsed into one dimension
>>> a = np.arange (10)
>>> b=a.reshape ( ( 2, 5 ) )
>>> b
array ( [ [ 0 , 1 , 2 , 3 , 4] ,
[5 , 6 , 7 , 8 , 9 ] ] )
>>> b [ 0 , 0 ] = 10
>>> print ( b )
[ [ 1 0 , 1 , 2 , 3 , 4] ,
[ 5 , 6 , 7 , 8 , 9 ] ] )
>>> print ( a )
[10 1 2 3 4 5 6 7 8 9]
>>> b.resize ( ( 5, 2 ) )
>>> print ( b )
[ [ 1 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9 ] ]
>>> c = b.transpose ( )
>>> print ( c )
[ [ 1 0 2 4 6 8]
[ 1 3 5 7 9 ] ]
Indeksiranje polja
- Basic indexing (returns a view)
- x[start:stop:step]: Select a subarray from start to stop with an increment of step
- if start or stop are negative, they are interpreted as n +
- start or n + stop, with n being the number of elements
- if start is not given: default is 0
- if stop is not given: default is n (number of elements)
- if step is not given: default is 1
- Advanced indexing (returns a copy)
>>> x = np.arange (10)
>>> print ( x )
[0 1 2 3 4 5 6 7 8 9]
>>> print ( x [1:7:2] )
[1 3 5]
>>> print ( x [-2:10])
[8 9]
>>> print ( x [-3:3:-1])
[7 6 5 4]
>>> print ( x [5:] )
[5 6 7 8 9]
Napredno indeksiranje
>>> x=np.linspace (0, 1 ,10)
>>> print ( x<0.5)
[ True True True True True False False False False False ]
>>> print ( np.where ( x<0.5))
( array ( [ 0, 1, 2, 3, 4] ), )
>>> y=8∗np.ones_like ( x )
>>> y[np.where ( x<0.5)]=10
>>> print ( y )
[ 10. 10. 10. 10. 10. 8. 8. 8. 8. 8. ]
Globalne operacije z indeksi
- min([axis, out]): Returns the minimum
- ptp([axis, out]): Peak to peak (maximum - minimum) value
- conj(): Complex-conjugate all elements
- sum([axis, dtype, out]): Returns the sum of the array elements
- prod([axis, dtype, out]): Returns the product of the array elements
- var([axis, dtype, out, ddof]): Returns the variance of the array elements
- std([axis, dtype, out, ddof]): Returns the standard deviation of the array elements
- all([axis, out]): Returns True if all elements evaluate to True
- any([axis, out]): Returns True if any of the elements of a evaluate to True
>>> x = np.arange (10)
>>> print ( x )
[0 1 2 3 4 5 6 7 8 9]
>>> print ( x.min ( ) )
0
>>> print ( x.ptp ( ) )
9
>>> print ( x.mean ( ) )
4.5
>>> print ( x.var ( ) )
8.25
>>> print ( x.std ( ) )
2.87228132327
>>> print ( x.sum ( ) )
45
Univerzalne funkcije
- Functions that are (re)defined to work on numpy arrays
- Mathematical functions (square root, exponential... )
- Trigonometric functions (sin, arccos, ... )
- Bit-twiddling functions (bitwise and, ... )
- Comparison and boolean functions (logical and, greater, ... )
>>> x=np.linspace (0 ,1 ,10)
>>> print ( x∗∗3)
[ 0. 0.00137174 0.01097394 0.03703704 0.0877915
0.17146776 0.2962963 0.47050754 0.70233196 1. ]
>>> print (2∗x / ( x +1))
[ 0. 0.2 0.36363636 0.5 0.61538462
0.71428571 0.8 0.875 0.94117647 1. ]
>>> print ( np.sin ( x∗np.pi ) )
[ 0.00000000e+00 3.42020143e−01 6.42787610e−01 8.66025404e−01
9.84807753e−01 9.84807753e−01 8.66025404e−01 6.42787610e−01
3.42020143e−01 1.22460635e−16]
>>> print ( np.sqrt( x ) )
[ 0. 0.33333333 0.47140452 0.57735027 0.66666667
0.74535599 0.81649658 0.8819171 0.94280904 1. ]
Naprednejše funkcije: Integracija, odvajanje in linearna algebra
- trapz(y[, x, dx, axis]): Integrates along the given axis using the composite trapezoidal rule
- gradient(f, *varargs): Returns the gradient of an N-dimensional array
- diff(a[, n, axis]): Calculates the n-th order discrete difference along given axis
- dot(a, b): Dot product of two arrays
- inner(a, b): Inner product of two arrays
- cholesky(a): Cholesky decomposition
- eig(a): Computes the eigenvalues and right eigenvectors of a square array
- eigvals(a): Computes the eigenvalues of a general matrix
- det(a): Computes the determinant of an array
- solve(a, b): Solves a linear matrix equation, or system of linear scalar equations
- inv(a): Computes the (multiplicative) inverse of a matrix
Primer trapezne integracije napisane kot funkcija integrate.
import numpy as np
def f1(x):
return 1 + x**2
def f2(x):
return np.exp(-x**2)
def integrate(f, a, b, n):
x = a + np.arange(1, n) * (b - a)/n
result = 0.5 * ( f(a) + f(b) ) + np.sum(f(x))
return result * (b - a)/n
a = 0.0
b = 10.0
for n in range(4,10):
i1 = integrate(f1, a, b, n)
i2 = integrate(f2, a, b, n)
print "n=%d f1=%8.5f f2=%8.5f" % (n, i1, i2)
Povzetek
Poleg predstavljenih funkcij obstajajo še druga področja za analizo, FFT, sortiranje in iskanje, nakjučna števila, polinome, finanče funkcije, …
Numpy lahko v povezavi z drugimi knjižnicami (MPI4Py, scipy, matplotlib, ...) učinkovito nadomesti matlab. Najbolje pa se numpy priučino ma konkretnih problemih.