Skip to content

Commit 0810c5f

Browse files
added week4 phase3 summer
1 parent 6c50ff2 commit 0810c5f

7 files changed

Lines changed: 1139 additions & 0 deletions

File tree

Binary file not shown.
Binary file not shown.
53.7 KB
Loading

Phase 3 - 2020 (Summer)/Week 4(Apr 19 - Apr 25)/Exercise3/exercise3.ipynb

Lines changed: 923 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import sys
2+
import numpy as np
3+
from matplotlib import pyplot
4+
5+
sys.path.append('..')
6+
from submission import SubmissionBase
7+
8+
9+
def displayData(X, example_width=None, figsize=(10, 10)):
10+
"""
11+
Displays 2D data stored in X in a nice grid.
12+
"""
13+
# Compute rows, cols
14+
if X.ndim == 2:
15+
m, n = X.shape
16+
elif X.ndim == 1:
17+
n = X.size
18+
m = 1
19+
X = X[None] # Promote to a 2 dimensional array
20+
else:
21+
raise IndexError('Input X should be 1 or 2 dimensional.')
22+
23+
example_width = example_width or int(np.round(np.sqrt(n)))
24+
example_height = n / example_width
25+
26+
# Compute number of items to display
27+
display_rows = int(np.floor(np.sqrt(m)))
28+
display_cols = int(np.ceil(m / display_rows))
29+
30+
fig, ax_array = pyplot.subplots(display_rows, display_cols, figsize=figsize)
31+
fig.subplots_adjust(wspace=0.025, hspace=0.025)
32+
33+
ax_array = [ax_array] if m == 1 else ax_array.ravel()
34+
35+
for i, ax in enumerate(ax_array):
36+
ax.imshow(X[i].reshape(example_width, example_width, order='F'),
37+
cmap='Greys', extent=[0, 1, 0, 1])
38+
ax.axis('off')
39+
40+
41+
def sigmoid(z):
42+
"""
43+
Computes the sigmoid of z.
44+
"""
45+
return 1.0 / (1.0 + np.exp(-z))
46+
47+
48+
class Grader(SubmissionBase):
49+
# Random Test Cases
50+
X = np.stack([np.ones(20),
51+
np.exp(1) * np.sin(np.arange(1, 21)),
52+
np.exp(0.5) * np.cos(np.arange(1, 21))], axis=1)
53+
54+
y = (np.sin(X[:, 0] + X[:, 1]) > 0).astype(float)
55+
56+
Xm = np.array([[-1, -1],
57+
[-1, -2],
58+
[-2, -1],
59+
[-2, -2],
60+
[1, 1],
61+
[1, 2],
62+
[2, 1],
63+
[2, 2],
64+
[-1, 1],
65+
[-1, 2],
66+
[-2, 1],
67+
[-2, 2],
68+
[1, -1],
69+
[1, -2],
70+
[-2, -1],
71+
[-2, -2]])
72+
ym = np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
73+
74+
t1 = np.sin(np.reshape(np.arange(1, 25, 2), (4, 3), order='F'))
75+
t2 = np.cos(np.reshape(np.arange(1, 41, 2), (4, 5), order='F'))
76+
77+
def __init__(self):
78+
part_names = ['Regularized Logistic Regression',
79+
'One-vs-All Classifier Training',
80+
'One-vs-All Classifier Prediction',
81+
'Neural Network Prediction Function']
82+
83+
super().__init__('multi-class-classification-and-neural-networks', part_names)
84+
85+
def __iter__(self):
86+
for part_id in range(1, 5):
87+
try:
88+
func = self.functions[part_id]
89+
90+
# Each part has different expected arguments/different function
91+
if part_id == 1:
92+
res = func(np.array([0.25, 0.5, -0.5]), self.X, self.y, 0.1)
93+
res = np.hstack(res).tolist()
94+
elif part_id == 2:
95+
res = func(self.Xm, self.ym, 4, 0.1)
96+
elif part_id == 3:
97+
res = func(self.t1, self.Xm) + 1
98+
elif part_id == 4:
99+
res = func(self.t1, self.t2, self.Xm) + 1
100+
else:
101+
raise KeyError
102+
yield part_id, res
103+
except KeyError:
104+
yield part_id, 0
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
## To be done for next week
2+
3+
1. Complete All Video Lectures and Quizes of week4 of the [Coursera Course](https://www.coursera.org/learn/machine-learning).
4+
2. For python implementation of neural network you can take help from [here](https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6).
5+
3. Add your python(if you are doing by your own) or jupyter notebook files and create pull request.
6+
4. Each part of the assignment has equal weightage - total 100 points.
7+
5. Complete assignment in octave(for the sake of your certification, it is optional and does not consist of any point).
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from urllib.parse import urlencode
2+
from urllib.request import urlopen
3+
import pickle
4+
import json
5+
from collections import OrderedDict
6+
import numpy as np
7+
import os
8+
9+
10+
class SubmissionBase:
11+
12+
submit_url = 'https://www-origin.coursera.org/api/' \
13+
'onDemandProgrammingImmediateFormSubmissions.v1'
14+
save_file = 'token.pkl'
15+
16+
def __init__(self, assignment_slug, part_names):
17+
self.assignment_slug = assignment_slug
18+
self.part_names = part_names
19+
self.login = None
20+
self.token = None
21+
self.functions = OrderedDict()
22+
self.args = dict()
23+
24+
def grade(self):
25+
print('\nSubmitting Solutions | Programming Exercise %s\n' % self.assignment_slug)
26+
self.login_prompt()
27+
28+
# Evaluate the different parts of exercise
29+
parts = OrderedDict()
30+
for part_id, result in self:
31+
parts[str(part_id)] = {'output': sprintf('%0.5f ', result)}
32+
result, response = self.request(parts)
33+
response = json.loads(response.decode("utf-8"))
34+
35+
# if an error was returned, print it and stop
36+
if 'errorMessage' in response:
37+
print(response['errorMessage'])
38+
return
39+
40+
# Print the grading table
41+
print('%43s | %9s | %-s' % ('Part Name', 'Score', 'Feedback'))
42+
print('%43s | %9s | %-s' % ('---------', '-----', '--------'))
43+
for part in parts:
44+
part_feedback = response['partFeedbacks'][part]
45+
part_evaluation = response['partEvaluations'][part]
46+
score = '%d / %3d' % (part_evaluation['score'], part_evaluation['maxScore'])
47+
print('%43s | %9s | %-s' % (self.part_names[int(part) - 1], score, part_feedback))
48+
evaluation = response['evaluation']
49+
total_score = '%d / %d' % (evaluation['score'], evaluation['maxScore'])
50+
print(' --------------------------------')
51+
print('%43s | %9s | %-s\n' % (' ', total_score, ' '))
52+
53+
def login_prompt(self):
54+
if os.path.isfile(self.save_file):
55+
with open(self.save_file, 'rb') as f:
56+
login, token = pickle.load(f)
57+
reenter = input('Use token from last successful submission (%s)? (Y/n): ' % login)
58+
59+
if reenter == '' or reenter[0] == 'Y' or reenter[0] == 'y':
60+
self.login, self.token = login, token
61+
return
62+
else:
63+
os.remove(self.save_file)
64+
65+
self.login = input('Login (email address): ')
66+
self.token = input('Token: ')
67+
68+
# Save the entered credentials
69+
if not os.path.isfile(self.save_file):
70+
with open(self.save_file, 'wb') as f:
71+
pickle.dump((self.login, self.token), f)
72+
73+
def request(self, parts):
74+
params = {
75+
'assignmentSlug': self.assignment_slug,
76+
'secret': self.token,
77+
'parts': parts,
78+
'submitterEmail': self.login}
79+
80+
params = urlencode({'jsonBody': json.dumps(params)}).encode("utf-8")
81+
f = urlopen(self.submit_url, params)
82+
try:
83+
return 0, f.read()
84+
finally:
85+
f.close()
86+
87+
def __iter__(self):
88+
for part_id in self.functions:
89+
yield part_id
90+
91+
def __setitem__(self, key, value):
92+
self.functions[key] = value
93+
94+
95+
def sprintf(fmt, arg):
96+
""" Emulates (part of) Octave sprintf function. """
97+
if isinstance(arg, tuple):
98+
# for multiple return values, only use the first one
99+
arg = arg[0]
100+
101+
if isinstance(arg, (np.ndarray, list)):
102+
# concatenates all elements, column by column
103+
return ' '.join(fmt % e for e in np.asarray(arg).ravel('F'))
104+
else:
105+
return fmt % arg

0 commit comments

Comments
 (0)