import numpy as np
vector = np.arange(12)
vector.shape
vector.dtype
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
vector * 2
vector + vector_again
You can make 2 or more dimensions:
arr2d = vector.reshape((4, 3))
arr2d
a_transpose_a = arr2d.T.dot(arr2d)
a_transpose_a
np.linalg.inv(a_transpose_a)
Get help with:
np.lookfor('correlation')
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})
import glob
glob.glob('*.mat')
mat_contents = scipy.io.loadmat('for_matlab.mat')
mat_contents
random_arr = np.random.normal(size=(128, 128))
%pylab inline
import matplotlib.pyplot as plt
plt.imshow(random_arr)
smoothed_arr = scipy.ndimage.gaussian_filter(random_arr, 8)
plt.imshow(smoothed_arr)
def func(x):
return x ** 2 - 5 * x + 4
x = np.linspace(-3, 7)
plt.plot(x, func(x))
scipy.optimize.fmin_powell(func, 0)
rv = scipy.stats.norm(0, 1)
x = np.linspace(-3, 3)
pdf = rv.pdf(x)
pdf
plt.plot(pdf)
Get help with:
scipy.lookfor('convolution')
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:')
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)
%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)
%timeit sum_to(10000)
%timeit cython_sum_to(10000)
import sympy
X = sympy.Symbol('X')
my_formula = X**2 + X / 2 + sympy.sin(X)
my_formula
my_formula.diff()
my_formula.integrate()