import numpy as np
vector = np.arange(12)
vector.shape
(12,)
vector.dtype
dtype('int64')
Another way of making the same array is:
vector_again = np.array([0,1,2,3,4,5,6,7,8,9,10,11]) # array from a list
Addition and so on work on elements, rather like the MATLAB dot syntax for element-wise operations:
vector + 1
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
vector * 2
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22])
vector + vector_again
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22])
You can make 2 or more dimensions:
arr2d = vector.reshape((4, 3))
arr2d
array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]])
a_transpose_a = arr2d.T.dot(arr2d)
a_transpose_a
array([[126, 144, 162], [144, 166, 188], [162, 188, 214]])
np.linalg.inv(a_transpose_a)
array([[ -1.18515780e+13, 2.37031559e+13, -1.18515780e+13], [ 2.37031559e+13, -4.74063119e+13, 2.37031559e+13], [ -1.18515780e+13, 2.37031559e+13, -1.18515780e+13]])
Get help with:
np.lookfor('correlation')
Search results for 'correlation' -------------------------------- numpy.corrcoef Return correlation coefficients. numpy.correlate Cross-correlation of two 1-dimensional sequences. numpy.ma.corrcoef Return correlation coefficients of the input array. numpy.cov Estimate a covariance matrix, given data.
Scipy is a large library. Check out what is in there by doing:
import scipy
and then doing tab completion. In fact, there is so much in there, that when you import scipy
, it does not load all its submodules, as this would take too long. So, you have to import them individually before using them.
import scipy.io
import scipy.ndimage
import scipy.optimize
import scipy.stats
scipy.io.savemat('for_matlab.mat', {'arr2d': arr2d, 'vector': vector})
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/io/matlab/mio.py:266: FutureWarning: Using oned_as default value ('column') This will change to 'row' in future versions oned_as=oned_as)
import glob
glob.glob('*.mat')
['for_matlab.mat']
mat_contents = scipy.io.loadmat('for_matlab.mat')
mat_contents
{'__globals__': [], '__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Fri Feb 22 09:36:00 2013', '__version__': '1.0', 'arr2d': array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]), 'vector': array([[ 0], [ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], [11]])}
random_arr = np.random.normal(size=(128, 128))
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
import matplotlib.pyplot as plt
plt.imshow(random_arr)
<matplotlib.image.AxesImage at 0x106f67990>
smoothed_arr = scipy.ndimage.gaussian_filter(random_arr, 8)
plt.imshow(smoothed_arr)
<matplotlib.image.AxesImage at 0x1071dd250>
def func(x):
return x ** 2 - 5 * x + 4
x = np.linspace(-3, 7)
plt.plot(x, func(x))
[<matplotlib.lines.Line2D at 0x1075d0750>]
scipy.optimize.fmin_powell(func, 0)
Optimization terminated successfully. Current function value: -2.250000 Iterations: 2 Function evaluations: 39
array(2.5000000105713474)
rv = scipy.stats.norm(0, 1)
x = np.linspace(-3, 3)
pdf = rv.pdf(x)
pdf
array([ 0.00443185, 0.00635135, 0.00896675, 0.01247075, 0.01708592, 0.02306069, 0.03066159, 0.04016108, 0.05182083, 0.0658706 , 0.08248352, 0.10174921, 0.12364689, 0.1480211 , 0.17456307, 0.20280069, 0.2320998 , 0.26167871, 0.29063661, 0.31799518, 0.34275126, 0.36393672, 0.38068082, 0.39226937, 0.39819528, 0.39819528, 0.39226937, 0.38068082, 0.36393672, 0.34275126, 0.31799518, 0.29063661, 0.26167871, 0.2320998 , 0.20280069, 0.17456307, 0.1480211 , 0.12364689, 0.10174921, 0.08248352, 0.0658706 , 0.05182083, 0.04016108, 0.03066159, 0.02306069, 0.01708592, 0.01247075, 0.00896675, 0.00635135, 0.00443185])
plt.plot(pdf)
[<matplotlib.lines.Line2D at 0x107846f90>]
Get help with:
scipy.lookfor('convolution')
Search results for 'convolution' -------------------------------- numpy.convolve Returns the discrete, linear convolution of two one-dimensional sequences. numpy.bartlett Return the Bartlett window. numpy.correlate Cross-correlation of two 1-dimensional sequences.
You've already seen matplotlib in action above, displaying images and plots. Here a little more.
x = np.linspace(-np.pi, np.pi)
y = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y)
plt.plot(x, y2, 'g:')
[<matplotlib.lines.Line2D at 0x10784f650>]
Cython allows you to write code that can make use of C compilation speed from within Python
def sum_to(n): # A python function
result = 0
for val in range(1, n):
result += val
return result
sum_to(100)
4950
%load_ext cythonmagic
%%cython
def cython_sum_to(int n): # A Cython function
cdef int result = 0 # Tell Cython that result is a C int
cdef int val # ditto val
for val in range(1, n): # Now this loop gets compiled to C
result += val
return result
cython_sum_to(100)
4950
%timeit sum_to(10000)
1000 loops, best of 3: 1.1 ms per loop
%timeit cython_sum_to(10000)
100000 loops, best of 3: 8.7 us per loop
import sympy
X = sympy.Symbol('X')
my_formula = X**2 + X / 2 + sympy.sin(X)
my_formula
X**2 + X/2 + sin(X)
my_formula.diff()
2*X + cos(X) + 1/2
my_formula.integrate()
X**3/3 + X**2/4 - cos(X)