<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ishay Telavivi on Medium]]></title>
        <description><![CDATA[Stories by Ishay Telavivi on Medium]]></description>
        <link>https://medium.com/@ishay.telavivi?source=rss-44ca4c35c8b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*_HU8UbO8z30pxCyvAjDP4g.jpeg</url>
            <title>Stories by Ishay Telavivi on Medium</title>
            <link>https://medium.com/@ishay.telavivi?source=rss-44ca4c35c8b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:01:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ishay.telavivi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Use Cross-Validation for Matrix Completion]]></title>
            <link>https://medium.com/data-science/how-to-use-cross-validation-for-matrix-completion-2b14103d2c4c?source=rss-44ca4c35c8b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b14103d2c4c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nmf]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[matrix-factorization]]></category>
            <dc:creator><![CDATA[Ishay Telavivi]]></dc:creator>
            <pubDate>Thu, 02 Jan 2020 15:13:02 GMT</pubDate>
            <atom:updated>2020-01-18T06:55:25.581Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step cross-validation optimization for finding the best k latent features and factor matrices</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_2LilLuCDe_ogr0e" /><figcaption>Photo by <a href="https://unsplash.com/@jespl?utm_source=medium&amp;utm_medium=referral">Jessi Pena</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>General</h4><p>Cross-Validation is a well-known practice in machine learning, and normally, it is a part of the training process which assures that our models perform well on data that was not fitted. There are different ways of performing cross-validation, but in all of them, we predict our fitted model on unfitted data.</p><p>In my searches for Matrix Completion tools, I found mainly examples that use the whole data, and don’t leave a test set. In this post, I am demonstrating step by step how to use cross-validation to find the best <strong>k</strong> (latent features) in NMF (Non-negative Matrix Factorization) algorithm for completing missing values in a matrix. However, this can be applied to other algorithms as well.</p><p>Just to keep everyone on the same page, Matrix Factorization is the reduction of a matrix into its constituent parts using linear algebra. Any matrix <strong>X </strong>can be reduced to a pair of factor matrices, <strong>A</strong> and <strong>Y</strong>, where <strong>X</strong> is the dot product of these matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*M-HRUeWOD_HCpXpJH6CTlA.png" /><figcaption>X matrix and A/Y as its factor matrices</figcaption></figure><p>There are tons of information about matrix factorization on the internet, so I do not elaborate on it. NMF is when all values, of both the matrix and its factor matrices are non-negative. See more information in<a href="https://en.wikipedia.org/wiki/Non-negative_matrix_factorization"> https://en.wikipedia.org/wiki/Non-negative_matrix_factorization</a></p><p>This post demonstrates:</p><p>1. How to implement the cross-validation for finding the best k latent features</p><p>2. How to handle the randomness of initial factor matrices</p><p>The following were the basis for my work:</p><p>1. A post by Alex Williams, from which I took the inspiration of the cross validation for NMF:<a href="http://alexhwilliams.info/itsneuronalblog/2018/02/26/crossval/"> http://alexhwilliams.info/itsneuronalblog/2018/02/26/crossval/</a>, and my post <strong>is actually a step-by-step implementation of that concept.</strong></p><p>2. A Stackoverflow answer by Tautvydas whose NMF optimization function was used as the basis of the code:<a href="https://stackoverflow.com/questions/22767695/python-non-negative-matrix-factorization-that-handles-both-zeros-and-missing-dat"> https://stackoverflow.com/questions/22767695/python-non-negative-matrix-factorization-that-handles-both-zeros-and-missing-dat</a></p><p>The code is written in Python, and is demonstrated on a Numpy array, but can be easily adapted to be used with a Pandas dataframe.</p><p><strong>What is ‘Latent Features’, and why do we need the right number of them?</strong></p><p>For a matrix <strong>X,</strong> there may be many possible pairs of <strong>A</strong>/<strong>Y</strong>, each pair varies in <strong>shape</strong> and <strong>values</strong>.</p><p>To focus the discussion on the <strong>shape</strong> element, let’s assume that <strong>X</strong> has <strong>m</strong> rows and <strong>n</strong> columns, as in the diagram above. Therefore the shape of <strong>A</strong> and <strong>Y</strong> should be <strong>m</strong> by <strong>k</strong> for <strong>A</strong>, and <strong>k</strong> by <strong>n</strong> for <strong>Y</strong>, where <strong>k</strong> may be any counting number (positive whole number).</p><p><strong>k</strong> represents the number of features of both <strong>A</strong> and <strong>Y.</strong> However, since we have only <strong>X</strong>, we do not know the size of <strong>k</strong>, and therefore we do not know the shape of <strong>A</strong>/<strong>Y</strong>. This is why the features represented by <strong>k</strong> are called <strong>latent features</strong>. In the diagram below we see different pairs of factor matrices <strong>A</strong>/<strong>Y</strong>, each with different <strong>k</strong>, all of them are valid matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*esKSPo4xvwtOcDLbKj6i8g.png" /></figure><p>To demonstrate what <strong>latent features</strong> are, let’s examine an example. There are many uses for matrix completion, however the most famous is the movie rating recommender system, based on <a href="https://en.wikipedia.org/wiki/Netflix_Prize">Netflix Prize</a>, where the users’ preferences are partially missing.</p><p>Below is an example for a completed matrix (the blue one), where the figures represent the users’ ranking, and the factor matrices embed some features, 3 in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*o6vK1XZcjK3qlyIiVXQT5g.png" /><figcaption>If John likes comedy, and the movies B,C,E are comedies, the algorithm may “assign” a feature to represent comedy preferences, since there is some supportive information for that.</figcaption></figure><p>Which <strong>k</strong> should we choose to use when we want to complete missing values in <strong>X</strong>?</p><p>A too small <strong>k</strong> may lack the information we need and will result in underfitting. Adding more features, in this case, can tell us more about the missing values.</p><p>A too high value for <strong>k</strong> might end up in overfitting. This is caused when we get multiple solutions, like in the following matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*zRAV4rGrW1oxqgSxVG2RYg.png" /><figcaption>The vector on the right does not provide any new information. It is just a linear combination of the rest of the vectors (x+y-z).</figcaption></figure><p><strong>Determining k is done by the cross-validation process.</strong></p><h4>Step 1- Generate Sample Data</h4><p>Here we create our own “missing data”. What’s behind it?</p><p>1. We want to create a full table, including the “missing values”, so we can really see if we got good completion at the end of the process for these values.</p><p>2. We want to generate the table from real <strong>A</strong> and <strong>Y</strong>, so we know what <strong>k</strong> is optimal and see if we get this as an output.</p><p>In the printed outputs, I used a small matrix (10 by 12), mainly for presentation convenience. However to see a real effect of the cross-validation we need a larger matrix, so all the plots were taken from a 40 by 25 matrix. Both matrices had 5 latent features.</p><p><strong>Note that k must be smaller than the minimum of the matrix’s rows/columns, otherwise we have multiple solutions.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfb991e3309e4b304c067da2aa4da29f/href">https://medium.com/media/cfb991e3309e4b304c067da2aa4da29f/href</a></iframe><p>The output (for 10 by 12):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4FITUn-w9nmNuvA5" /></figure><p>Now we create nulls randomly to simulate the real “missing values”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ff8f0a04d66253cf3cb8278a5201d5d/href">https://medium.com/media/9ff8f0a04d66253cf3cb8278a5201d5d/href</a></iframe><p>The output (for 10 by 12):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AlPg6qgK-th63eu9" /></figure><p>From now on, the code is relevant for a real matrix with missing values.</p><h4>Step 2 — Preparation phase</h4><p>First, we create the null mask. It is required for the last step where we complete the missing values with the resulted matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba23c522d24bf1e25f2b31fe24c85e43/href">https://medium.com/media/ba23c522d24bf1e25f2b31fe24c85e43/href</a></iframe><p>Now we add 1 (or any other number) to the matrix. Why is that?</p><p>The learning phase begins with filling the nulls with 0, so we want to distinguish between the real zeros and the nulls-filled-with-zero.</p><p>Of course, this is only relevant if you have zeros in your matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03759a06c0c201cfd56f41a2376fc989/href">https://medium.com/media/03759a06c0c201cfd56f41a2376fc989/href</a></iframe><h4>Step 3 — Fold Preparation</h4><p>In any cross-validation we split the data such as some of it is being fitted on, and the rest of the data is used for testing.</p><p>Here we partition the data matrix into four folds, where each fold serves as a held-out set for testing at its turn. The matrix is split in half vertically and horizontally, as in the diagram below.</p><p>This meets a basic requirement that the fitted area should spread out over all the rows and columns, otherwise, the algorithm doesn’t have the right data to learn from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*KJbbidxIOhW-jFJt4AlYOg.png" /><figcaption>On the left-hand side: split to 4 folds. On the right-hand side: fold 1 as test set, the other folds as train set.</figcaption></figure><p>We get the train and test errors for each fold, and then we use their average.</p><p>I used 4 folds. However, one may use a different number of folds and even develop it to be a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f17df9c90cb4f4a4edae456816739721/href">https://medium.com/media/f17df9c90cb4f4a4edae456816739721/href</a></iframe><p>Applying the function on our matrix produces the train and test sets, as well as 0/1 masks per each set. For example, with fold=2, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*MWt2hXpnZt5PDon3" /></figure><p>These masks are for the folds only, and not yet include the null-mask. This will be combined together with the fold-mask into one on the next step.</p><h4>Step 4 — Cross-Validation</h4><p>The cross-validation function is relatively long, so first I write its main components as a short algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*oojYazfzE6Eidw5-BYu7Hg.png" /><figcaption>Cross-validation algorithm flow</figcaption></figure><p><strong>Why do we split each fold into several cycles?</strong></p><p>The learning process starts by assigning random values to one of the factor matrices <strong>A</strong> and <strong>Y</strong>. Then during the learning process, the matrices are updated till we reach the optimum.</p><p>However, we do not know if the random matrix we start with will lead us to the absolute optimum or only to a local one.</p><p>So here we try out several initiation random matrices in several cycles and take the <strong>end matrices</strong> of the best cycle. Note that our best cycle is the one with the lower <strong>train error </strong>(not the test error) since this is still a part of the fitting phase and not the testing.</p><p>The diagram below describes several cycles of <strong>one fold</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYpkflqpF3sC9OeZ1zk-Lg.png" /><figcaption>The matrices that are surrounded by a green line are taken to be used on the actual learning with the already optimized <strong>k</strong> (see step 7).</figcaption></figure><p>The full cross-validation function has a few parts. The main ones are presented below. The rest can be found in the full notebook that is referred to at the bottom of the post.</p><p><strong>First part: preparation per fold</strong> — is where we prepare mainly the mask per fold.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d70ce5de7868a8736cad53829ba4ddcc/href">https://medium.com/media/d70ce5de7868a8736cad53829ba4ddcc/href</a></iframe><p><strong>Second part: matrix initiation</strong> — initiates Y, A, X (masked) per cycle. Also initiates the train and test errors values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7bd3b530f8f53c68cc0caf3ce053532/href">https://medium.com/media/c7bd3b530f8f53c68cc0caf3ce053532/href</a></iframe><p><strong>Third part: update</strong> — learning process where <strong>A</strong>, <strong>Y</strong> and <strong>X</strong> are being updated per iteration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7979b3d7761736efdd69ca1f371d644d/href">https://medium.com/media/7979b3d7761736efdd69ca1f371d644d/href</a></iframe><p><strong>Fourth part: conclusion</strong> — collect all results, elect best cycle per fold and average folds errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/214eb2f66d25816ab85eab5c5714a64c/href">https://medium.com/media/214eb2f66d25816ab85eab5c5714a64c/href</a></iframe><h4>Step 5 — Run multiple <strong>k</strong></h4><p>Here we use the nmf_cv function for different <strong>k</strong>s. During the learning, we can follow the train and test errors per cycle, and a plot for the best cycle per fold.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa30e080c221f79a7045a43332c08c61/href">https://medium.com/media/fa30e080c221f79a7045a43332c08c61/href</a></iframe><p>Below are three representative plots and respective errors — for underfit (too low <strong>k</strong>) on the left-hand side, right <strong>k</strong> in the middle, and overfit on the right-hand side. Notice the differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*RqVMrFl_KfypoLgJ" /><figcaption>Difference in train and test error per k.</figcaption></figure><p>Then we extract the best run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d6b6e4c277db4c32faeb3c9ac9bc55b/href">https://medium.com/media/5d6b6e4c277db4c32faeb3c9ac9bc55b/href</a></iframe><p>The following plot shows the train and test errors per <strong>k</strong>. As we could expect, the best <strong>k</strong> is 5, due to the latent features we picked when creating the sample data on step 1. In real data we don’t know this number of course.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*XeQ9HJ1UiowloFWZ" /></figure><p>For some of the <strong>k</strong>s (for example k=8), the test error is very high, and seem to divert from the “perfect” test error curve. To overcome this issue, one may use square root or log over the matrix, to reduce the numbers and by that “control” the error.</p><h4>Step 6 — Capturing <strong>A</strong> and <strong>Y</strong></h4><p>As discussed earlier, a given matrix <strong>X</strong> may have totally different factor matrices, not only in shape, but also in their values. So we may end up the training process in similar <strong>X</strong> matrices for the different folds, but very different <strong>A</strong> and <strong>Y</strong>. See example on a 2 by 2 matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*sJY0g0NYS1K2f_YebjNh5g.png" /><figcaption>Different sets of factor matrices for the same X matrix.</figcaption></figure><p>This means that we cannot just average All <strong>A</strong>s or <strong>Y</strong>s. The alternative is to use one of the pairs (for example <strong>A</strong> and <strong>Y</strong> from fold 0).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b8d6d0af1178b5d5e20b66301d9b357/href">https://medium.com/media/4b8d6d0af1178b5d5e20b66301d9b357/href</a></iframe><h4>Step 7 — Train with Optimized <strong>k</strong> and Captured <strong>A</strong>/<strong>Y</strong> Matrices</h4><p>This is the step that we actually use the cross validation results:</p><p>- We use the optimal k (implicitly only, the shapes of <strong>A</strong>/<strong>Y </strong>assume the right <strong>k</strong>)</p><p>- We use the end A/Y matrices. Since these are the end matrices, we do not have to use very high number of iterations.</p><p>The function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38f85465e02fe56ebf5a71b242d97a72/href">https://medium.com/media/38f85465e02fe56ebf5a71b242d97a72/href</a></iframe><p>And we get the predicted matrix. We can compare the original matrix with the predicted one (top left corner of both) and the error on the <strong>non-null</strong> values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dd64d1fb23a6a9837ef6fc316d296b2/href">https://medium.com/media/1dd64d1fb23a6a9837ef6fc316d296b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EYSmxpE-VAS1Q4dO" /></figure><p>And now the original:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c81c9e99a39092b0bc5dd52ca9fac68/href">https://medium.com/media/5c81c9e99a39092b0bc5dd52ca9fac68/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*LhNyuWI6hA7rrSVk" /></figure><h4>Step 8 — Examine Nulls Error</h4><p>Since we know the missing values (we created the original matrix), we have the opportunity to examine how well the algorithm managed to predict the missing values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57b572fedfdd26a7c50e7cf240fcd0fb/href">https://medium.com/media/57b572fedfdd26a7c50e7cf240fcd0fb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gX70si_eLZjvte4a" /></figure><p>And now the original:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1de1b4bcbaad93bd7b8d4c52c33e2a92/href">https://medium.com/media/1de1b4bcbaad93bd7b8d4c52c33e2a92/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*JfSiG9dajt0k17f4" /></figure><h4>Step 9 — Merging the missing value from the NMF</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5df92f5addbb8e5520d2ecec13215f3/href">https://medium.com/media/f5df92f5addbb8e5520d2ecec13215f3/href</a></iframe><p>And here we get the completed matrix.</p><h4><strong>Recapping</strong></h4><p>Without the cross validation we couldn’t have known the <strong>k</strong> latent features to be used, and will have gotten better <strong>train</strong> performance for any higher <strong>k</strong>, since we use all the data.</p><p>In addition, random matrices might lead us to local optimization point and not to the best one. By using the end <strong>A/Y</strong> matrices from the best run, we ensure that we reach the minimum error.</p><p>One may use this code as is or modify it in accordance for specific needs, for example with another algorithm.</p><p>The full notebook can be found in <a href="https://github.com/IshayTelavivi/cross_validation_matrix_completion/blob/master/cv_for_nmf_sample1.ipynb">https://github.com/IshayTelavivi/cross_validation_matrix_completion/blob/master/cv_for_nmf_sample1.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b14103d2c4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-use-cross-validation-for-matrix-completion-2b14103d2c4c">How to Use Cross-Validation for Matrix Completion</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>