# gotta import
import numpy as np
# defining a new array:
X = np.array([[1,2,3],[4,5,6]]) # will make an array with X.shape = (2,3)
print("nice array: \n", X, "\nThe shape was", X.shape, "\n")
X = np.zeros([3,3]) # the shape is given as a list
print("zeros:\n", X)
print("")
# accessing and setting
X[0,1] = 999
print("after setting X[0,1] to 999:")
print(X)
# make a 1x9 array into a 3x3 array
X = np.array(range(9))
np.reshape(X, (3,3))
# or:
X.reshape((3,3))
np.linspace(1,2,11) # 11 points between 0 and and 1 inclusive
Of course we could have done this with list comprehensions ([1 + 0.1*x for x in range(11)]
) but anything you do in numpy will be faster.
X = np.array(range(9))
print(X)
print(X + 10)
np.array([1,2,3]) + np.array([4,5,6])
Numpy figures out how to use the function with the array you gave.
But maybe you want to control it youself:
arr = np.array(range(9)).reshape(3,3) + 1
arr
np.sum(arr)
np.apply_along_axis(np.sum, 0, arr)
np.apply_along_axis(np.sum, 1, arr)
There is also: np.apply_over_axis
This is very very similar to Matlab's plotting functions.
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from math import pi
import math
xs = np.linspace(0, 2*pi, 200)
ys = np.cos(xs)
# alternatively, we could have done: ys = np.vectorize(math.cos)(xs)
zs = np.sin(xs)
plt.plot(xs, ys)
plt.plot(xs, zs)
X = np.genfromtxt("faces.txt", delimiter=None) # load the face dataset
X.shape
There are 4916 rows, 576 columns. Each row is actually a 24x24 image.
im = X[0].reshape(24,24)
plt.imshow(im, cmap="gray", interpolation = "none")
im = im.transpose() # it was sideways, so let's transpose
# we could also have said: im.T
plt.imshow(im, cmap="gray", interpolation = "none")
# Let's make our lives easier with a helper function
def showimg(imvec):
plt.figure(figsize=(2,2))
img = np.reshape(imvec,(24,24)) # convert vectorized data point t
plt.imshow( img.T , cmap="gray", interpolation="none")
startface = 50
for i in range(startface, startface+10):
showimg(X[i,:])
avg_face = np.apply_along_axis(np.mean, 0, X) # axis 0 is the first axis
avg_face_image = np.reshape(avg_face, (24, 24))
plt.imshow(avg_face_image.transpose(), cmap="gray", interpolation="none")
plt.imshow(avg_face_image.transpose(), cmap="gray")