Starting from:
$35

$29

Problem Set 2 Solution

Singular Value Decomposition and Principal Com-ponent Analysis (20 points)






In this problem we will explore the relationship between two of the most popular dimensionality-reduction techniques, SVD and PCA, at a basic conceptual level. Before we proceed with the question itself, let us brie y recap the SVD and PCA techniques and a few important observations:




First, recall that the eigenvalue decomposition of a real, symmetric, and square matrix B (of size d d) can be written as the following product:




B=Q QT




where = diag( 1; : : : ; d) contains the eigenvalues of B (which are always real) along its main diagonal and Q is an orthogonal matrix containing the eigenvectors of B as its columns.




Principal Component Analysis (PCA): Given a data matrix M (of size p q), PCA involves the computation of the eigenvectors of M MT or MT M. The matrix of these eigenvectors can be thought of as a rigid rotation in a high dimensional space. When you apply this transformation to the original data, the axis corresponding to the princi-pal eigenvector is the one along which the points are most \spread out." More precisely, this axis is the one along which the variance of the data is maximized. Put another way, the points can best be viewed as lying along this axis, with small deviations from this axis. Likewise, the axis corresponding to the second eigenvector (the eigenvector corresponding to the second-largest eigenvalue) is the axis along which the variance of distances from the rst axis is greatest, and so on.




Singular Value Decomposition (SVD): SVD involves the decomposition of a data matrix M (of size p q) into a product: U V T where U (of size p k) and V (of size q k) are column-orthonormal matrices1 and (of size k k) is a diagonal matrix. The entries along the diagonal of are referred to as singular values of M. The key to understanding what SVD o ers is in viewing the r columns of U, , and V as representing concepts that are hidden in the original matrix M.




For answering the questions below, let us de ne a real matrix M (of size p q) and let us assume this matrix corresponds to a dataset with p data points and q dimensions.







1A matrix U 2 Rp q is column-orthonormal if and only if UT U = I where I denotes the identity matrix


CS 246: Mining Massive Data Sets - Problem Set 2
2







(a) [3 points]




Are the matrices M MT and MT M symmetric, square and real? Explain.







(b) [5 points]




Prove that the nonzero eigenvalues of M MT are the same as the nonzero eigenvalues of MT M. You may ignore multiplicity of eigenvalues. Are their eigenvectors the same?







(c) [2 points]




Given that we now understand certain properties of MT M, write an expression for MT M in terms of Q, QT and where = diag( 1; : : : ; d) contains the eigenvalues of MT M along its main diagonal and Q is an orthogonal matrix containing the eigenvectors of MT M as its columns?




Hint: Check the de nition of eigenvalue decomposition provided in the beginning of the ques-tion to see if it is applicable.







(d) [5 points]




SVD decomposes the matrix M into the product U V T where U and V are column-orthonormal and is a diagonal matrix. Given that M = U V T , write a simpli ed ex-pression for MT M in terms of V , V T and .







(e) [5 points]




In this question, let us experimentally test if SVD decomposition of M actually provides us the eigenvectors (PCA dimensions) of MT M. We strongly recommend students to use Python and suggested functions for this exercise.2 Initialize matrix M as follows:

3
1 2

62 17

M=6 7




43 45

4 3




Compute the SVD of M (Use scipy.linalg.svd function in Python and set the argument full matrices to False). The function returns values corresponding to U, and V T . What are the values returned for U, and V T ? Note: Make sure that the rst element of the returned array has a greater value than the second element.







2Other implementations of SVD and PCA might give slightly di erent results. Besides, you will just need fewer than ve python commands to answer this entire question

CS 246: Mining Massive Data Sets - Problem Set 2
3







Compute the eigenvalue decomposition of MT M (Use scipy.linalg.eigh function in Python). The function returns two parameters: a list of eigenvalues (let us call this list Evals) and a matrix whose columns correspond to the eigenvectors of the respective eigenvalues (let us call this matrix Evecs). Sort the list Evals in descending order such that the largest eigenvalue appears rst in the list. Also, re-arrange the columns in Evecs such that the eigenvector corresponding to the largest eigenvalue appears in the rst column of Evecs. What are the values of Evals and Evecs (after the sorting and re-arranging process)?







Based on the experiment and your derivations in part (c) and (d), do you see any correspondence between V produced by SVD and the matrix of eigenvectors Evecs (after the sorting and re-arranging process) produced by eigenvalue decomposition? If so, what is it?




Note: The function scipy.linalg.svd returns V T (not V ).




Based on the experiment and the expressions obtained in part (c) and part (d) for MT M, what is the relationship (if any) between the eigenvalues of MT M and the singular values of M? Explain.




Note: The entries along the diagonal of (part (e)) are referred to as singular values of M. The eigenvalues of MT M are captured by the diagonal elements in (part (d))




What to submit:




Written solutions to questions 1(a) to 1(e) with explanations wherever required



Upload the code via Gradescope [1(e)]






k-means on Spark (20 points)






Note: This problem should be implemented in Spark. You should not use the Spark MLlib clustering library for this problem. You may store the centroids in memory if you choose to do so.







\ \ \







This problem will help you understand the nitty gritty details of implementing clustering algorithms on Spark. In addition, this problem will also help you understand the impact of using various distance metrics and initialization strategies in practice. Let us say we have a set X of n data points in the d-dimensional space Rd. Given the number of clusters k and the set of k centroids C, we now proceed to de ne various distance metrics and the corresponding cost functions that they minimize.

CS 246: Mining Massive Data Sets - Problem Set 2
4










Euclidean distance Given two points A and B in d dimensional space such that A = [a1; a2 ad] and B = [b1; b2 bd], the Euclidean distance between A and B is de ned as:




v




d
jja bjj =
uXi
(ai
bi)2
(1)
t










=1












The corresponding cost function that is minimized when we assign points to clusters using the Euclidean distance metric is given by:




X


x
c
2
(2)
= min
c
2C
jj
jj




x2X




Note, that in the cost function the distance value is squared. This is intentional, as it is the squared Euclidean distance the algorithm is guaranteed to minimize.




Manhattan distance Given two random points A and B in d dimensional space such that

= [a1; a2 ad] and B = [b1; b2 bd], the Manhattan distance between A and B is de ned
as:

d






Xi
jai
bij


ja bj =
(3)
=1









The corresponding cost function that is minimized when we assign points to clusters using the Manhattan distance metric is given by:




=
X
j
j
(4)
c


min x c




x2X
2C















Iterative k-Means Algorithm: We learned the basic k-Means algorithm in class which is as follows: k centroids are initialized, each point is assigned to the nearest centroid and the centroids are recomputed based on the assignments of points to clusters. In practice, the above steps are run for several iterations. We present the resulting iterative version of k-Means in Algorithm 1.




Iterative k-Means clustering on Spark: Implement iterative k-means using Spark.




Please use the dataset from q2/data within the bundle for this problem.




The folder has 3 les:




data.txt contains the dataset which has 4601 rows and 58 columns. Each row is a document represented as a 58 dimensional vector of features. Each component in the vector represents the importance of a word in the document. The ID to download data.txt into a Colab is 1E-voIV2ctU4Brw022Na8RHVVRGOoNkO1



c1.txt contains k initial cluster centroids. These centroids were chosen by selecting k = 10 random points from the input data. The ID to download c1.txt into a Colab is 1yXNlZWMqUcAwDScBrkFChOHJwR1FZXmI
CS 246: Mining Massive Data Sets - Problem Set 2
5










Algorithm 1 Iterative k-Means Algorithm







procedure Iterative k-Means



Select k points as initial centroids of the k clusters.



for iterations := 1 to MAX ITER do



for each point p in the dataset do



Assign point p to the cluster with the closest centroid



end for



Calculate the cost for this iteration.



for each cluster c do



Recompute the centroid of c as the mean of all the data points assigned to c



end for



end for



end procedure






c2.txt contains initial cluster centroids which are as far apart as possible, using Eu-clidean distance as the distance metric. (You can do this by choosing 1st centroid c1 randomly, and then nding the point c2 that is farthest from c1, then selecting c3 which is farthest from c1 and c2, and so on). The ID to download c2.txt into a Colab is 1vfovle9DgaeK0LnbQTH0j7kRaJjsvLtb






Set number of iterations (MAX ITER) to 20 and number of clusters k to 10 for all the ex-periments carried out in this question. Your driver program should ensure that the correct amount of iterations are run.










Exploring initialization strategies with Euclidean distance [10 pts]



[5 pts] Using the Euclidean distance (refer to Equation 1) as the distance measure, compute the cost function (i) (refer to Equation 2) for every iteration i. This means that, for your rst iteration, you’ll be computing the cost function using the initial centroids located in one of the two text les. Run the k-means on data.txt using c1.txt and c2.txt. Generate a graph where you plot the cost function (i) as a function of the number of iterations i=1..20 for c1.txt and also for c2.txt. You may use a single plot or two di erent plots, whichever you think best answers the theoretical questions we’re asking you about.



(Hint: Note that you do not need to write a separate Spark job to compute (i). You should be able to calculate costs while partitioning points into clusters.)




[5 pts] What is the percentage change in cost after 10 iterations of the K-Means algorithm when the cluster centroids are initialized using c1.txt vs. c2.txt and the distance metric being used is Euclidean distance? Is random initialization of k-means using c1.txt better than initialization using c2.txt in terms of cost (i)? Explain your reasoning.



(Hint: to be clear, the percentage refers to (cost[0]-cost[10])/cost[0].)

CS 246: Mining Massive Data Sets - Problem Set 2
6







Exploring initialization strategies with Manhattan distance [10 pts]



[5 pts] Using the Manhattan distance metric (refer to Equation 3) as the distance



measure, compute the cost function (i) (refer to Equation 4) for every iteration i. This means that, for your rst iteration, you’ll be computing the cost function using the initial centroids located in one of the two text les. Run the k-means on data.txt using c1.txt and c2.txt. Generate a graph where you plot the cost function (i) as a function of the number of iterations i=1..20 for c1.txt and also for c2.txt. You may use a single plot or two di erent plots, whichever you think best answers the theoretical questions we’re asking you about.




(Hint: This problem can be solved in a similar manner to that of part (a). Also note that It’s possible that for Manhattan distance, the cost do not always decrease. K-means only ensures monotonic decrease of cost for squared Euclidean distance. Look up K-medians to learn more.)




[5 pts] What is the percentage change in cost after 10 iterations of the K-Means algorithm when the cluster centroids are initialized using c1.txt vs. c2.txt and the



distance metric being used is Manhattan distance? Is random initialization of k-means using c1.txt better than initialization using c2.txt in terms of cost (i)? Explain your reasoning.







What to submit:










Upload the code for 2(a) and 2(b) to Gradescope



A plot of cost vs. iteration for two initialization strategies [2(a)]



Percentage improvement values and your explanation [2(a)]



A plot of cost vs. iteration for two initialization strategies [2(b)]



Percentage improvement values and your explanation [2(b)]






Latent Features for Recommendations (35 points)






Note: Please use native Python (Spark not required) to solve this problem. It usually takes several minutes to run, however, time may di er depending on the system you use.







\ \ \







The goal of this problem is to implement the Stochastic Gradient Descent algorithm to build a Latent Factor Recommendation system. We can use it to recommend movies to users.


CS 246: Mining Massive Data Sets - Problem Set 2
7










We encourage you to read the slides of the lecture \Recommender Systems 2" again before attempting the problem.




Suppose we are given a matrix R of ratings. The element Riu of this matrix corresponds to the rating given by user u to item i. The size of R is m n, where m is the number of movies, and n the number of users.




Most of the elements of the matrix are unknown because each user can only rate a few movies.




Our goal is to nd two matrices P and Q, such that R ’ QP T . The dimensions of Q are m k, and the dimensions of P are n k. k is a parameter of the algorithm.




We de ne the error as

E =
(i;u) ratings(Riu
qi puT )2
+
" u
kpuk22 +
i
kqik22
#:
(5)


X




X


X








2
















P

The (i;u)2ratings means that we sum only on the pairs (user; item) for which the user has rated the item, i.e. the (i; u) entry of the matrix R is known. qi denotes the ith row of the matrix Q (corresponding to an item), and pu the uth row of the matrix P (corresponding to a user u). qi and pu are both row vectors of size k. is the regularization parameter. k k2 is the L2 norm and kpuk22 is square of the L2 norm, i.e., it is the sum of squares of elements of pu.







(a) [10 points]




Let "iu denote the derivative of the error E with respect to Riu. What is the expression for "iu? What are the update equations for qi and pu in the Stochastic Gradient Descent algorithm? Please show your derivation and use "iu in your nal expression of qi and pu.







(b) [25 points]




Implement the algorithm. Read each entry of the matrix R from disk and update "iu, qi and pu for each entry.




To emphasize, you are not allowed to store the matrix R in memory. You have to read each element Riu one at a time from disk and apply your update equations (to each element) each iteration. Each iteration of the algorithm will read the whole le.




Choose k = 20, = 0:1 and number of iterations = 40. Find a good value for the learning rate , starting with = 0:1. (You may not modify k or ) The error E on the training set ratings.train.txt discussed below should be less than 65000 after 40 iterations; you should observe both qi and pu stop changing.




Based on values of , you may encounter the following cases:

CS 246: Mining Massive Data Sets - Problem Set 2
8










If is too big, the error function can converge to a high value or may not monotonically decrease. It can even diverge and make the components of vectors p and q equal to 1.




If is too small, the error function doesn’t have time to signi cantly decrease and reach convergence. So, it can monotonically decrease but not converge i.e. it could have a high value after 40 iterations because it has not converged yet.







Use the dataset at q3/data within the bundle for this problem. It contains the following les:




ratings.train.txt: This is the matrix R. Each entry is made of a user id, a movie id, and a rating.







Plot the value of the objective function E (de ned in equation 5) on the training set as a function of the number of iterations. What value of did you nd?




You can use any programming language to implement this part, but Java, C/C++, and Python are recommended for speed. (In particular, Matlab can be rather slow reading from disk.) It should be possible to get a solution that takes on the order of minutes to run with these languages.




Hint: These hints will help you if you are not sure about how to proceed for certain steps of the algorithm, although you don’t have to follow them if you have another method.




Initialization of P and Q: We would like qi and pu for all users u and items i such

that qi pTu 2 [0; 5]. A good way to achieve that is to initialize all elements of P and Q

p




to random values in [0; 5=k].




Update the equations: In each update, we update qi using pu and pu using qi. Compute the new values for qi and pu using the old values, and then update the vectors qi and pu.




You should compute E at the end of a full iteration of training. Computing E in pieces during the iteration is incorrect since P and Q are still being updated.







What to submit




Equation for "iu. Update equations in the Stochastic Gradient Descent algorithm [3(a)]



Value of . Plot of E vs. number of iterations. Make sure your graph has a y-axis so that we can read the value of E. Only one plot with your chosen is required [3(b)]



Please upload all the code to Gradescope [3(b)]
CS 246: Mining Massive Data Sets - Problem Set 2
9







Recommendation Systems (25 points)






Note: Please use native Python (Spark not required) to solve this problem. If you run into memory error when doing large matrix operations, please make sure you are using 64-bit Python instead of 32-bit (which has a 4GB memory limit).




\ \ \







Consider a user-item bipartite graph where each edge in the graph between user U to item I, indicates that user U likes item I. We also represent the ratings matrix for this set of users and items as R, where each row in R corresponds to a user and each column corresponds to an item. If user i likes item j, then Ri;j = 1, otherwise Ri;j = 0. Also assume we have m users and n items, so matrix R is m n.




Let’s de ne a matrix P , m m, as a diagonal matrix whose i-th diagonal element is the degree of user node i, i.e. the number of items that user i likes. Similarly, a matrix Q, n n, is a diagonal matrix whose i-th diagonal element is the degree of item node i or the number of users that liked item i. See gure below for an example.







(a) [4 points]




De ne the non-normalized user similarity matrix T = R RT (multiplication of R and transposed R). Explain the meaning of Tii and Tij (i 6= j), in terms of bipartite graph structures (See Figure 1) (e.g. node degrees, path between nodes, etc.).










Cosine Similarity: Recall that the cosine similarity of two vectors u and v is de ned as:




u v




cos-sim(u,v) = kukkvk







(b) [6 points]




Let’s de ne the item similarity matrix, SI , n n, such that the element in row i and column j is the cosine similarity of item i and item j which correspond to column i and column j of the matrix R. Show that SI = Q 1=2RT RQ 1=2, where Q 1=2 is de ned by Qrc1=2 = 1=pQrc for all nonzero entries of the matrix, and 0 at all other positions.







Repeat the same question for user similarity matrix, SU where the element in row i and column j is the cosine similarity of user i and user j which correspond to row i and row j of the matrix R. That is, your expression for SU should also be in terms of some combination of R, P , and Q. Your answer should be an operation on the matrices, in particular you should not de ne each coe cient of SU individually.

CS 246: Mining Massive Data Sets - Problem Set 2
10
























































































Figure 1: User-Item bipartite graph.










Your answer should show how you derived the expressions.




(Note: To make the element-wise square root of a matrix, you may write it as matrix to the power of 12 .)







(c) [5 points]




The recommendation method using user-user collaborative ltering for user u, can be de-scribed as follows: for all items s, compute ru;s = x2users cos-sim(x; u) Rxs and recommend the k items for which ru;s is the largest.




Similarly, the recommendation method using item-item collaborative ltering for user u can be described as follows: for all items s, compute ru;s = x2itemsRux cos-sim(x; s) and recommend the k items for which ru;s is the largest.




Let’s de ne the recommendation matrix, m n, such that i; j) = ri;j. Find for both item-item and user-user collaborative ltering approaches, in terms of R, P and Q. Your nal answer should describe operations on matrix level, not speci c terms of matrices.




Hint: For the item-item case, = RQ 1=2RT RQ 1=2.




Your answer should show how you derived the expressions (even for the item-item case, where we give you the nal expression).

CS 246: Mining Massive Data Sets - Problem Set 2
11







(d) [10 points]




In this question you will apply these methods to a real dataset. The data contains information about TV shows. More precisely, for 9985 users and 563 popular TV shows, we know if a given user watched a given show over a 3 month period.




Use the dataset from q4/data within the bundle for this problem.




The folder contains:




user-shows.txt This is the ratings matrix R, where each row corresponds to a user and each column corresponds to a TV show. Rij = 1 if user i watched the show j over a period of three months. The columns are separated by a space.




shows.txt This is a le containing the titles of the TV shows, in the same order as the columns of R.




We will compare the user-user and item-item collaborative ltering recommendations for the 500th user of the dataset. Let’s call him Alex. (i.e. with Python’s 0-based indexing, Alex=users[499].)




In order to do so, we have erased the rst 100 entries of Alex’s row in the matrix, and replaced them by 0s. This means that we don’t know which of the rst 100 shows Alex has watched. Based on Alex’s behaviour on the other shows, we will give Alex recommendations on the rst 100 shows. We will then see if our recommendations match what Alex had in fact watched.




Compute the matrices P and Q.




Using the formulas found in part (c), compute for the user-user collaborative ltering. Let S denote the set of the rst 100 shows (the rst 100 columns of the matrix). From all the TV shows in S, which are the ve that have the highest similarity scores for Alex? In case of ties of similarity scores between two shows, choose the one with smaller index. Do not write the index of the TV shows, write their names using the le shows.txt.




Compute the matrix for the movie-movie collaborative ltering. From all the TV shows in S, which are the ve that have the highest similarity scores for Alex? In case of ties between two shows, choose the one with smaller index. Again, hand in the names of the shows and their similarity score.







For sanity check, your highest similarity score for user-user collaborative ltering should be above 900, and your highest similarity score for movie-movie ltering should be above 31.




What to submit:




(i) Interpretation of Tii and Tij [4(a)]



CS 246: Mining Massive Data Sets - Problem Set 2
12




(ii)
Expression of SI and SU in terms of R, P and Q and accompanying explanation [4(b)]
(iii)
Expression of in terms of R, P and Q and accompanying explanation [4(c)]





The answer to this question should include the followings: [4(d)]



The names of ve TV shows that have the highest similarity scores for Alex for the user-user collaborative ltering (no need to report the similarity scores)




The names of ve TV shows that have the highest similarity scores for Alex for the item-item collaborative ltering (no need to report the similarity scores)




Upload the source code via Gradescope

More products