dibgerge / ml-coursera-python-assignments Goto Github PK
View Code? Open in Web Editor NEWPython assignments for the machine learning class by andrew ng on coursera with complete submission for grading capability and re-written instructions.
Python assignments for the machine learning class by andrew ng on coursera with complete submission for grading capability and re-written instructions.
print(X.shape, theta.shape, y.shape)
print(theta)
print(X[0])
outputs:
(47, 3) (2,) (47,)
[-3.63029144 1.16636235]
[ 1. 0.13141542 -0.22609337]
because X had a column concatenated in an earlier cell:
X_norm = np.concatenate([np.ones((m, 1)), X_norm], axis=1)
so there is a mismatch when trying to do a dot product with a row of X
and theta
. 3 elements vs. 2.
Also it won't let me concatenate theta with the line below:
theta = np.concatenate([np.ones((m, 1)), theta], axis=1)
Hello all,
The following line in exercise7.ipynb is causing a ModuleNotFoundError:
"%load_ext autoreload "
There is an extra space after "autoreload" which is passed further:
ModuleNotFoundError Traceback (most recent call last)
in
----> 1 get_ipython().run_line_magic('load_ext', 'autoreload ')
Solution: just delete the space after autoreload.
Thank you,
Andreas
I am doing week 6 exercise and found that learning curve method is not accepting solution. My Linear Regression cost function is accepted but this is not.
` m = y.size
# You need to return these values correctly
error_train = np.zeros(m)
error_val = np.zeros(m)
# ====================== YOUR CODE HERE ======================
for i in range(1, m+1):
X_train = X[:i, :]
y_train = y[:i]
theta = utils.trainLinearReg(linearRegCostFunction, X_train, y_train, lambda_)
error_train[i-1] = linearRegCostFunction(X_train, y_train, theta, lambda_)[0]
error_val[i-1] = linearRegCostFunction(Xval, yval, theta, lambda_)[0]
# =============================================================
return error_train, error_val`
I can see same graph in output.
I'm getting an "HTTPError: HTTP Error 500: Internal Server Error" when submitting the warmUpExercise on Lab 1.
I am pretty sure that my email and token work because when I distort the token and resubmit, I get the error:
"You used an invalid email or your token may have expired. Please make sure you have entered all fields correctly. Try generating a new token if the issue still persists."
Is anyone else able to submit the Coursera auto-grader?
In the README you are saying that matrix multiplication is done with np.dot() and that after python 3.5 '@' is replaced np.dot(), however, this is not completely correct. '@' works as np.matmul() which quoting from NumPy's docs:
"matmul differs from dot in two important ways:
Multiplication by scalars is not allowed, use * instead.
Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature (n,k),(k,m)->(n,m):
"
It's not a big deal but it's worth correcting I belive.
https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
Since the original set of assignments are written for matlab/octave, it makes sense to use the data files as .mat. However, most of the time data will be saved and loaded using csv, so maybe it would be a good idea to use that extension in order to get the learner familiar with manipulating csv files?
Really just a suggestion here. Thanks for your work!
The expected value of C and sigma is 0.3 and 0.1 This combination gives an error 0.04. But the combination 3 and 0.1 gives an error 0.035 which is smaller than 0.04. Due to this my submission fails.
The expected code :
model = utils.svmTrain(X, y, 0.3, gaussianKernel, args=(0.1,))
predictions = utils.svmPredict(model, Xval)
print(np.mean(predictions != yval))
0.04
Whereas this one
model = utils.svmTrain(X, y, 3, gaussianKernel, args=(0.1,))
predictions = utils.svmPredict(model, Xval)
print(np.mean(predictions != yval))
0.035
While my output appears to be correct, I am getting the following error on the grader. I attempted to trace back the issue, but it seems to be stemming from the grader file itself. Has anyone come across this before? Thanks!
UnboundLocalError Traceback (most recent call last)
in ()
1 grader[3] = learningCurve
----> 2 grader.grade()
~/Desktop/python_practice/ml-coursera-python-assignments-master/submission.py in grade(self)
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)
~/Desktop/python_practice/ml-coursera-python-assignments-master/Exercise5/utils.py in iter(self)
UnboundLocalError: local variable 'res' referenced before assignment
This is my code for the learningCurve() function.
def learningCurve(X, y, Xval, yval, lambda_=0):
m = y.size
m_val = yval.size
# You need to return these values correctly
error_train = np.zeros(m)
error_val = np.zeros(m)
# ====================== YOUR CODE HERE ======================
for i in range(1, m+1):
temp_theta = utils.trainLinearReg(linearRegCostFunction, X[:i,], y[:i], 0)
error_train[i-1] = (1/(2*m))*np.sum(np.square(X[:i, ] @ temp_theta - y[:i ]))
error_val[i-1] = (1/(2*m_val))*np.sum(np.square(Xval @ temp_theta - yval))
# =============================================================
return error_train, error_val
The fourth cell from last in 3.1 feature normalization in exercise1 should be "You should now submit your solutions." but not "You should not submit your solutions.", right?
Felt strange when I first saw this lol.
As I try to submit my code for the first part of exercise 4 I get the following error :
ValueError Traceback (most recent call last)
in
1 grader = utils.Grader()
2 grader[1] = nnCostFunction
----> 3 grader.grade()
~/Desktop/AndrewNg_Course/Python/ml-coursera-python-assignments/submission.py in grade(self)
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)
~/Desktop/AndrewNg_Course/Python/ml-coursera-python-assignments/Exercise4/utils.py in iter(self)
203 # Each part has different expected arguments/different function
204 if part_id == 1:
--> 205 res = func(self.t, 2, 4, 4, self.Xm, self.ym, 0)[0]
206 elif part_id == 2:
207 res = func(self.t, 2, 4, 4, self.Xm, self.ym, 1.5)
in nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_)
118 y_mat[i,y[i]]=1
119 y_vec = y_mat[i]
--> 120 j += np.dot(-y_vec,log1) - np.dot((1-y_vec),log2)
121 J = (1/m)*j
122
ValueError: shapes (10,) and (4,) not aligned: 10 (dim 0) != 4 (dim 0)`
That is odd because my code runs ok when I call the nnCostFunction function needed to calculate the feedforward cost and I find the requested cost to be equal to the answer provided.
Moreover y_vec, log1, 1-y_vec and log2 are all 1d vectors with shape (10,) so I cannot understand how a shape (4,) is found by the grader.
Thank you in advance
Hello,
Thanks for what you have done, much appreciated.
I've tried to submit the warmUpExercise and this is what I get.
How can I solve this?
SSLCertVerificationError Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1316 h.request(req.get_method(), req.selector, req.data, headers,
-> 1317 encode_chunked=req.has_header('Transfer-encoding'))
1318 except OSError as err: # timeout error
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in request(self, method, url, body, headers, encode_chunked)
1243 """Send a complete request to the server."""
-> 1244 self._send_request(method, url, body, headers, encode_chunked)
1245
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in _send_request(self, method, url, body, headers, encode_chunked)
1289 body = _encode(body, 'body')
-> 1290 self.endheaders(body, encode_chunked=encode_chunked)
1291
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in endheaders(self, message_body, encode_chunked)
1238 raise CannotSendHeader()
-> 1239 self._send_output(message_body, encode_chunked=encode_chunked)
1240
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in _send_output(self, message_body, encode_chunked)
1025 del self._buffer[:]
-> 1026 self.send(msg)
1027
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in send(self, data)
965 if self.auto_open:
--> 966 self.connect()
967 else:
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in connect(self)
1413 self.sock = self._context.wrap_socket(self.sock,
-> 1414 server_hostname=server_hostname)
1415
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
422 context=self,
--> 423 session=session
424 )
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
869 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 870 self.do_handshake()
871 except (OSError, ValueError):
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py in do_handshake(self, block)
1138 self.settimeout(None)
-> 1139 self._sslobj.do_handshake()
1140 finally:
SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)
During handling of the above exception, another exception occurred:
URLError Traceback (most recent call last)
in
3
4 # send the added functions to coursera grader for getting a grade on this part
----> 5 grader.grade()
~/Documents/ml/submission.py in grade(self)
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
~/Documents/ml/submission.py in request(self, parts)
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()
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
220 else:
221 opener = _opener
--> 222 return opener.open(url, data, timeout)
223
224 def install_opener(opener):
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
523 req = meth(req)
524
--> 525 response = self._open(req, data)
526
527 # post-process response
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in _open(self, req, data)
541 protocol = req.type
542 result = self._call_chain(self.handle_open, protocol, protocol +
--> 543 '_open', req)
544 if result:
545 return result
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
501 for handler in handlers:
502 func = getattr(handler, meth_name)
--> 503 result = func(*args)
504 if result is not None:
505 return result
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in https_open(self, req)
1358 def https_open(self, req):
1359 return self.do_open(http.client.HTTPSConnection, req,
-> 1360 context=self._context, check_hostname=self.check_hostname)
1361
1362 https_request = AbstractHTTPHandler.do_request
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1317 encode_chunked=req.has_header('Transfer-encoding'))
1318 except OSError as err: # timeout error
-> 1319 raise URLError(err)
1320 r = h.getresponse()
1321 except:
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)>
Hello!
I might be dumb, but where are the actual solutions? I click in the table where you list the functions, but it just seems to take me to the same page?
Thank you for your work though, hope I can figure it out! :D
`
def oneVsAll(X, y, num_labels, lambda_):
# Some useful variables
m, n = X.shape
# You need to return the following variables correctly
all_theta = np.zeros((num_labels, n + 1))
# Add ones to the X data matrix
X = np.concatenate([np.ones((m, 1)), X], axis=1)
# ====================== YOUR CODE HERE ======================
initial_theta = np.zeros((n+1,1))
options = {'maxiter': 50}
for c in np.arange(1, num_labels+1):
res = optimize.minimize(lrCostFunction,
initial_theta,
(X, (y == c), lambda_),
jac=True,
method='TNC',
options=options)
all_theta[c-1] = res.x
# ============================================================
return all_theta
`
Hi,Dib,
Could you please tell me what's wrong with my code? I am confused.
Thanks.
In the very last part of excercise2, the expected accuracy is to be approximately 83.1%
Expected accuracy (with lambda = 1): 83.1 % (approx)
When I actually run my solution code, I get accuracy of 79.7%. I do not believe that my implementation is incorrect as the previous cells all print correct values for thetas and gradients. The plot also matches figures above with theta=1.
Here is my solution code and the unexpected result -
`
6.//Load the .mat file, which returns a dictionary
7. weights = loadmat(os.path.join('Data', 'ex3weights.mat'))
8.
9. //get the model weights from the dictionary
10. // Theta1 has size 25 x 401
11. //Theta2 has size 10 x 26
12. Theta1, Theta2 = weights['Theta1'], weights['Theta2']
13.
14. //swap first and last columns of Theta2, due to legacy from MATLAB indexing,
15. //since the weight file ex3weights.mat was saved based on MATLAB indexing
16. Theta2 = np.roll(Theta2, 1, axis=0)
`
here we are swapping first and last row not column (as stated in line 14 [which is incorrect]) with axis = 0 (in line 16) not column .
When submitting an assignment (assignment#1) in my case, I am just prompted for the email address and not the web token.
As such, I don't see my submissions on the coursera page.
Please advise.
Thanks
First of all I greatly appreciate all the effort that was put into this project,
but,
when I try submitting warmUpExercise I get this error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-15-a776c0c55379> in <module>
1 # appends the implemented function in part 1 to the grader object
----> 2 grader[1] = warmUpExercise
3
4 # send the added functions to coursera grader for getting a grade on this part
5 grader.grade()
NameError: name 'grader' is not defined
I hope the grader still works.
Firstly - thanks so much for creating and posting these notebooks - incredibly useful for everyone that wants to complete Andrew Ng's course, but continue to code in Python - including me!
I'm having problems submitting my code - for the very first part of the first exercise.
When I provide my username and token, I get consistently get the following error message (it's a long error log - the two images are the beginning and end parts):
I'd appreciate any help anyone can give in how to solve this. My thanks in advance.
grader[1] = findClosestCentroids
grader.grade()
in iter(self)
220 # Each part has different expected arguments/different function
221 if part_id == 1:
--> 222 res = 1 + func(self.X, self.C)
223 elif part_id == 2:
224 res = func(self.X, self.idx, 3)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
The assignment key for Exercise 8 seems to be incorrect and the grader cannot grade the assignments due to it.
This block:
res = optimize.minimize(lrCostFunction,
initial_theta,
(X, (y == c), lambda_),
jac=True,
method='TNC') # <-
options=options)
Also, options should be written with a colon, e.g., options= {'maxiter': 50}
Coursera added a new section which is located just before programming assignment 1 section of week 2. They have also changed the token duration and now token is going to expire in 30 minutes.
After these updates, I am unable to submit the assignment. When I submitted the assignment, it is showing HTTPError: HTTP Error 500: Internal Server Error
The entire error is below
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
<ipython-input-5-a776c0c55379> in <module>
3
4 # send the added functions to coursera grader for getting a grade on this part
----> 5 grader.grade()
~\Downloads\ML Assignments - Python\submission.py in grade(self)
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
~\Downloads\ML Assignments - Python\submission.py in request(self, parts)
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()
C:\Program Files (x86)\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
220 else:
221 opener = _opener
--> 222 return opener.open(url, data, timeout)
223
224 def install_opener(opener):
C:\Program Files (x86)\lib\urllib\request.py in open(self, fullurl, data, timeout)
529 for processor in self.process_response.get(protocol, []):
530 meth = getattr(processor, meth_name)
--> 531 response = meth(req, response)
532
533 return response
C:\Program Files (x86)\lib\urllib\request.py in http_response(self, request, response)
638 # request was successfully received, understood, and accepted.
639 if not (200 <= code < 300):
--> 640 response = self.parent.error(
641 'http', request, response, code, msg, hdrs)
642
C:\Program Files (x86)\lib\urllib\request.py in error(self, proto, *args)
567 if http_err:
568 args = (dict, 'default', 'http_error_default') + orig_args
--> 569 return self._call_chain(*args)
570
571 # XXX probably also want an abstract factory that knows when it makes
C:\Program Files (x86)\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
500 for handler in handlers:
501 func = getattr(handler, meth_name)
--> 502 result = func(*args)
503 if result is not None:
504 return result
C:\Program Files (x86)\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
647 class HTTPDefaultErrorHandler(BaseHandler):
648 def http_error_default(self, req, fp, code, msg, hdrs):
--> 649 raise HTTPError(req.full_url, code, msg, hdrs, fp)
650
651 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 500: Internal Server Error
Hi,
On the last task when you have to implement the predict()
function for neural nets - I test it and get the correct 97.5% training set accuracy but then when I submit using the grader I don't get the points. It just shows " 0 / 30" for the last task without any additional message. Is it a bug or a mistake on my end?
I have tried to generate a new token on Coursera and resubmit but it did not help.
Please refer to this link of Coursera discussion forum. In Q5 it is written that if we are doing element wise multiplication with g'(z), while calculating delta_{2} , we must remove the first column of the Theta_2.
The bug was that, it was asked to remove the first element of delta_2, which should be done only if we are doing element wise multiplication with a_2*(1- a_2), but here we are doing with g'(z).
I have opened a pull request, you can merge it or, change that line yourself.
I keep getting the below error. However, I am using my email and the token generated in the Coursera pages. Anyone has the similar issue?
URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
I am unable to get the indexes right for the method.
def computeCost(X, y, theta):
m = y.size
J = 0
print(X.shape)
hyp = X@theta
err = hyp - y
sqr_err = err**2
J = (1/(2m))(np.sum(sqr_err))
return J
This is the code i wrote but it does not seem to work for all the test cases, but when I use
hyp = [email protected]
the external test cases work but the ones inside the system do not.
The external test cases are the ones on the Coursera website and the internal test cases are the ones where we input the data file by using os.path.join...
Is this an issue with the data formatting or am I making a mistake? I have attached my files and everything, for you to see.
Please help.
Hi everyone.
I'm having a problem in the exercise 2.
I implement my costFunction that works fine with initial_theta set to numpy.zeros().
Then I test with test_theta set to numpy.ones(). The first two values are incorrect but the others 26 are the same as the expected. I got as the first two values:
0.43079084 and 0.07660616 instead of 0.346045 and 0.161352
As accuracy I also get a wrong value: 79.66 instead of 83.1
This is my costFunction
def costFunctionReg(theta, X, y, lambda_):
m, n = X.shape
theta = theta.reshape((n, 1))
h_theta = sigmoid(X @ theta)
J = (1 / m) * (-y.T @ numpy.log(h_theta) - (1 - y).T @ numpy.log(1 - h_theta)) + (lambda_ / (2 * m)) * (theta[1:theta.size]).T @ theta[1:theta.size]
thetaZero = theta
thetaZero[1] = 0
grad = ((1 / m) * (h_theta - y).T @ X) + lambda_ / m * thetaZero.T
grad = grad.reshape((n, 1))
return J, grad
Where I'm wrong?
I implement the same (i think) code in octave and I got the correct result.
Thanks.
The function returns 'None' for vocabList when using the following:
It works with the following code
urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
This sentence text:
The first column is the population of a city and the second column is the profit of a food truck in that city
Should be modified to add the units on population (10k) and profit (10k)
I am new to begin the "Machine Learning" course. I submitted the exercise to grade and Jupyter notebook promt me to input email and token. I input my private email and token displayed on cmd but I get the error "You used an invalid email or your token may have expired. Please make sure you have entered all fields correctly. Try generating a new token if the issue still persists."
Can anyone help me ?
Getting errors making it hard to submit file.
TypeError Traceback (most recent call last)
in
3
4 # send the added functions to coursera grader for getting a grade on this part
----> 5 grader.grade()
~\Documents\MSc\Coursera_ML\ml-coursera-python-assignments\submission.py in grade(self)
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"))
~\Documents\MSc\Coursera_ML\ml-coursera-python-assignments\submission.py in sprintf(fmt, arg)
103 return ' '.join(fmt % e for e in np.asarray(arg).ravel('F'))
104 else:
--> 105 return fmt % arg
TypeError: must be real number, not NoneType
When I try to submit first excercise to the grader Im getting following error:
TypeError Traceback (most recent call last)
<ipython-input-5-a776c0c55379> in <module>()
3
4 # send the added functions to coursera grader for getting a grade on this part
----> 5 grader.grade()
~\PythonProjects\ml-coursera-python-assignments\submission.py in grade(self)
31 parts[str(part_id)] = {'output': sprintf('%0.5f ', result)}
32 result, response = self.request(parts)
---> 33 response = json.loads(response)
34
35 # if an error was returned, print it and stop
~\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
310 if not isinstance(s, str):
311 raise TypeError('the JSON object must be str, not {!r}'.format(
--> 312 s.__class__.__name__))
313 if s.startswith(u'\ufeff'):
314 raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
TypeError: the JSON object must be str, not 'bytes'
What should I do ?
H = sigmoid(np.dot(X,theta))
J = (1/m)*sum((np.dot(-y,np.log(H)))-np.dot((1-y),np.log(1-H)))
grad = (1/m)*sum(np.dot(X,(H-y)))
After submitting block [8], I get this error:
Submitting Solutions | Programming Exercise logistic-regression
Use token from last successful submission ([email protected])? (Y/n): n
Login (email address): [email protected]
Token: **correct token value**
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-d8e5e73f37b1> in <module>
3
4 # send the added functions to coursera grader for getting a grade on this part
----> 5 grader.grade()
~\Documents\ml-coursera-python-assignments-master\ml-coursera-python-assignments-master\submission.py in grade(self)
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)
~\Documents\ml-coursera-python-assignments-master\ml-coursera-python-assignments-master\Exercise2\utils.py in __iter__(self)
129 # Each part has different expected arguments/different function
130 if part_id == 1:
--> 131 res = func(self.X)
132 elif part_id == 2:
133 res = func(np.array([0.25, 0.5, -0.5]), self.X, self.y)
<ipython-input-5-b8fb2cf15b4e> in sigmoid(z)
28 import math
29
---> 30 g = 1 / (1 + math.exp(-z))
31
32
TypeError: only size-1 arrays can be converted to Python scalars
my sigmoid function did not throw errors when running the previous block earlier ...
hi guys.
I encountered this warning while checking exercise 2
ml-coursera-python-assignments/Exercise2/utils.py:45: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
return np.array(out)
This warning does not sound dangerous, but I thought it's good to inform you.
Hi
Thanks for this work!
I have correctly submitted the Regularized Linear Regression Cost Function and Regularized Linear Regression Gradient exercises.
However, when I plot the line of best fit, instead of getting this:
I get this:
Consequently, when I submit learningCurve, I get this ValueError: setting an array element with a sequence.
Can't figure out why...
the function cell [4] requests the user's email address but does not request the user's token.
after running this cell, the kernel locks up
Sorry if this is a daft question. The coursera forum mentors state clearly in several threads that only Matlab/Octave exercises will be graded. I'm keen to complete all in python.
If you follow your instructions and https://github.com/sgang007/Coursera-Stanford-ML-Python
submission guidance will i still be able to pass/get my certificate using python ?
Also thank you for this repo!!!
Thank you so much for providing a Python version of the programming assignments.
However, when I attempt to run the grader for any problem, I enter my email address when prompted, enter the token code generated on Coursera, and then the following error occurs:
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)>
The actual stack trace is much longer than that, but that is the relevant portion at the bottom.
I've tried Googling around to find a solution to this but have had no luck.
I implemented the below code for part 1.3 of exercise 5
`def linearRegCostFunction(X, y, theta, lambda_=0.0):
"""
Compute cost and gradient for regularized linear regression
with multiple variables. Computes the cost of using theta as
the parameter for linear regression to fit the data points in X and y.
Parameters
----------
X : array_like
The dataset. Matrix with shape (m x n + 1) where m is the
total number of examples, and n is the number of features
before adding the bias term.
y : array_like
The functions values at each datapoint. A vector of
shape (m, ).
theta : array_like
The parameters for linear regression. A vector of shape (n+1,).
lambda_ : float, optional
The regularization parameter.
Returns
-------
J : float
The computed cost function.
grad : array_like
The value of the cost function gradient w.r.t theta.
A vector of shape (n+1, ).
Instructions
------------
Compute the cost and gradient of regularized linear regression for
a particular choice of theta.
You should set J to the cost and grad to the gradient.
"""
# Initialize some useful values
m = y.size # number of training examples
# You need to return the following variables correctly
J = 0
if theta is None:
theta = np.zeros(theta.shape)
else:
theta = theta
#X = np.concatenate([np.ones((m, 1)), X], axis=1)
# ====================== YOUR CODE HERE ======================
h = X.dot(theta)
J= (1/(2*m))*np.sum(np.square(h-y)) + (lambda_/ (2*m)) *np.sum(np.square(theta[1:]))
grad = (1/m)*(X.T.dot(h-y))+ (lambda_/m)*np.r_[[[0]],theta[1:].reshape(-1,1)]
grad = grad.flatten()
# ============================================================
return J, grad[[0,3]]`
the above function produces the below output, which matches the correct value.
theta = np.array([1, 1])
J, grad = linearRegCostFunction(np.concatenate([np.ones((m, 1)), X], axis=1), y, theta, 1)
Gradient at theta = [1, 1]: [-15.303016, 598.250744]
(this value should be about [-15.303016, 598.250744])
However, the grade function doesn't grade the submission
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.