Exercise 4
Please complete the predict
function to produce 1
or 0
predictions given a
dataset and a learned parameter vector π€w and πb.
- First you need to compute the prediction from the model π(π₯(π))=π(π€β
π₯(π))f(x(i))=g(wβ
x(i)) for every example
- Youβve implemented this before in the parts above
- We interpret the output of the model (π(π₯(π))f(x(i))) as the probability that π¦(π)=1y(i)=1 given π₯(π)x(i) and parameterized by π€w.
- Therefore, to get a final prediction (π¦(π)=0y(i)=0 or π¦(π)=1y(i)=1) from the logistic regression model, you can use the following heuristic -if π(π₯(π))>=0.5f(x(i))>=0.5, predict π¦(π)=1y(i)=1if π(π₯(π))<0.5f(x(i))<0.5, predict π¦(π)=0y(i)=0
If you get stuck, you can check out the hints presented after the cell below to help you with the implementation.
def predict(X, w, b):
ββ"
Predict whether the label is 0 or 1 using learned logistic
regression parameters w
Args:
X : (ndarray Shape (m, n))
w : (array_like Shape (n,)) Parameters of the model
b : (scalar, float) Parameter of the model
Returns:
p: (ndarray (m,1))
The predictions for X using a threshold at 0.5
"""
# number of training examples
m, n = X.shape
p = np.zeros(m)
### START CODE HERE ###
# Loop over each example
for i in range(m):
z_wb = None
# Loop over each feature
for j in range(n):
# Add the corresponding term to z_wb
z_wb += None
# Add bias term
z_wb += None
# Calculate the prediction for this example
f_wb = None
# Apply the threshold
p[i] = None
### END CODE HERE ###
return p
Test your predict code
np.random.seed(1)
tmp_w = np.random.randn(2)
tmp_b = 0.3
tmp_X = np.random.randn(4, 2) - 0.5
tmp_p = predict(tmp_X, tmp_w, tmp_b)
print(fβOutput of predict: shape {tmp_p.shape}, value {tmp_p}')
Can someone solve this question.