<?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 David Blanar on Medium]]></title>
        <description><![CDATA[Stories by David Blanar on Medium]]></description>
        <link>https://medium.com/@david.blanar?source=rss-c43743e2cbe0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VVOGxeOWzgkZyp_RUUeVoA.jpeg</url>
            <title>Stories by David Blanar on Medium</title>
            <link>https://medium.com/@david.blanar?source=rss-c43743e2cbe0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:02:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@david.blanar/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[Predicting Nutritional Contents of Meals Using Deep Learning]]></title>
            <link>https://medium.com/@david.blanar/predicting-nutritional-contents-of-meals-using-deep-learning-c455e175b601?source=rss-c43743e2cbe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c455e175b601</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[nutrition]]></category>
            <dc:creator><![CDATA[David Blanar]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 16:09:59 GMT</pubDate>
            <atom:updated>2023-04-27T16:23:33.928Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p><strong>Nutrition5k</strong> is a 2021 <a href="https://arxiv.org/pdf/2103.03375.pdf">paper</a> and an open source <a href="https://github.com/google-research-datasets/Nutrition5k">dataset</a> created by Google researchers as a first stepping stone towards machine learning algorithms capable of in-depth nutritional understanding of food. The dataset contains around 5000 meals with associated mass, calorie and macronutrient content (i.e. protein, fat and carbohydrates). Each dish is additionally broken down into ingredients with the mass, calories and macronutrients of each ingredient provided.</p><p>Video recordings and overhead pictures of each meal are also provided. The meals range from plates of a few tomatoes to dishes containing more than a dozen ingredients with thousands of calories. The dishes were assembled and recorded incrementally with each major ingredient being added in turn, videos and pictures taken, and with the corresponding mass, calories and macronutrients recorded in the metadata files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fS_-1qHq0tVczT69DJq1w.png" /><figcaption>Incremental meal scanning, picture taken from the Nutrition5k paper (Figure 11)</figcaption></figure><p>I found the dataset by chance and was intrigued by the fact that it is (as of the time of this writing) the only public dataset of its kind. There are similar datasets but none of them offer the depth and detail of Nutrition5k. Many of these datasets are more geared toward classifying pictures of food into distinct categories and most contain too few meals or ingredients to reliably achieve macronutrient estimation. Immediately upon stumbling across it, I could see the usefulness for people struggling with weight loss, diabetes or for fitness and nutrition enthusiasts. Since the model itself was never published, I decided to give it a shot and reimplement the paper.</p><p>The dataset is composed of metadata files with calorie and macronutrient information for each dish, overhead pictures and roughly 190 GBs of 1080p video recordings from overhead mounted rotating cameras capturing each meal from 4 different angles.</p><p><strong>Data exploration &amp; preprocessing</strong></p><p>The first order of business was to extract images from the videos to be able to train a CNN. The authors used <strong>ffmpeg</strong> to extract every fifth frame, however that seemed like overkill to me. Watching a few of the videos revealed that most of the time the cameras are stationary and only rotate every few seconds. Extracting every fifth frame meant 5 images per each second of video (assuming 25 FPS), most of them identical. I decided to instead select every 25th frame for roughly 1 image per second. This captured the various angles without creating a gazillion images from every video, expediting the extraction and later the training process.</p><p>Another thing I noticed was the fact that some of the videos were seriously broken. Most of them were less than 25 seconds in length but some of them ran for minutes, one for almost an hour. Investigation showed that sometimes the crew recording the dishes simply forgot to turn off the cameras.</p><p>Luckily, for virtually all videos the first 25 seconds were the most important, so I capped the image extraction to the first 25 seconds of each video. This is easier said than done as I needed to first convert each video from h264 to mp4 to then be able to get the duration of the video (otherwise ffmpeg was unable to read it), cut the video to appropriate length and then extract the pictures.</p><p>Next, I resized the images to 320x320 pixels, deviating from the 256x256 used in the paper. I did the same to the overhead images provided in the dataset. This part was easy thanks to Python’s <strong>Pillow</strong> library for image processing.</p><p>After that I took a look at the metadata files themselves. These are CSV files with rows corresponding to each dish and columns containing mass, calories, macronutrients and the nutritional breakdown of each dish. With a little bit of processing I transformed the data into a pandas dataframe, keeping only items containing the top 75 most common (by mass) ingredients. Any less than that and some very common ingredients such as chicken breast were left out, causing the model accuracy to deteriorate. On the other hand, keeping all of the ingredients made the model look for barely visible things such as salt, pepper, olive oil, etc. Some ingredients were outright filtered out on the basis that they don’t contribute much to the nutritional breakdown of the dish and are present in pretty much every item (such as the aforementioned salt).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juU9iUiHbtqdIVBXEEFwKg.png" /><figcaption>The data after processing</figcaption></figure><p>Next, I filtered the data to only include labels for the top 5 ingredients which represented the largest percentage of the mass of the dish. The reasoning was that if a particular dish is made up of 10 different ingredients, there really isn’t any point in letting the model struggle to take into account a single olive in a dish with 1000 calories worth of rice and pork. Moreover, the paper states that there are on average 5.7 ingredients per dish so 5 seemed like a reasonable number. The data was then split into train and test sets according to the split provided with the dataset.</p><p><strong>Training the model</strong></p><p>With the data assembled, I proceeded to train an EfficientNet V2 B0 model on the images of the food to get a model capable of recognizing the makeup of a dish. <strong>Tensorflow</strong> was used for training and the model was loaded with weights pre-trained on the Imagenet dataset. Retraining the entire network was necessary as my experiments showed that by default the pre-trained model wasn’t capable of recognizing the ingredients very well as the Imagenet dataset contains a generic set of categories not particularly geared towards food recognition.</p><p>The overall architecture is very similar to the one used in the paper, albeit smaller. This was done to facilitate training on regular hardware as I trained the model on my laptop’s GPU. I settled on a learning rate of 0.00001 and using the Adam optimizer with binary cross-entropy loss, deviating from the paper which used RMSProp.</p><p>I used various techniques to try to get the model to train as well as it could, chief among them being data augmentation to combat the limited variability of the dataset. Another trick was to make the images larger, hence why I resized them to 320x320. The idea was that more pixels would allow the CNN to pick up on more patterns and achieve better accuracy.</p><p>The final model was able to categorize dishes with a precision of 78.8% and recall of 63%. Given the difficulty of the task (i.e. oftentimes some ingredients were obstructed by others and the ingredients varied wildly), I was unable to push the model further in the time I allotted myself.</p><p>The next step was to train a model to predict mass, calorie and macronutrient makeup of a dish from a picture. The previously trained EfficientNet V2 B0 architecture was used as a base model and two models were trained — a portion independent model where the macronutrients were divided by the mass of the dish and a direct regression model which tried to predict the mass and macronutrients directly without any outside reference.</p><p>Notably, I ended up getting rid of calories altogether and instead decided to calculate the caloric content from the predicted macronutrients themselves (since carbohydrates and protein are about 4 calories per gram and fat about 9 calories per gram). The architecture is once again pretty much the same as in the paper with only minor tweaks to the size of the individual layers.</p><p>In both cases I selected a learning rate of 0.00001 and used the Adam optimizer. Mean absolute error was selected as the loss metric in accordance with the paper.</p><p><strong>The results</strong></p><p>The final results of evaluation on the test set can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0fc6q7a9kOqS2p6BfcrwA.png" /><figcaption>* Results from the Nutrition5k paper; ** Models were evaluated on the entire test set; *** Models were evaluated on the test set with outliers removed (outliers being dishes with mass or calorie content greater than 99% of the dataset)</figcaption></figure><p>As can be clearly seen, the models underperform when compared to the original trained by Google researchers. To come closer I needed to make a few shortcuts, such as evaluating the models on the test set with outliers removed. Part of it is due to the fact that the original model used a much larger InceptionV2 architecture pre-trained on JFT-300M, a closed source dataset containing more than 300 million images in ~18000 classes (and part of it can also be attributed to the fact that, surprise surprise, I’m not a Google researcher).</p><p>The portion independent model is more accurate than the one attempting a direct regression of macronutrient contents from just a picture of a meal. This is expected and consistent with the findings in the paper. However, it is much less useful as in most real-world situations the exact mass of a dish is not known.</p><p>The main performance bottleneck is the image recognition part. My experiments have shown that when the model recognizes the contents of the plate very well the macronutrient and mass regression tends to be very accurate. As is often the case, improvements could be achieved by using larger datasets, however assembling comprehensive imagery along with detailed breakdowns of each dish is a challenging and time consuming task, as the authors of the paper admit.</p><p><strong>Conclusion &amp; next steps</strong></p><p>Since the image recognition part seems to be the main problem, the next step would be to try to get more labeled food data and try training the base model again. Embedding the model into a mobile device in order to be able to quickly snap a photo and run it through the model would be also an interesting idea to pursue, however right now the generated models are too large (~400mb each) despite the fact that a relatively small architecture was used.</p><p>If you want to take a look, feel free to check out my <a href="https://gitlab.com/davidblanar/nutrition5k">Gitlab repository</a> or read the original paper. Please note that the repository is quite large as it contains the model weights as well as some preprocessed data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c455e175b601" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Computing Made Easy with Dask]]></title>
            <link>https://medium.com/@david.blanar/distributed-computing-made-easy-with-dask-2df8f67e9a30?source=rss-c43743e2cbe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df8f67e9a30</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[David Blanar]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 16:15:10 GMT</pubDate>
            <atom:updated>2022-06-13T16:15:10.530Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of the time software engineers deal with relatively small data. Read some records from a database and display them to the user here, perform some simple calculations there, maybe process a small file every now and again. As long as the data fits comfortably into memory, everything is sunshine and roses.</p><p>However, sometimes you need to process large chunks of data. Maybe you’re a Machine Learning engineer who needs to process millions of rows of user-generated data before feeding it into a model, maybe your company gave you some CSV files to extract some information from using Pandas except each of the files is 30 gigabytes in size.</p><p><strong>Almost a drop-in replacement for Pandas</strong></p><p>If you’re familiar with Pandas, Dask will feel very natural to you. It effectively mirrors the Pandas API with some rare caveats. This makes Dask a perfect candidate to be an almost drop-in replacement for Pandas with very few code changes necessary.</p><p>In addition, the biggest selling point of Dask is that it allows distributed computation. If your data is too large to fit into memory, it allows you to process the data in chunks, only loading each partition into memory as needed before processing it or saving it to disk. This gives Dask the ability to process files of almost any size in a multi-threaded fashion.</p><p><strong>A simple example in Pandas</strong></p><p>To illustrate the power of Dask and the similarity between the two APIs, let’s write a simple program that reads some data from a file, processes it and saves the result into another file. To do this we’re going to use a publicly available <a href="https://www.kaggle.com/datasets/zanjibar/100-million-data-csv">dataset</a>.</p><p>The 4.5GB CSV consists of trade statistics provided by the Ministry of Finance of Japan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b23ni4ENhR9YeGRXnNorQ.png" /><figcaption>Trade data with renamed columns</figcaption></figure><p>First let’s load up the data into a Pandas dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94bdd8a5edcbecfd1e5d0a6393817234/href">https://medium.com/media/94bdd8a5edcbecfd1e5d0a6393817234/href</a></iframe><p>Oops! The entire file is now loaded into memory and is using ~7GB of RAM. Not good. Nevertheless, let’s try and process it anyway, calculating the balance of imports vs exports for every year.</p><p>We’ve already renamed the columns as the original CSV doesn’t contain understandable column names. We can see that the date is a combination of year and month, so our first order of business is to split it into separate columns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/164b6ba66f2dce89c67bc4aff9a1b465/href">https://medium.com/media/164b6ba66f2dce89c67bc4aff9a1b465/href</a></iframe><p>Ouch! The memory consumption actually jumps to &gt;20GB and the computer is not happy. Let’s try a smaller file so that we don’t risk crashing the machine. We’ll use a file generated from the original by sampling only 10% of the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9685e86147188cd05bf826fce572288e/href">https://medium.com/media/9685e86147188cd05bf826fce572288e/href</a></iframe><p>Now after adding the month and year columns the program is consuming “only” ~4GB of memory. Let’s split the dataframe into imports and exports and calculate yearly sums.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1c5e063ff8d3f7260cb93b7b6bb3440/href">https://medium.com/media/a1c5e063ff8d3f7260cb93b7b6bb3440/href</a></iframe><p>Finally, let’s join the data together and subract imports from exports to get the overall balance and save it into a file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/730f0c50085e2e9b3ca4aff84692c3b5/href">https://medium.com/media/730f0c50085e2e9b3ca4aff84692c3b5/href</a></iframe><p>We got our result, however we needed to use only 1/10th of the data, otherwise the task proved too much for the computer. Surely the answer can’t be to simply use small datasets or pay exorbitant sums of money for memory when running computations. A different approach is needed.</p><p><strong>Dask to the rescue</strong></p><p>Let’s recreate the above steps but this time let’s use Dask.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82b09bb90dfa1c7aa6e0ec50248a19c1/href">https://medium.com/media/82b09bb90dfa1c7aa6e0ec50248a19c1/href</a></iframe><p>First we need to initialize a Dask distributed client and set some constraints on memory and CPU cores, otherwise Dask would happily eat all the available RAM. Then we load the data and set a blocksize of 25MB. Since we’re working with a single large CSV file in this fashion we can tell Dask to load the file in chunks.</p><p>The rest of the code looks very much the same with the exception of the last line where we tell Dask to store the output into a single file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e755d0c3ce5a113b472b2a9d751f51/href">https://medium.com/media/f2e755d0c3ce5a113b472b2a9d751f51/href</a></iframe><p>We can then verify that we’ve obtained the same result while the memory consumption never went above 700MB!</p><p>Dask accomplishes this by loading the data in chunks and applying the necessary changes to each partition before assembling the final result. The computations are not executed until we instruct Dask to do so, which is what happens when we call .to_csv(). The rest of the code is just telling Dask which tasks to execute on each partition.</p><p>Finally, if we run our code on the larger file that gave Pandas such trouble, we’ll find that Dask processes the file just fine and the memory consumption never exceeds 700MB.</p><p><strong>Conclusion</strong></p><p>We’ve shown how Dask can process large datasets in a distributed and memory efficient manner. The example above used a 4.5GB file but Dask is capable of much more. The complete code can be found <a href="https://github.com/davidblanar/dask-computing">here</a>.</p><p>Unfortunately, not all is roses with Dask. As of the writing of this post it still doesn’t support multiple indexes on a dataframe. In addition, there are several inconsistencies between the Dask and Pandas APIs, but these are usually trivial to work around.</p><p>Ultimately, Dask is just another tool in a Software Engineer’s toolbox. Most of the time if the data is small using Pandas is faster and more convenient. However, if you’re ever in a situation where you need to process large amounts of data, Dask might be just the thing for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df8f67e9a30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimising Content Discovery via Probabilistic Machine Learning]]></title>
            <link>https://medium.com/filmzie-tech/optimising-content-discovery-via-probabilistic-machine-learning-6a7e7b4eac1a?source=rss-c43743e2cbe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a7e7b4eac1a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[streaming-video]]></category>
            <category><![CDATA[filmzie]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <dc:creator><![CDATA[David Blanar]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 10:02:12 GMT</pubDate>
            <atom:updated>2022-02-18T10:02:12.407Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Presenting users with interesting movies is an essential strategy for any successful streaming platform. It drives more user engagement, increases user retention and viewing time, and, at the end of the day, brings in more revenue. While there are many techniques for optimisation, be it interesting artwork or intuitive app design, this post focuses on ways of ordering video content such that it makes the movie library more appealing to the user.</p><p><strong>The problem of scale</strong></p><p>As with many problems, the simplest and fastest solution is often to let a human do it. Indeed, that is what happened at Filmzie in its very beginning. We employed people who divided our movie library into categories and managed the order of the content in every category so that the user would see — what we believed were — the most appealing entries first. This was done on a per-country and per-platform basis, our platforms being iOS, Android, web and CTV.</p><p>This was easy enough when there was only a limited amount of content and countries to serve, however, as Filmzie’s movie library grew and our presence in various parts of the world expanded, this became unmanageable. There were simply too many permutations of country, platform, category, and content for a human to process, making the solution unscalable. A decision was made to automate everything, encountering various interesting challenges along the way.</p><p><strong>A look at the data</strong></p><p>As part of our service, we collect data on how much content was streamed, which country it was watched in as well as various other metrics. Here is an example of our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ujrWL-pjlBJcBKR5-eH7Q.png" /></figure><p>We’ve discovered that our library very much follows the Pareto principle — a vast majority of our content has only been watched a couple of times, giving us little data to determine whether the movies would be appealing or not, all the while most of our watch time comes from a small selection of very popular movies.</p><p>In addition, simply ordering by the sum of minutes watched would not be enough. A film that was watched 5 times and accumulated 500 minutes surely performs better than a film that was watched 100 times and accumulated 1000 minutes. A more sophisticated approach was needed.</p><p><strong>The problem of discovery</strong></p><p>Another issue we had to deal with was discovery. Suppose the machine works and then we add a new movie. That movie will essentially have a score of 0 as it has never been watched before. How can we tell the machine to “favour” some films while still allowing it to intelligently sort the rest of the content?</p><p>This leads to a more general issue — what if some films are genuinely good but for some reason they have a low score and, therefore, will never be put at the front of the queue where users can discover them more easily? Clearly, we need to introduce a little bit of randomness into the process.</p><p><strong>A probabilistic solution</strong></p><p>We started by assembling all the data and dividing it by country and platform, essentially creating an entry for every combination of content, country, and platform. We then calculated the total amount of viewed minutes and how many times a particular film was viewed.</p><p>Subsequently, we fed the ratio between the two into a Poisson prior. Using a probabilistic approach solves the issue of randomness and discoverability as it allows the machine to “make mistakes” and sometimes favour a film that doesn’t have a particularly good score. However, the higher the ratio, the more probable it is for the machine to put the film forward. Indeed, most of the time the algorithm places the most popular movies first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*QH_AE0X8BEYbXtrnInUyAg.png" /><figcaption>Source: <a href="https://upload.wikimedia.org/wikipedia/commons/1/16/Poisson_pmf.svg">Wikipedia</a></figcaption></figure><p><strong>And the results are in</strong></p><p>We let the machine fully manage content for several weeks to allow it to learn the most optimal way of ordering our library and reduce any bias introduced by spikes and drops in view time due to holidays and other real-world events.</p><p>Upon evaluation, we discovered that our overall view time increased by roughly 15% while we saved hundreds of hours of manpower. Interestingly enough, countries such as USA and the UK, which were particularly managed by humans, did not see an increase, suggesting that the machine can sort the library similarly well as a human can, however it does this for all the countries and platforms as opposed to just a few.</p><p><strong>Conclusion</strong></p><p>We’ve managed to solve the issues of scale and discoverability using Machine Learning, saving precious human work. The entire process of extracting the data, training the model, and deploying it to production is entirely automatic — no human input needed at all.</p><p>The model itself is not ground-breaking. Our team at Filmzie is convinced we could improve the performance even further by using a conjugate Gamma-Poisson model instead. This is, in fact, on our road map. However, it goes to show how much of an improvement can be achieved with a relatively simple application of machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a7e7b4eac1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/filmzie-tech/optimising-content-discovery-via-probabilistic-machine-learning-6a7e7b4eac1a">Optimising Content Discovery via Probabilistic Machine Learning</a> was originally published in <a href="https://medium.com/filmzie-tech">filmzie-tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>