Skip to content

Commit 0601277

Browse files
committed
add numpy exercises
1 parent df32fc5 commit 0601277

File tree

9 files changed

+343
-0
lines changed

9 files changed

+343
-0
lines changed

Diff for: numpy_class/exercises/ex1.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import matplotlib.pyplot as plt
12+
13+
A = np.array([
14+
[0.3, 0.6, 0.1],
15+
[0.5, 0.2, 0.3],
16+
[0.4, 0.1, 0.5]])
17+
18+
v = np.ones(3) / 3
19+
20+
num_iters = 25
21+
distances = np.zeros(num_iters)
22+
for i in range(num_iters):
23+
v2 = v.dot(A)
24+
d = np.linalg.norm(v2 - v)
25+
distances[i] = d
26+
v = v2
27+
28+
plt.plot(distances)
29+
plt.show()

Diff for: numpy_class/exercises/ex2.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import matplotlib.pyplot as plt
12+
13+
def sampleY(n=1000):
14+
# draw n samples from uniform dist.
15+
X = np.random.random(n)
16+
Y = X.sum()
17+
return Y
18+
19+
20+
# now draw N Y's
21+
N = 1000
22+
Y_samples = np.zeros(N)
23+
for i in range(N):
24+
Y_samples[i] = sampleY()
25+
26+
27+
# now plot the Y_samples
28+
plt.hist(Y_samples, bins=20)
29+
plt.show()

Diff for: numpy_class/exercises/ex3.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import pandas as pd
12+
import matplotlib.pyplot as plt
13+
14+
15+
# load in the data
16+
df = pd.read_csv('../../large_files/train.csv')
17+
data = df.values
18+
X = data[:, 1:] # images
19+
Y = data[:, 0] # labels
20+
21+
# loop through each label
22+
for k in range(10):
23+
Xk = X[Y == k]
24+
25+
# mean image
26+
Mk = Xk.mean(axis=0)
27+
28+
# reshape into an image
29+
im = Mk.reshape(28, 28)
30+
31+
# plot the image
32+
plt.imshow(im, cmap='gray')
33+
plt.title("Label: %s" % k)
34+
plt.show()

Diff for: numpy_class/exercises/ex4.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import pandas as pd
12+
import matplotlib.pyplot as plt
13+
14+
15+
# load in the data
16+
df = pd.read_csv('../../large_files/train.csv')
17+
data = df.values
18+
19+
# shuffle the images
20+
np.random.shuffle(data)
21+
22+
X = data[:, 1:] # images
23+
Y = data[:, 0] # labels
24+
25+
26+
# define rotate functions
27+
def rotate1(im):
28+
return np.rot90(im, 3)
29+
30+
def rotate2(im):
31+
H, W = im.shape
32+
im2 = np.zeros((W, H))
33+
for i in range(H):
34+
for j in range(W):
35+
im2[j,H - i - 1] = im[i,j]
36+
return im2
37+
38+
39+
for i in range(X.shape[0]):
40+
# get the image
41+
im = X[i].reshape(28, 28)
42+
43+
# flip the image
44+
# im = rotate1(im)
45+
im = rotate2(im)
46+
47+
# plot the image
48+
plt.imshow(im, cmap='gray')
49+
plt.title("Label: %s" % Y[i])
50+
plt.show()
51+
52+
ans = input("Continue? [Y/n]: ")
53+
if ans and ans[0].lower() == 'n':
54+
break

Diff for: numpy_class/exercises/ex5.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import matplotlib.pyplot as plt
12+
13+
14+
15+
def is_symmetric1(A):
16+
return np.all(A == A.T)
17+
18+
19+
def is_symmetric2(A):
20+
rows, cols = A.shape
21+
if rows != cols:
22+
return False
23+
24+
for i in range(rows):
25+
for j in range(cols):
26+
if A[i,j] != A[j,i]:
27+
return False
28+
29+
return True
30+
31+
32+
def check(A, b):
33+
print("Testing:", A)
34+
assert(is_symmetric1(A) == b)
35+
assert(is_symmetric2(A) == b)
36+
37+
38+
# test the functions
39+
A = np.zeros((3, 3))
40+
check(A, True)
41+
42+
A = np.eye(3)
43+
check(A, True)
44+
45+
A = np.random.randn(3, 2)
46+
A = A.dot(A.T)
47+
check(A, True)
48+
49+
A = np.array([[1, 2, 3], [2, 4, 5], [3, 5, 6]])
50+
check(A, True)
51+
52+
A = np.random.randn(3, 2)
53+
check(A, False)
54+
55+
A = np.random.randn(3, 3)
56+
check(A, False)
57+
58+
A = np.arange(9).reshape(3, 3)
59+
check(A, False)
60+

Diff for: numpy_class/exercises/ex6.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import matplotlib.pyplot as plt
12+
13+
14+
# generate unlabeled data
15+
N = 2000
16+
X = np.random.random((N, 2))*2 - 1
17+
18+
# generate labels
19+
Y = np.zeros(N)
20+
Y[(X[:,0] < 0) & (X[:,1] > 0)] = 1
21+
Y[(X[:,0] > 0) & (X[:,1] < 0)] = 1
22+
23+
# plot it
24+
plt.scatter(X[:,0], X[:,1], c=Y)
25+
plt.show()

Diff for: numpy_class/exercises/ex7.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import matplotlib.pyplot as plt
12+
13+
def get_donut():
14+
N = 2000
15+
R_inner = 5
16+
R_outer = 10
17+
18+
# distance from origin is radius + random normal
19+
# angle theta is uniformly distributed between (0, 2pi)
20+
R1 = np.random.randn(N//2) + R_inner
21+
theta = 2*np.pi*np.random.random(N//2)
22+
X_inner = np.concatenate([[R1 * np.cos(theta)], [R1 * np.sin(theta)]]).T
23+
24+
R2 = np.random.randn(N//2) + R_outer
25+
theta = 2*np.pi*np.random.random(N//2)
26+
X_outer = np.concatenate([[R2 * np.cos(theta)], [R2 * np.sin(theta)]]).T
27+
28+
X = np.concatenate([ X_inner, X_outer ])
29+
Y = np.array([0]*(N//2) + [1]*(N//2))
30+
return X, Y
31+
32+
X, Y = get_donut()
33+
plt.scatter(X[:,0], X[:,1], c=Y)
34+
plt.show()

Diff for: numpy_class/exercises/ex8.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import matplotlib.pyplot as plt
12+
13+
def get_spiral():
14+
# Idea: radius -> low...high
15+
# (don't start at 0, otherwise points will be "mushed" at origin)
16+
# angle = low...high proportional to radius
17+
# [0, 2pi/6, 4pi/6, ..., 10pi/6] --> [pi/2, pi/3 + pi/2, ..., ]
18+
# x = rcos(theta), y = rsin(theta) as usual
19+
20+
radius = np.linspace(1, 10, 100)
21+
thetas = np.empty((6, 100))
22+
for i in range(6):
23+
start_angle = np.pi*i / 3.0
24+
end_angle = start_angle + np.pi / 2
25+
points = np.linspace(start_angle, end_angle, 100)
26+
thetas[i] = points
27+
28+
# convert into cartesian coordinates
29+
x1 = np.empty((6, 100))
30+
x2 = np.empty((6, 100))
31+
for i in range(6):
32+
x1[i] = radius * np.cos(thetas[i])
33+
x2[i] = radius * np.sin(thetas[i])
34+
35+
# inputs
36+
X = np.empty((600, 2))
37+
X[:,0] = x1.flatten()
38+
X[:,1] = x2.flatten()
39+
40+
# add noise
41+
X += np.random.randn(600, 2)*0.5
42+
43+
# targets
44+
Y = np.array([0]*100 + [1]*100 + [0]*100 + [1]*100 + [0]*100 + [1]*100)
45+
return X, Y
46+
47+
48+
X, Y = get_spiral()
49+
plt.scatter(X[:,0], X[:,1], c=Y)
50+
plt.show()

Diff for: numpy_class/exercises/ex9.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# https://deeplearningcourses.com/c/deep-learning-prerequisites-the-numpy-stack-in-python
2+
# https://www.udemy.com/deep-learning-prerequisites-the-numpy-stack-in-python
3+
4+
from __future__ import print_function, division
5+
from future.utils import iteritems
6+
from builtins import range, input
7+
# Note: you may need to update your version of future
8+
# sudo pip install -U future
9+
10+
import numpy as np
11+
import pandas as pd
12+
import matplotlib.pyplot as plt
13+
14+
15+
from ex8 import get_spiral
16+
17+
# get the data
18+
X, Y = get_spiral()
19+
20+
# combine the data into one array
21+
# data to be concatenated must have same # of dimensions
22+
# e.g. N x D and N x 1
23+
# not N x D and N
24+
data = np.concatenate((X, np.expand_dims(Y, 1)), axis=1)
25+
26+
df = pd.DataFrame(data)
27+
df.columns = ['x1', 'x2', 'y']
28+
df.to_csv('mydata.csv', index=False)

0 commit comments

Comments
 (0)