0
0
ML Pythonml~10 mins

Matrix factorization basics in ML Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a matrix factorization model using numpy.

ML Python
import numpy as np

# Initialize matrices
R = np.array([[5, 3, 0], [4, 0, 0], [1, 1, 0]])
num_users, num_items = R.shape
K = 2
P = np.random.rand(num_users, [1])
Q = np.random.rand(num_items, K)
Drag options to blanks, or click blank then click option'
A1
Bnum_users
Cnum_items
DK
Attempts:
3 left
💡 Hint
Common Mistakes
Using num_users or num_items as the second dimension of P instead of K.
Setting the dimension to 1 which is incorrect for latent features.
2fill in blank
medium

Complete the code to compute the predicted rating matrix by multiplying P and Q transpose.

ML Python
predicted_ratings = np.dot(P, [1])
Drag options to blanks, or click blank then click option'
AQ
BR
CQ.T
DP.T
Attempts:
3 left
💡 Hint
Common Mistakes
Multiplying P by Q without transpose causing dimension mismatch.
Using P.T or R which are incorrect for prediction.
3fill in blank
hard

Fix the error in the gradient descent update step for matrix factorization.

ML Python
for i in range(num_users):
    for j in range(num_items):
        if R[i][j] > 0:
            eij = R[i][j] - np.dot(P[i, :], Q[j, :].T)
            for k in range(K):
                P[i][k] += [1] * (2 * eij * Q[j][k] - 0.01 * P[i][k])
Drag options to blanks, or click blank then click option'
A0.002
B0.02
C-0.002
D-0.02
Attempts:
3 left
💡 Hint
Common Mistakes
Using a negative learning rate causing the model to diverge.
Using too large a learning rate causing unstable updates.
4fill in blank
hard

Fill both blanks to complete the error calculation and regularization term in matrix factorization.

ML Python
error = 0
for i in range(num_users):
    for j in range(num_items):
        if R[i][j] > 0:
            error += (R[i][j] - np.dot(P[i, :], Q[j, :].T))[1] 2
            for k in range(K):
                error += 0.01 / 2 * (P[i][k][2] 2 + Q[j][k][2] 2)
Drag options to blanks, or click blank then click option'
A**
B*
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' instead of '**' which multiplies but does not square.
Using '+' or '-' which changes the meaning of the formula.
5fill in blank
hard

Fill all three blanks to create a dictionary of predicted ratings for items with predicted rating above 3.

ML Python
predicted_dict = {item: predicted_ratings[user][[1]] for user in range(num_users) for item in range(num_items) if predicted_ratings[user][item] [2] 3 and predicted_ratings[user][item] [3] 5}
Drag options to blanks, or click blank then click option'
Aitem
B>
C<
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'user' instead of 'item' as dictionary keys.
Using wrong comparison operators causing incorrect filtering.