<?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 Maciej D. Korzec on Medium]]></title>
        <description><![CDATA[Stories by Maciej D. Korzec on Medium]]></description>
        <link>https://medium.com/@korzec?source=rss-661e2473471a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*02cDtvSwvA5yg4QwHbN6fQ.png</url>
            <title>Stories by Maciej D. Korzec on Medium</title>
            <link>https://medium.com/@korzec?source=rss-661e2473471a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:38:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@korzec/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[The Core Value of Recommender Systems for Successful Internet Enterprises]]></title>
            <link>https://medium.com/swlh/the-core-value-of-recommender-systems-for-successful-internet-enterprises-7164a7bacdc6?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7164a7bacdc6</guid>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Sat, 31 Oct 2020 04:18:57 GMT</pubDate>
            <atom:updated>2020-10-31T21:48:11.924Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>An assessment of the importance of recommender systems</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*gWnfMilyrr4JQP_cAk-utQ.png" /><figcaption>(Source: Combined Unsplash sources <a href="https://unsplash.com/photos/lRoX0shwjUQ">@jankolar</a> and <a href="https://unsplash.com/photos/1K6IQsQbizI">@franki</a> by the author)</figcaption></figure><p>Most users are aware of the existence of individualized recommendations on large internet platforms, e.g. by using Amazon and noting the <em>You might also like</em> features. However, the importance and dominance of this technology within big data platforms is maybe more crucial than many might think:</p><blockquote><strong>70% of the 30 largest internet companies use recommender systems within their core business.</strong></blockquote><p>During the preparation for a talk on the Netflix architecture I learned that nearly all the features on the streaming platform are individualized. It aroused my interest in this topic in general. Netflix tries to recommend the most relevant movies, series, advertisements, and overall page to the users. From a set of dozens of images from one movie it even selects one that is most likely clicked. Netflix has a great <a href="https://netflixtechblog.com/">tech blog</a>, where you can find all kinds of information about the platform.</p><p>My interest in the technical details grew, and it resulted in a series of articles about recommending similar images with help of convolutional networks (part <a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb?source=your_stories_page-------------------------------------">1</a>, <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=your_stories_page-------------------------------------">2</a>, <a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d?source=your_stories_page-------------------------------------">3</a>, <a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b?source=your_stories_page-------------------------------------">4</a>). The question arose, how prominent recommender systems are for large internet companies.</p><p>This topic is addressed today. For this article the 30 largest internet companies by revenue were analyzed with respect to usage of recommender systems, and we can note that</p><ol><li><strong>successful internet companies rely on the cloud and big data catalogs</strong></li><li><strong>to compete with other players, and efficiently use data, they must use recommender systems whenever applicable — mostly based on machine learning</strong></li></ol><p>Let us continue with the results of the evaluation before giving an idea what recommender systems are, explaining their competitive role and concluding with a discussion on the importance on the core business of these companies.</p><h3>The top 30 internet companies</h3><p>For the following analysis, the 30 largest internet companies by revenue were considered. The revenue numbers are mostly from 2019, so that the Covid19 effect is not reflected — e.g. Expedia’s revenue dropped drastically since then.</p><p>Let us first have a look at the distribution of these companies by country:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*1cQON2UcRluij9hQfu4W6Q.png" /><figcaption>Top 30 internet companies country distribution (Source: Diagram by the author, numbers from this <a href="https://en.wikipedia.org/wiki/List_of_largest_Internet_companies">list</a> — 19th of October 2020)</figcaption></figure><p>What strikes most is that only 7% of these companies (2) are from Europe, the portion is unchanged when considering the top 100 — it reflects the failure in digitalization of a whole, developed continent — and that the core players in AI, USA and China, indeed benefit from this expertise.</p><p>The next diagram shows which of these companies rely on recommender systems within their core business (major revenue stream):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*X3cbfDQcLnXPllL1eSKUZQ.png" /><figcaption>Usage of Recommender Systems within the top-30 internet companies (Source: Diagram by the author, top 30 companies from this <a href="https://en.wikipedia.org/wiki/List_of_largest_Internet_companies">list</a> were evaluated— 19th of October 2020)</figcaption></figure><p>There are companies like PayPal, where recommender systems are not crucial for the overall core business. However, the majority, products with huge user bases, data, or catalogs, need the technology to fully benefit from running a big data platform. And these systems are driving internet companies nowadays. Hence it is not surprising that 70% of the companies incorporate recommender systems within their core revenue stream.</p><p>You can find the table with the companies and assessment in the <em>Resources</em> section at the end of the article.</p><h3>How recommender systems improve market shares</h3><p>When Petabytes of data have been collected, only one point is certain: The data accounts for significant costs for storage and computations.</p><p>Everything else depends on very many business and technical expertise factors. The successful data-related companies from the top-30 list do have a solid business plan and the expertise to harvest the data. Those with a huge catalog are all able to benefit from the long tail.</p><p>One should not forget the business goals when working with big data. Therefore, let us have a look at two citations from Peter Thiel’s book on success for start-ups [1]</p><blockquote><em>“Monopoly is the condition of every successful business.”</em></blockquote><blockquote><em>“A good business takes advantage of the complementarity between computers and humans, using both machines and human employees to solve problems.”</em></blockquote><p>This is exactly the complementarity recommender systems are offering, computers create possibly good selections, and users decide if the computer made indeed a good guess — which it often does.</p><p>In a traditional offline shop, one tries to offer the most popular items, to maximize the number of sales</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*446BPm_mfTf4gdFX-acVXg.png" /><figcaption>The long tail (source: the author)</figcaption></figure><p>Consequently, the less popular items are never sold. On platforms that can work with a huge warehouse (digital or analog) not offering the individually most popular items can lead to churn or non-conversion.</p><p>Recommender systems have the goal to find individual interests (individual popularity). Then the users also see only a fraction of the whole catalogue, but it is hopefully the most popular fraction in each user’s eyes. In this way revenue is created from the long tail depicted above, the overall not so popular items. The probability increases that a user does not churn. If he can find a satisfactory item, he is unlikely to look out for other sites.</p><p>The explanation of the importance for preventing churn is described by the following, simplifying calculation: If you have two platform competitors with the same catalog and strategy, but the first one has a much better recommender system, it is quite sure that users will tend to churn less from the platform with the good recommender.</p><p>Assume:</p><ul><li>Companies <strong>A</strong> and <strong>B</strong> have both 100 units of customers</li><li>Probability to churn within a year <strong>A</strong> to <strong>B</strong> is 10%</li><li>Probability to churn within a year <strong>B</strong> to <strong>A</strong> is 20%</li></ul><p>To calculate the distribution after n years without taking into account any other effect, consider the calculation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*ZNv1Slr3YhMvXeReJxo3hA.png" /></figure><p>After five years (n=5) this gives:</p><ul><li>Customer units of A: 128</li><li>Customer units of B: 78</li></ul><p>Hence by considering churn alone with one competitor, <strong>A </strong>wins the market by a significant margin and starts creating the desired monopoly. Now <strong>B</strong> can try to get more new customers, but the cost of customer acquisition is much higher than the cost for keeping a customer — in the long run the battle will be lost as <strong>A </strong>generates more cash flow and adds additional positive effects. If all other competitors together stay at 100 units and have a 20% yearly churn this is even better for <strong>A</strong>.</p><p>This is the reason why Netflix has always been happy with a &lt;10% churn rate while the average for over the top content is estimated to be around 20%. Feel free to check-out their nonlinearly growing subscribers numbers <a href="https://www.statista.com/statistics/250934/quarterly-number-of-netflix-streaming-subscribers-worldwide/">here</a>, approaching the 200 million mark in the end of 2020.</p><p>Of course, content is key, without it, no recommender in this world will help and no monopoly will be established. But you may fail with the best content, as this is just essential programmatic marketing.</p><p>In general, recommender systems are divided into collaborative, content based and hybrid systems, and based on the use-case of the platform one needs to decide what fits best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tAVZ5U_oIkG084mE-xbSw.png" /><figcaption>Main types of recommender systems (source: the author)</figcaption></figure><p><strong>Example for a collaborative recommender system:</strong></p><p>Whenever you read phrases like <em>users who bought x also bought y,</em> a collaborative recommender system is running. It tries to find a neighborhood within the set of all users that has a similar interest in items that you have. It relies on the collaboration of the users, hence the name.</p><p><strong>Example for a content-based recommender system:</strong></p><p>Recommending the most similar images from a large set of images, based on machine generated similarity is an example for a pure content-based recommender system. I wrote about it in my first post on Medium <a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb?source=your_stories_page-------------------------------------">Effortlessly Recommending Similar Images</a> and three follow-up articles that resulted in a demo app that you can access <a href="https://image-recommender-demo.herokuapp.com/">here</a>.</p><p><strong>Example for a hybrid recommender system:</strong></p><p>The recommendations on Netflix are hybrids. The system uses all it can get, metadata of the titles, individualized images (content based) and other users’ behavior and taste to suggest movies and series that the user shall click.</p><h3>A/B testing</h3><p>How do you measure success when there are so many degrees of freedom? After a data scientist created a recommender system that works with some sample data, it is still not guaranteed that it gives statistically relevant benefit in production. Carrying out A/B tests (or A/B/C/D/ …) is hence mandatory, starting with a metric for success that all stakeholders can agree upon. This essentially means that software with different versions is running for different user groups to evaluate the performance of different recommender systems.</p><p>A platform should use a microservice architecture and log clicks and conversions. Then certain users can be forwarded to the application with the old version of the recommender and other users can test the new version. If after some time (this can be several moths) the evaluation shows a significant improvement, the new model can be deployed to all users. Scalability may become an issue, if for example, a collaborative model works on all &gt;100 million users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1dauH-1CohAipCTeqDnAw.png" /><figcaption>Description how A/B tests may be carried out (Source: the author)</figcaption></figure><p>There is literature on recommender systems available [2] that also covers many more sub-types of recommender systems, if you want to gain deeper insights, it is recommended to go through such complete resources.</p><h3>Takeaways</h3><p>Nowadays it is a necessity to use recommender systems to become a big player in the platform economy. All internet companies with large revenue have them if it is applicable. Companies with good content employing this growth potential will always take over the lead over those ignoring the long tail. They benefit from customer binding and better churn and conversion rates. Hence, when thinking about a new platform, one has always to ask the question</p><p><em>Could recommender systems be employed to improve conversion rates?</em></p><p>If the answer is yes, a high priority should be set to derive a scalable concept, a microservice architecture, a suitable analytics approach, an A/B testing idea, and its implementation.</p><h3>Resources</h3><p>[1] Peter Thiel, Zero to One: Notes on Startups, or How to Build the Future, 2014</p><p>[2] Charu C. Aggarwal, Recommender Systems: The Textbook, 2016</p><p>Table of top-30 companies with recommender system evaluation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d59c0757b85ad2f6ee71ffcc2e98e59f/href">https://medium.com/media/d59c0757b85ad2f6ee71ffcc2e98e59f/href</a></iframe><h3>Thanks for reading!</h3><p>If you found the read interesting, you might want to catch up on some of my previous articles:</p><ul><li><a href="https://medium.com/swlh/iot-a7fd31445902">IoT</a></li><li><a href="https://medium.com/swlh/7-tips-for-product-owners-from-7-years-of-experience-a2aa7ba54770">7 Tips for Product Owners From 7 Years of Experience</a></li><li><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7164a7bacdc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-core-value-of-recommender-systems-for-successful-internet-enterprises-7164a7bacdc6">The Core Value of Recommender Systems for Successful Internet Enterprises</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IoT]]></title>
            <link>https://medium.com/swlh/iot-a7fd31445902?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7fd31445902</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Sat, 17 Oct 2020 09:51:43 GMT</pubDate>
            <atom:updated>2020-10-31T22:17:24.018Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Exploring IoT in 2020</strong></h3><p><strong>Basics of the internet of things</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZaZB2Mwc2kxFXZoP9iq4Q.png" /><figcaption>Connecting things (Source <a href="https://unsplash.com/photos/_z0DiiaIhB4">Unsplash</a>, extended and adjusted by M. D. Korzec)</figcaption></figure><p>To connect hardware devices with the internet seems often like a good and at first sight like a simple idea. Everyone wants to digitalize. You can monitor what your devices are doing — great. You can gain insights over your product and/or the customers, and you can react on the service or business level if needed — perfect.</p><p>However, around <strong>3 out of 4 IoT projects fail</strong> <a href="https://www.whyiotprojectsfail.com/">according to a recent report.</a></p><p>When every company has become agile, which is supposed to reduce the number of failing software projects, why is the number so high?</p><p>If an IoT solution needs to scale (success!), the data challenges become huge. Within the 5-layer complexity described in the next section, usual scalability issues in data projects arise.</p><p>Let us dive into a more detailed introduction to IoT first.</p><h3>What is the internet of things?</h3><p>The internet of things (IoT) is the generic idea to connect hardware items, sensors or devices (things), to the internet to generate benefits for the end-user and the thing provider. It was named IoT to get <a href="https://www.techrepublic.com/article/how-the-term-internet-of-things-was-invented/">the word “internet” into the title of a talk in front of management by Kevin Ashton in 1999.</a> He wanted to motivate the need to put RFID chips into the company’s devices in times of the dot-com bubble. By now IoT is applied throughout very many industries and it is very often combined with the current trends in artificial intelligence (AI).</p><p>Often IoT is described <em>a little bit more pompously</em> as <strong>the fourth industrial revolution</strong>, the next step after going from manual labor to machine-based labor, introduction of electricity and computerization. As the technology penetrates almost all areas of life, it might indeed be seen this way. Others like to refer to AI as the fourth industrial revolution — and there is a large overlap.</p><p>IoT has an inherent five-layer complexity, as sketched below: 1. device hardware, 2. device software, 3. network communication, 4. cloud environments, 5. cloud applications</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*lYKDVkUeWMne3tpYb9qG_Q.png" /><figcaption>5 layers of IoT (source: the author)</figcaption></figure><p>This means that <strong>IoT products require business and technical decisions in all of these layers</strong>, not only in software or hardware. This boosts the requirements for the manager’s and the engineers’ skills. IoT projects tend to be complex when the number of devices in scope is high. <strong>Social risks arise with complexity </strong>(it becomes complicated to get people with the right skill set for the projects)<strong>.</strong></p><p>In hardware driven businesses, where IoT ideas often emerge, there are often gaps in expertise with respect to networks, software, and cloud. If you treat software projects in the same way in which hardware focused projects were solved, this might not work out as expected.</p><p>IoT is by now related to most industries, e.g.:</p><ul><li>consumer electronics, e.g. for home automation</li><li>healthcare devices, e.g. for monitoring/optimizing long-term therapies</li><li>factory equipment, e.g. reducing complete break-down of costly machines</li><li>farming, e.g. optimization of water and fertilizer levels</li><li>energy, e.g. for wind turbine maintenance</li><li>finance, e.g. for payment options with ‘some device’</li><li>automotive, e.g. car-to-x communication</li></ul><p>One of the most complex “things” to consider is the car, communicating device states and user interactions to the cloud, communicating to other cars or infrastructure, using a vast amount of different sensors to understand the environment and driving autonomously. Information from various sources can be gathered and analyzed in order to improve the provided service, or in order to adjust/create new products based on the insights from infrequent states and user behavior.</p><p>This is the challenge the German automotive industry is currently dealing with. It has always been strong in manufacturing at scale, while for example Tesla as a young competitor is way more software driven. Building a prototype everyone loves does not mean that it is ready for mass production — no matter if it is hard- or software. Tesla experienced it the other way around than German OEMs, when they had to scale the Model 3 production <a href="https://www.wired.com/story/tesla-fremont-factory-model-3-production-tent-parking-lot-structure/">and had to move parts of the production into a temporary tent</a>.</p><p>The following schematic describes common IoT set-ups in some more detail</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQF7jFGWmYun8RN2LV7ymA.png" /><figcaption>Generic IoT set-up (source: the author; free images from pexels.com)</figcaption></figure><p>Sensors measure relevant information e.g. on machines or devices. The events need to pass a gateway<strong>: </strong>Data from the devices/sensors needs to be preprocessed (often filtered to reduce volume) and translated as different communication technologies are used, e.g. Bluetooth on the sensor/actor side and LAN on the cloud side.</p><p>In the cloud the incoming events are monitored and evaluated. Different actions can be carried out based on the insights that are gained.</p><p>The large cloud providers offer their individual IoT environments (e.g. <a href="https://aws.amazon.com/iot/">AWS</a>, <a href="https://cloud.google.com/iot-core">GCP</a>, <a href="https://azure.microsoft.com/en-us/overview/iot/">Azure</a>). However, it may become more complicated when you work on premises without a private cloud to prohibit a vendor lock and costs that are hard to estimate. For industrial IoT (IIoT) there are large companies like <a href="https://developer.bosch-iot-suite.com/service/gateway-software/">Bosch</a> that offer gateway solutions, and also provide software on the application side — for example Siemens offers its cloud platform <a href="https://siemens.mindsphere.io/">MindSphere</a>.</p><p>What is the benefit? IoT allows for new business cases and to increase efficiency. You gain the information value cycle that suits particularly well for consumer electronics at scale when improving the application software continuously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*rh59sl5jDUIuTMudKwVRlA.png" /><figcaption>The information value cycle, phrased in <a href="https://www2.deloitte.com/us/en/insights/focus/internet-of-things/technical-primer.html">Deloitte insights, The internet of things, A technical primer, 2018, Deloitte</a>) (sketch source: the author)</figcaption></figure><p>The technological expertise needed to be able to run in this circle is high. Most efforts happen on the application side — hence within the software running in the cloud.</p><p>The following section explains different use-cases.</p><h3>Monitor, analyze, act</h3><p>When you have the gateway under control, possibly large amounts of data arrive in the cloud or your own IoT platform.</p><p>Depending on the use-case of IoT, the monitor, analyze, act triad that needs to be built in software, must be considered in different ways. This is broken down in the following schematic, where maintenance/service, demand-driven business, and machine to machine use cases are described.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2f0YL7l6mCRLxx6GVJuvNQ.png" /><figcaption>Adapted schematic (source: the author) from von <a href="https://www.youtube.com/watch?v=3M7s8KXz6es">https://www.youtube.com/watch?v=3M7s8KXz6es</a></figcaption></figure><p><strong>Maintenance/service:</strong></p><p>This use-case is dominant in predictive maintenance in production processes, even for smaller endeavors. In suitable business-cases it is assumed that prediction of failure by monitoring and analyzing the condition of expensive production parts with help of suitable sensors, can prevent them from breaking. Instead a much cheaper repair can circumvent long down-times and large costs.</p><p><em>Service</em> can mean to use a downtime of the production-chain for cost-minimal replacements/repair. A typical example where IoT is successfully employed are wind turbines, but you could also have middle-class use-cases, such as reducing downtimes for filling machines of a beverage supplier.</p><p>The goals here are to reduce costs and/or increase revenue by having to spend less on spare parts and having fewer downtimes.</p><p>Business actions can be triggered. For example, when wind turbines run into problems, the stakeholders can start understanding under which conditions it happens. Then they can be optimized based on this knowledge.</p><p><strong>Demand-driven business:</strong></p><p>This use-case may be for consumer goods, for example in vending machines. User-interaction can be stored and analyzed. Gained insights may be used for further optimization of the business, for example by adjusting the marketing strategy.</p><p>The goals are to increase revenue, optimize service and its costs.</p><p><strong>Machine to machine:</strong></p><p>Automation is every manager’s favorite goal.</p><p>A great example for automation with multiple communication partners are crop fields with monitored soil quality and moisture, reacting on bad numbers with messages to machines automatically pouring water in the right areas with the right mix of complement — and humans being only responsible for monitoring and maintenance of the machinery and the sensors. Based on the outcomes of this automation the business can be further driven.</p><p>Results are efficiency, improved processes and hence increasing quality and revenue.</p><h3>General challenges for IoT</h3><p>We saw some of the many use-cases for IoT. The information value cycle fits perfectly to continuous learning and continuous delivery approaches of our time.</p><p>But let us have a deeper look into the challenges that it brings along, as we learned that if four of you start an IoT project, three will fail.</p><p>Some of the most important challenges for IoT resulting from the five-layer complexity are (partly taken from J. Holdowsky, M. Mahto, M. E. Raynor, M. Cotteleer, <em>Inside the internet of things (iot), </em>Deloitte university press 2015)</p><ul><li>Security</li><li>Energy consumption, not only from the sensors, but also from the network</li><li>Scaling of a secure network</li><li>Complexity and interdisciplinarity of the IoT topic</li><li>Standardization (law, technical standards, worldwide)</li><li>Continuous development and delivery</li><li>Scaling of real-time calculations and data operations</li><li>Data storage</li><li>Data lineage, from unique IDs for sensors to data lineage for dashboards</li><li>Data Analytics</li></ul><p>Note that security of IoT is one of the largest issues, in particular for consumer electronics. If you want to learn more about that, you may refer to one of the many sources that are devoted mainly to this topic, e.g. <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8742551">V. Hassija et al., <em>A Survey on IoT Security: Application Areas,Security Threats, and Solution Architectures, </em>IEEE Access 2019</a>.</p><p>Many IoT projects are motivated “from the hardware side”. Large enterprises working with huge machines determine the optimization potential through IoT and need to get a grip on the data — the oil of the current age. In the next section important aspects for suitable IoT architectures on the application side are described.</p><h3>Data architectures for the cloud applications</h3><p><strong>Small solutions</strong></p><p>If an IoT solution consists of few devices and few log data, many solutions seem possible. For simple industrial IoT (IIoT) one may build for example upon the <a href="https://www.elastic.co/blog/industrial-internet-of-things-iiot-with-the-elastic-stack">Elastic Stack</a>, many services are available in the big cloud providers by now. It consists mainly of</p><ul><li>Data shippers that forward logs</li><li>Logstash, a server-side data processing pipeline</li><li>Elasticsearch, a search engine</li><li>Kibana, a visualization tool based on the Elasticsearch index</li></ul><p>Kibana may include alerting and you can decide if the person to act receives an e-mail, a Slack notification, or any other kind of message.</p><p><strong>Large solutions</strong></p><p>When the requirements are high though, data pours in rapidly, analytics need to be carried out fast, with vast flexibility and with exact numbers (Kibana approximates aggregated numbers when it deals with big data). A suitable architecture with proper ETL pipelines needs to be thought through, with the possibility for different groups to work in parallel. Imagine for example how much data needs to be dealt with from smart watches that are sold by the millions per year.</p><p>Either one relies on cloud web services that are designed for the specific IoT use-case, ore one builds up an own pipeline that can be migrated if a vendor lock is prohibited.</p><p>AWS for example offers a whole set of services that you may use for building up an IoT pipeline. It is easy to lose overview over the many services and different costs they generate, and you will not be able to migrate easily once you implemented all relevant elements in this stack. Hence it might be wise just to use the “infinite” storage (S3) and computational resources (EC2) and write a modular pipeline that is deployed to AWS EKS. Not only you might have a better overview over the resources, it then still should be possible to migrate the whole system either on premises or to another cloud that manages Kubernetes — the big cloud providers offer this service by now and the S3 protocol is kind of standard for object stores.</p><p>Instead of Amazon <a href="https://aws.amazon.com/kinesis/data-firehose/?nc1=h_ls&amp;kinesis-blogs.sort-by=item.additionalFields.createdDate&amp;kinesis-blogs.sort-order=desc">Kinesis Firehose streaming platform</a>, for example <a href="https://kafka.apache.org/">Kafka</a> is a suitable platform for consideration under the Apache-2.0 license. It can handle many millions of writes in a minute and it works in a producer-consumer architecture.</p><p>Various sensors/devices/machines may produce logs to be stored in Kafka. This needs to be taken care of first, then you have the relevant raw data stored and can work one by one on the consumer side. Due to its success it is a service in the major cloud platforms by now, too.</p><p>No matter which stack is used exactly, for large projects probabilities are high to end up with a producer-consumer architecture. Extraction processes can be added one after another, for example</p><ul><li>to search within relevant logs with Elasticsearch and use Kibana for visualizations/search</li><li>to visualize certain aspects based on a PosgreSQL database that is connected to Tableau</li><li>to maintain OLAP cubes with druid and base visualizations on Superset for computationally demanding analytics use-cases.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*ltR1YMfSfDuco-KRHzfh6w.png" /><figcaption>Schematic of a producer-consumer architecture with Kafka and examplary services (source: the author)</figcaption></figure><p>This kind of architecture allows for flexibility and scalability.</p><p>When starting an IoT project at least the core use cases need to be specified first, the data amounts pouring in, acceptable downtimes and hence an adapted (distributed) architecture.</p><p>If you have a small, fixed number of devices, it is comparably easy. If the plan is to scale in masses, but without knowing if 10000 or 1000000 devices will be registered within the next years, the architecture must be horizontally scalable to get by with increasing loads. Again, if you are unsure if the system shall run on AWS, GCP, Azure or even on premises, Kubernetes with Docker services might be a good option — if the expertise to take this path is available.</p><p>In case you plan to scale, I suggest reading some of the articles from the <a href="https://netflixtechblog.com/">Netflix technology blog</a>. Although Netflix is a movie platform, its data science approaches are state of the art for anything where large data amounts are streamed continuously and evaluated by various stakeholders. You can have similar challenges with IoT software in case of suitable amounts of devices.</p><h3>Takeaways</h3><p>The different use-cases for IoT were introduced within the information value cycle and the inherent five layers of IoT solutions. These lead many projects to failure due to the interdisciplinary complexity.</p><p>The IoT landscape is wide, so that challenges may diverge. It is a completely different project if you connect three robots in a factory to an already available IoT platform and can accept downtimes of the monitoring system than writing the cloud software from scratch for a highly reliable system that might end up with millions of devices in scope in case of success. Both ends were touched within this articles.</p><p>Challenges for a large-scale solution were described, it makes a secure and scalable network, data flow, data analytics platform mandatory. If this is your use-case, think about a suitable, scalable, and extendable architecture first. Producer-consumer approaches suit well in this case.</p><h3>Thanks for reading!</h3><p>If you found the read interesting, you might want to catch up on some of my previous articles:</p><ul><li><a href="https://medium.com/swlh/the-core-value-of-recommender-systems-for-successful-internet-enterprises-7164a7bacdc6">The Core Value of Recommender Systems for Successful Internet Enterprises</a></li><li><a href="https://medium.com/swlh/7-tips-for-product-owners-from-7-years-of-experience-a2aa7ba54770">7 Tips for Product Owners From 7 Years of Experience</a></li><li><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</a></li><li><a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">Image Recommendations with PyTorch + Flask + PostgreSQL + Heroku deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7fd31445902" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/iot-a7fd31445902">IoT</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Recommendations with PyTorch + Flask + PostgreSQL + Heroku deployment]]></title>
            <link>https://medium.com/data-science/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/206682d06c6b</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Sat, 29 Aug 2020 08:29:13 GMT</pubDate>
            <atom:updated>2020-10-18T15:12:40.795Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Packaging a PostgreSQL/ PyTorch based image recommender system with Flask, importing data and running it on the Heroku cloud application platform.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riylSbFZVUMftHsjhMRZuA.png" /><figcaption>Selected image of a logo and automatically detected logos of other technologies employed for the image recommender application (Source: M. D. Korzec; <a href="https://flask.palletsprojects.com/en/1.1.x/license/#artwork-license">Flask logo license</a>; Python logo <a href="https://www.python.org/psf/trademarks/">PSF trandemark usage policy</a>; <a href="https://www.w3.org/html/logo/">html logo cc by 3.0</a>)</figcaption></figure><p>During the last weeks I have implemented an item-to-item image recommender system that uses PyTorch’s pretrained Resnet18 convolutional neural network to generate comparability through feature vectors, a database to manage the images and top-k lists and a user interface.</p><p>The developed solution and steps for the deployment on Heroku are presented in this article and <a href="https://github.com/MathMagicx/MediumFlaskImageRecommender">the code is available on GitHub</a>.</p><p>I have <strong><em>set and fulfilled </em></strong>the following <strong><em>requirements </em></strong>for this project</p><p><strong>1. The web app is accessible on the internet.</strong></p><p><strong>2. The application has a gallery of images with pagination, loading only the relevant data for the page.</strong></p><p><strong>3. The data for the gallery and the recommendations is fetched from a database.</strong></p><p><strong>4. The recommendations are most similar images from a possibly large image set. They must appear instantaneously; this means that the similarity calculation happens offline.</strong></p><p><strong>5. The gallery is responsive.</strong></p><p><strong>6. The Flask application is suitably packaged for future extensions/reuse.</strong></p><p><a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d?source=your_stories_page---------------------------">In my last post</a> already parts of the requirements were realized as prototype, in particular 2 and 4. <a href="https://github.com/MathMagicx/JupyterNotebooks/tree/master/ImageRecommenderResnet18">A Jupyter notebook is available at GitHub</a> for the Resnet18 PyTorch recommender that takes an image as input and gives out most similar images from the same image set. To use the Flask app this notebook should be used to generate Pandas dataframes that are stored as pickle files. These are used as static content in the app.</p><p>In this post we will show how to realize also all other requirements, how to use an SQLite database locally and PostgreSQL on Heroku, how to use it for pagination, how to clean-up the work and to deploy it to Heroku to make it available on the internet via browser on PCs or smartphones.</p><p>You can access and test the demo app with a few images on Heroku through the following link:</p><figure><a href="https://image-recommender-demo.herokuapp.com/"><img alt="Logo mds" src="https://cdn-images-1.medium.com/max/113/1*nCn31U3ol6VP8mwcpz9FYA.png" /></a></figure><p>This post is structured in the following sections:</p><p><strong>1. The features of the app are described</strong></p><p><strong>2. The calculation of similarities between images is revisited</strong></p><p><strong>3. The packaging structure for the application is described</strong></p><p><strong>4. The SQL model is presented</strong></p><p><strong>5. The backend application logic is introduced</strong></p><p><strong>6. The templates are introduced</strong></p><p><strong>7. All steps for the Heroku deployment are explained</strong></p><p><strong>8. A conclusion is made</strong></p><p><em>Note, for this article I was using a Windows 10 machine and Python 3.5.4. I have left out any exception handling.</em></p><h3><strong>1. Features of the app</strong></h3><p>To get a better understanding what the implementation is for, let me briefly explain the features of the application.</p><p><strong>Image gallery:</strong></p><p>One can browse a set of images in a self-written gallery, showing all the images from the initial input set (a small test set generated from my private image repository), as depicted below:</p><figure><img alt="Image gallery with pagination" src="https://cdn-images-1.medium.com/max/1024/1*xCiFl5-hNnh0hf3WTCyWKA.png" /><figcaption>Image gallery with pagination (Source: M. D. Korzec)</figcaption></figure><p>The gallery has a custom design that was created with stylesheets. It defines the sizing of the header, the mouse reactions, the images, the text overlay, and pagination number appearance.</p><p><strong>Pagination</strong>:</p><p>You can see the numbers below the images in the gallery. These allow to select a page with images. To not load all data at once I moved away from a JavaScript based approach that lead to hiding more information, but it was still loading all images. With the presented implementation, only the relevant data is loaded.</p><p><strong>Image recommendations:</strong></p><p>To each image from a possibly large image set, similar images with similarity values are fetched and presented in a second route. A one-to-many relationship is used for that end to show the most similar images to a selected input. The approach allows to change the number of sought recommendations. We use four, due to the small, artificial image set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*P7YL8bGtIQ3EImDOYcjuHg.png" /><figcaption>Rio de Janeiro from Pão de Açúcar, similar images found by the app (Source: M. D. Korzec)</figcaption></figure><p>As the images are truncated you can further click and enlarge them in a modal to see the complete images, this modal uses some basic JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTZuXz4dF3PBlWyjy4nKCA.png" /><figcaption>Enlarged image (Source: M. D. Korzec)</figcaption></figure><p><strong>Responsiveness</strong>:</p><p>The gallery and the recommendations are responsive, this means that you can use it on a smartphone and the image selection and proposals are user friendly on such devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etJawmGB2Yyb02SDnwmaZg.jpeg" /><figcaption>The gallery on a smartphone (Source: M. D. Korzec)</figcaption></figure><p><strong>Database commands:</strong></p><p>I prepared some test data and used a dictionary to use it in an <a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d?source=your_stories_page---------------------------">earlier prototype</a>. This is reused for an import command. One can use the console to create or clear the database, and to import data described in such a dictionary. This works locally for the SQLite, but also for the PostgreSQL database at Heroku. The commands are included as Blueprint module.</p><h3><strong>2. Calculating recommendations offline</strong></h3><p>In a <a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb?source=post_stats_page---------------------------">previous article</a> I explained in detail how one can easily generate a similarity matrix and top-k lists (for each image, the k most similar other images). An implementation was presented <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=post_stats_page---------------------------">in a separate post</a>. Hence check-out these posts for details.</p><p>What we do, briefly:</p><ul><li>Preprocess images from an image input folder</li><li>To each image create feature vectors with Resnet18 from PyTorch</li><li>Compare feature vectors and store top-k lists</li></ul><p>This is done in one <a href="https://github.com/MathMagicx/JupyterNotebooks/blob/master/ImageRecommenderResnet18/Recommending%20Similar%20Images.ipynb">Jupyter notebook</a>, where I now added two lines to store the dataframes with similar image names and similarity values as pickle files. These are used as static content for the recommender application presented here. You can check-out the repository with the test images and it should run without efforts.</p><p>What we need to add is the import of these results — the actual recommendations — to an SQL database.</p><p>For the online processing the backend process only queries the most similar images for rendering the proper html.</p><h3><strong>3. Packaging the app</strong></h3><p>The following application structure has been used:</p><pre>~/imageRecommender             <br>     |-- requirements.txt         # All packages to run the app<br>     |-- Procfile                 # file needed to use gunicorn<br>     |-- run.py                   # starts the application   <br>     |-- .flaskenv                # sets environment variables   <br>     |__ env                      # virtual environment – not in vc<br>     |__ /imageRecommender        # The application package<br>          |-- __init__.py         # Application factory method<br>          |-- config.py           # Configuration file for dev/prod     <br>          |-- models.py           # Database models <br>          |__ /commands           # For import to database<br>              |-- __init__.py     # Application factory<br>              |-- commands.py     # Commands for DB creation/import<br>          |__ /main               # For routes<br>              |-- __init__.py     # Application factory<br>              |-- routes.py       # Business logic, fctns for routes   <br>          |__ /static             # All static data<br>              |__ /css            # Stlyesheets<br>              |__ /javascript     # Java Script code for modal<br>              |__ /pickles        # The top-k lists in pickle format<br>              |__ /site_imgs      # The images for the app<br>              |-- favicon.ico     # The favicon<br>          |__ /templates          # All templates<br>              |-- home.html       # Home route<br>              |-- layout.html     # General layout<br>              |-- recommend.html  # Recommend route</pre><p>The <strong>__init__.py</strong> files make the folders that they are contained into modules. These modules can be registered as Blueprints. Only the <strong>__init__.py</strong> file on the imageRecommender level is non-empty in this application.</p><h3><strong>4. The data model</strong></h3><p>We store the image information in an SQL database. Therefore, we use <em>Flask-SQLAlchemy</em>, a library that helps using Flask with SQLAlchemy — which again is a Flask SQL toolkit that gives you the possibility to use SQL with Flask.</p><p><strong>3.1. Getting started with SQL for Flask</strong></p><p>The package supporting SQL databases is <strong>flask-sqlalchemy</strong>, version 2.4.4 is in the <strong>requiremets.txt</strong> file. With this we can import it to the application in the factory for the imageRecommender application factory <strong>__init__.py</strong>.</p><p>We configure the SQLite database for the Flask application locally and a Postgres database (everything is stored in one file then) for Heroku in the <strong>config.py </strong>file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f01975d20a7bdec0a2b214fb4aff12b/href">https://medium.com/media/9f01975d20a7bdec0a2b214fb4aff12b/href</a></iframe><p>Dependent on the use-case (development or production on Heroku) the right configuration is chosen. The secret key in production needs to be unique for security and the URL for the database needs to be set.</p><p><strong>3.2. The data model</strong></p><p>We create a class for the images for the gallery and a related class for the images to be recommended.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6ecfa404a80e453f085d4ca400405e/href">https://medium.com/media/cf6ecfa404a80e453f085d4ca400405e/href</a></iframe><p>Some remarks to this model:</p><ul><li>The <em>id</em> identifiers for both tables are set automatically and uniquely as default</li><li><em>imageName</em> and <em>imageDescription</em> are strings for the metadata of the images</li><li><em>imageRecs</em> is the relationship to the recommendations, these are needed for the recommend route</li><li>The <em>Imagerecommendations</em> class contains the related ID from the queried image, the name of the recommended image and its similarity value. It denormalizes the normal form with respect to the image name</li></ul><p>We can now create the database and import data.</p><p><strong>3.3 Database commands</strong></p><p>There are three simple commands:</p><ol><li>to drop the database</li><li>to create it</li><li>to import data</li></ol><p>The app is packaged as described above such that the <strong>commands.py</strong> script has access to the application — we will see that when talking about Blueprints later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a476eb5c0900e0f733d20f69daae017d/href">https://medium.com/media/a476eb5c0900e0f733d20f69daae017d/href</a></iframe><p>After running the import one has already a database that one can test, e.g. by creating queries.</p><h3><strong>5. The backend application logic</strong></h3><p>It was already described <a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d?source=your_stories_page---------------------------">in my last article</a> what Flask is and how to set-it up.</p><p>The solution is packaged to the imageRecommender package, and we call it with the <strong>run.py</strong> script</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8c058b860c37dfabfc9833d314e81c1/href">https://medium.com/media/c8c058b860c37dfabfc9833d314e81c1/href</a></iframe><p>The <em>createApp</em> method is in the <strong>__init__.py</strong> application factory, and it becomes useful to work with it when extending the application, e.g. by tests that require several instances of the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6324bc387f8047e3e175746d5f8233f2/href">https://medium.com/media/6324bc387f8047e3e175746d5f8233f2/href</a></iframe><ul><li>For the imports the configurations are loaded, these were described earlier. The app needs to be created in this <strong>__init__.py</strong> file via app = Flask(__name__).</li><li>After the object is created the environment variable is validated for the right use-case and the suitable configuration is loaded.</li><li>The database object is created, and two Blueprints are registered for the main application and the database commands. cli_group=None merges the commands to application level, so that they are just callable by flask &lt;command name&gt; in the Heroku console.</li></ul><p>The<em> main</em> Blueprint contains the main backend application logic in the <strong>routes.py</strong> file. Let’s go through this file set-by step:</p><pre>from flask import render_template, request, Blueprint<br>from imageRecommender.models import Galleryimages</pre><ul><li>We work with templates that are used for html page generations through the <em>render_template</em> package.</li><li>Via request we get the name of the selected image and the page that we are on in the gallery.</li><li>As we use Blueprints for modularizing the application, Blueprint is imported.</li><li>To the queried image we get the similar images via the Imagerecommendations related class, and therefore we work with our <em>Galleryimages </em>class.</li></ul><pre>main = Blueprint(&#39;Fmain&#39;, __name__)</pre><ul><li>The blueprint <em>Fmain </em>is registered.</li></ul><pre>@main.route(&quot;/&quot;)<br>@main.route(&quot;/home&quot;)<br>def home():<br>    page = request.args.get(&#39;page&#39;, 1, type=int)<br>    gImages = Galleryimages.query.paginate(page=page, per_page=8)<br>    return render_template(&#39;home.html&#39;, images = gImages)</pre><ul><li>The main and home route give access to the gallery.</li><li>Via the <em>home.html</em> template we render the images given within the <em>render_template</em> call.</li><li>It takes as input the images from <em>gImages</em>. Here the pagination feature is used. With <em>per_page</em> it can be set how many images are to be shown on one page of the gallery, and page is the default page to be opened, in this case the first page of the gallery with the first eight images.</li></ul><pre>@main.route(&quot;/recommend&quot;)<br>def recommend():<br>    selectedImage = request.args.get(&#39;selectedImage&#39;)<br>    imageEntry = Galleryimages.query.filter_by(imageName=selectedImage)<br>    images = []<br>    values = []<br>    for image in imageEntry:<br>         for recommendation in image.imageRecs:<br>             images.append(recommendation.recommendedName)<br>             values.append(recommendation.similarityValue)</pre><pre>    return render_template(&#39;recommend.html&#39;, title=&#39;Recommendations&#39;, customstyle=&#39;recommend.css&#39;, inputImage=selectedImage, similarImages=images, similarityValues = values)</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><ul><li>The recommend route is called with the corresponding recommend function that requests the user’s selectedImage.</li><li>It is queried from our database, and we iterate all recommendations from the related class.</li><li>The image and value arrays are filled with corresponding information.</li><li>All required information is passed to render the recommend.html page.</li></ul><h3><strong>6. The templates</strong></h3><p>We saw two calls to render html pages from templates:</p><pre>render_template(&#39;home.html&#39;, images = gImages)</pre><pre>render_template(&#39;recommend.html&#39;, title=&#39;Recommendations&#39;, customstyle=&#39;recommend.css&#39;, inputImage=selectedImage, similarImages=images, similarityValues = values)</pre><p>Let us have a look on the relevant sections of the <strong>home.html</strong> and <strong>recommend.html</strong> files</p><p>The application uses a layout template <strong>layout.html</strong> to maximize reuse of html code. The important part is that the body of the template has a block content that is specified within the other two html files.</p><pre>&lt;body&gt;<br>…<br>{% block content %} {% endblock %}<br>&lt;/body&gt;</pre><p>The <strong>home.html</strong> file is used for the gallery</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2a0d1bd5d07e1166472c6b63042157/href">https://medium.com/media/1e2a0d1bd5d07e1166472c6b63042157/href</a></iframe><p>It consists mainly of two parts:</p><p>1. The images in the gallery that are iterated via <em>{% for image in images.items %}</em> and</p><p>2. The pagination elements in the pagination div section. Here the most interesting part is the <em>iter_pages</em> method that allows to set how many numbers are shown to the left and right edges, and in the middle of the number block</p><p><em>{% for page_num in images.iter_pages(left_edge=2, right_edge=2, left_current=1, right_current=2) %}</em></p><p>The recommend.html template is used to show the query and the most similar images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e80057a4d1a86b2c74d3d404e8a0a36f/href">https://medium.com/media/e80057a4d1a86b2c74d3d404e8a0a36f/href</a></iframe><p>The modal at the end and the inclusion of the only JavaScript code in this app are for the pop-up that enlarge the similar images if wanted.</p><p><strong>Responsiveness:</strong></p><p>To properly show the gallery on a smartphone some design elements need different sizing and the gallery shall have only one column. This can all be realized with stylesheets by adding a corresponding section</p><pre><em>@media only screen and (max-device-width : 640px) {</em></pre><p>and for the gallery content we have set for example the column-count to one in this section</p><pre>.gallery .galleryContent .item{<br>    float: left;<br>    width: 100%;<br>    height: 100%;<br>    position: relative;<br>    cursor: pointer;<br>    column-count: 1;<br>}</pre><h3><strong>7. Heroku deployment</strong></h3><p>The <strong>.flaskenv</strong> file contains two entries and it works when <em>python-dotenv</em> is installed</p><pre>FLASK_APP=run.py<br>FLASK_ENV=development</pre><p>so that flask run lets you test the application locally on <a href="http://localhost:5000/">http://localhost:5000/</a></p><p>Now it is time to deploy the package and make it accessible through the internet.</p><figure><a href="http://heroku.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C514ItaHTpeHtD_15tMD8Q.png" /></a></figure><p><a href="https://www.heroku.com/">Heroku</a> is a platform that allows to easily deploy and host applications. It spares most efforts, no usual system administration, webserver, firewall set-up tasks etc. are needed. A free tier allows simple tests and the presented demo runs on such a free host. We want to deploy the application to Heroku as it offers free cloud web hosting services that are optimal for a demo as this one.</p><p>The following steps are <em>tested and working in August 2020</em> on Heroku.com.</p><p>For a simple deployment to Heroku push your code to GitHub. Create a repository. Use the URL you received to push the repository to GitHub.</p><p>Therefore, you need to visit <a href="https://www.heroku.com/">https://www.heroku.com/</a> and create an account with the primary development language Python.</p><p>To install the Heroku CLI follow the instructions on <a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a>.</p><p>You can carry out many of the following steps with the Heroku CLI, however, if possible, I present UI based configuration steps.</p><p>In Heroku click on “Create a new app”. It requests you to give it a name, let us set here <em>image-recommender-demo</em> and the region Europe.</p><p>Confirm and you get to a next screen, where you can select your deployment method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*bV34CKzVD5OM7Blgx2-sIQ.png" /></figure><p>As we pushed the code to GitHub, we select the GitHub option, after which we need to “Connect to GitHub” and authorize Heroku to access your GitHub repository.</p><p>Next, we enter the name of the corresponding repository <em>image-recommender-demo</em>, search for it and connect to it.</p><p>You can select to automatic deploy each change, e.g. to your master branch, which is very handy for such demo use-cases,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*_HYNsfTVa1dVafLnZwEjpA.png" /></figure><p>For the start we deploy it once manually (there is another button to be pushed for that end). You can now see your solution being built and the state of success</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*L8tVpJZyYd19Yw78rKjdUg.png" /></figure><p>On top of the site you can find a button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*8a-eRNKpqIkhEvILGepuYA.png" /></figure><p>That leads us in this case to our recommender system on</p><p><a href="https://image-recommender-demo.herokuapp.com/">https://image-recommender-demo.herokuapp.com/</a></p><p>Until now the logs will show that no web processes are running, therefore a <strong>Procfile</strong> needs to be created, this is used by Heroku to understand how to run the application. It contains only the line</p><pre>web: gunicorn run:app</pre><p><em>web</em> specifies that a web worker is used. An application server is needed, therefore gunicorn is used and it needs to be installed — version 20.0.4 is referenced in the <strong>requirements.txt</strong> file. <em>gunicorn</em> is the command needed to run the web process, such that the python code can communicate to the webserver. <em>run</em> refers to the <strong>run.py</strong> file containing the application object, <em>app</em> refers to the name of the application object.</p><p>After this is committed, one needs to set FLASK_ENV. As mentioned I use the <strong>.flaskenv</strong> file locally. In production the configuration is set manually via the Heroku CLI</p><pre>heroku config:set FLASK_ENV=production --app image-recommender-demo</pre><p>If you are not yet logged in, Heroku will request a login first.</p><p>Now running the app still leaves you with an internal server error as the database is not set-up yet.</p><p>We want to work with PostgreSQL. Click on “overview” in the Heroku UI, select “Configure Add-ons”, search for “Postgres”; select “Heroku Postgres”. I use the free version for this demo.</p><p>Now this database is already attached to the app <em>image-recommender-demo</em>! You can see it now under “Settings”, “Config Vars” with its URL.</p><p>If <em>psycopg2</em> was not yet installed Heroku will tell us again an error and the logs reveal that the module “psycopg2” was not found. Therefore, psycopg2==2.8.5 in the <strong>requirements.txt</strong> file gets the right package.</p><p>The tables still do not exist, so we will still see an error after this adjustment on Heroku.</p><p>To create the missing tables and import some data we use the commands from the <strong>command.py</strong> file explained earlier.</p><p>We shall set the <em>FLASK_APP</em> variable such that the commands are recognized in the Heroku con</p><pre>heroku config:set FLASK_APP=run.py --app image-recommender-demo</pre><p>Now we can call the console in Heroku and use the commands presented earlier</p><pre>flask createDB<br>flask importDB</pre><p>That’s it, the application is deployed, online and the database contains relevant data!</p><h3><strong>8. Conclusions</strong></h3><p>With this and the <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=post_stats_page---------------------------">PyTorch recommender post</a> you have everything at hand to</p><ul><li>Run machine learning code offline and store the results</li><li>Create a Flask based web application</li><li>Use the machine learning results in the web application</li><li>Use a PostgreSQL database with Flask</li><li>Deploy your application to Heroku</li></ul><p>You are not bound to use these programming insights for this particular demo app, you can become creative with other ideas once you understood all the steps.</p><p>There are still further aspects to be considered as described in my<a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d"> last article</a> to aim for production.</p><p>We could invest some more work and make the recommendations itself an API service with suitable endpoints for adding, deleting, and updating the entries.</p><p>This kind of service could be a part of a production system like a larger online shop. Note that in this case the images should be moved from the static folder to for example some object storage.</p><h3>Thanks for reading! Liked the topic?</h3><p>If you found the read interesting, you might want to catch up on my previous articles on the topic that this article extends upon:</p><ul><li><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</a></li><li><a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c">Recommending Similar Images Using PyTorch</a></li><li><a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d">A Flask App for Image Recommendations</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=206682d06c6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">Image Recommendations with PyTorch + Flask + PostgreSQL + Heroku deployment</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>
        <item>
            <title><![CDATA[A Flask App for Image Recommendations]]></title>
            <link>https://medium.com/data-science/a-flask-app-for-image-recommendations-a865e1496a0d?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a865e1496a0d</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 08:27:08 GMT</pubDate>
            <atom:updated>2020-10-31T22:19:02.763Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementation of a website for similar image recommendations based on convolutional neural networks in PyTorch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTgR6Hzd9QpRJUjR1ARrYg.png" /><figcaption>Image gallery and recommendations to a selected image (source: M. D. Korzec)</figcaption></figure><p>After creating a Python-based machine learning application you might want to get it running on a website.</p><p>In this article it is explained how this can be realized with the microframework Flask for an image-based recommender system.</p><p>We implement an image gallery on a website, the images can be selected, and similar images are displayed. Such a solution could be employed for example in online shops.</p><p>The similarities are obtained by comparing feature vectors derived with a pretrained Resnet18 network <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c">as explained in a previous article</a>. The results from this work are Pandas dataframes (essentially tables) with the names of most similar images and similarity values between zero (not similar) and one (most similar) for each image. These are stored and used here.</p><p>In the next figure, in (a) the steps from the theory and implementation are sketched. This article focuses on part (b), where the dataframes have already been calculated offline to be used on a website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h72jdWWVpWPKZ24ASU4xLw.png" /><figcaption><a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=your_stories_page---------------------------">Similarity matrix calculation (a</a>) and sorted top-k list for recommendations (b). In this article Flask is used to use the results for a website (source: M. D. Korzec, <a href="http://flask.pocoo.org/static/logo/flask.svg">Flask logo by Armin Ronacher</a>, Copyrighted <a href="https://commons.wikimedia.org/w/index.php?curid=19501815">free use</a>)</figcaption></figure><p>We will see how to</p><ul><li>install Flask and run the app locally on a debug server</li><li>define needed routes — the URLs that are used for the gallery and the recommendations</li><li>transfer the needed information from the user input to the backend and the recommendations back to the user</li><li>implement a html/JavaScript gallery that suggests similar images</li><li>create pickle files based on my first two articles (<a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">theory</a>, <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=your_stories_page---------------------------">implementation</a> with <a href="https://github.com/MathMagicx/JupyterNotebooks/tree/master/ImageRecommenderResnet18">Jupyter notebook</a>). Use them for top-k lists that define the recommended images.</li></ul><p>Update: In <a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">my follow-up article</a> you can find the extension of the presented approach. It explains all relevant code for using a PostgreSQL database, suitable packaging and it contains astep-by-step description for the deployment to Heroku. The code is linked in the post and the demonstrator is reachable <a href="http://image-recommender-demo.herokuapp.com/">here</a>.</p><h3>1. Flask</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*4ePJLlIwOQvrIvtV7AvyUw.png" /><figcaption>Logo by <a href="http://flask.pocoo.org/static/logo/flask.svg">Armin Ronacher</a>, Copyrighted <a href="https://commons.wikimedia.org/w/index.php?curid=19501815">free use</a></figcaption></figure><p><a href="https://flask.palletsprojects.com/en/1.1.x/">Flask</a> is a very popular microframework written in Python. It is called ‘micro’ as it does not come along with a complete feature set, abstraction layers for databases, user management or similar functionality, but it is extendable with available libraries covering all the needs.</p><p>This might sound like a drawback compared to feature-rich frameworks like <a href="https://docs.djangoproject.com/">Django</a>, however, it also reduces complexity, leaves the users with more choices and allows to keep a better overview over the application.</p><p>What you <em>can</em> do with it easily: Use your python code in the backend, communicate results to the frontend that you can write with html, JavaScript and css — you can also use a frontend framework like Vue.js.</p><p>Flask offers the usage of templates based on the Jinja2 syntax that simplify reusability and dynamic creation of webpages.</p><p>If you plan to play around with Flask for the first time, I recommend to watch a few tutorials from <a href="https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g">Corey Schafer</a>, who created a concise Flask series that gets you started very fast.</p><p>How to run Flask in the first step (on Windows)? After creating a suitable virtual environment, install it, e.g. with pip</p><pre><strong>pip install Flask</strong></pre><p>and import it to make all the code available to build Flask web applications</p><pre><strong>from</strong> <strong>flask</strong> <strong>import</strong> Flask</pre><p>To run the local debug webserver, you can use a batch file containing your main Python file</p><pre><strong>set FLASK_DEBUG=1<br>set FLASK_APP=recommenderFlask.py<br>flask run</strong></pre><p>FLASK_APP just sets the application file. Then you access it via</p><p><a href="http://localhost:5000/">http://localhost:5000/</a></p><p>Setting FLASK_DEBUG causes debug information to be displayed directly in the browser.</p><p>To print ‘Hello, world!” the python file should read</p><pre>from flask import Flask</pre><pre>app = Flask(__name__)<br>@app.route(‘/’)<br>def hello_world():<br>  return ‘Hello, World!’</pre><p>For this article I used Flask version 1.1.1 and Python version 3.5.4.</p><h3><strong>2. Routes</strong></h3><p>Let’s set up the main file for the application, recommendFlask.py</p><pre><strong>from flask import Flask<br>app = Flask(__name__)</strong></pre><pre><strong>@app.route(“/”)<br>@app.route(“/home”)<br># Need to write a function that is called when opening the site</strong></pre><pre><strong>@app.route(“/recommend”)<br># Need to write a function that is called when opening recommendations</strong></pre><pre><strong>if __name__ == ‘__main__’:<br>  app.run(debug=True)</strong></pre><ul><li>We import the Flask class to be able to create the Flask web application.</li><li>The Flask instance app is created, and it is run in the last line if the script is called directly as then Python sets <strong>__name__ == ‘__main__’. </strong>This is not the case if <em>recommendFlask.py</em> was imported from another script. Setting debug to true has the benefit that you can see errors during development on the website itself.</li><li>In between there are the home and recommend routes that are not doing anything yet. They will trigger corresponding functions written and explained in the next sections. We will reach the main page that will contain an image gallery via <strong>localhost:5000/home/ or localhost:5000/, </strong>while the recommendations will be shown on <strong>localhost:5000/recommend/</strong></li></ul><p>Let us create a gallery with images.</p><h3><strong>3. The gallery</strong></h3><p>We will put the image names of interest that are located within a folder into a dummy array on top of the recommenderFlask.py file.</p><pre>images = [<br>  {<br>    ‘name’:’buildings0.jpg’,<br>    ‘caption’: ‘Lisboa’<br>  },<br>  {<br>    ‘name’: ‘buildings1.png’,<br>     …</pre><p>We use this data to create the gallery. For a production system this part needs to be moved to a database — this will be part of a follow-up article.</p><p>The home route is called with a function that renders the html pages based on the variable content concerning the images.</p><p>Therefore, add the library for html rendering</p><pre>from flask import render_template</pre><p>and call the gallery creation with the image array</p><pre>@app.route(“/home”)<br>def home():<br>  return render_template(‘home.html’, images = images)</pre><p><strong>home.htm</strong>l is a template to be put into the Flask template folder that allows to iterate e.g. in a div block through the images.</p><p>Flask enables the usage of passed variables and for example to use for loops and variables in curly brackets as the following one</p><pre>{% for image in images %}<br>  &lt;div class=”item”&gt;<br>    &lt;a href=”{{ url_for(‘recommend’, selectedImage=’’) }}{{image.name }}”&gt;<br>    &lt;img src=”{{ url_for(‘static’, filename=’site_imgs/images/’) }}{{image.name}}” alt=”{{image.name}}” id=”showSimilarInPopup”&gt;<br>    &lt;div class=”caption”&gt;<br>      {{image.caption}}<br>    &lt;/div&gt;<br>    &lt;/a&gt;<br>  &lt;/div&gt;<br>{% endfor %}</pre><p>In the templates you can add css and scripts to make the gallery work. For pagination in the gallery I added one script that is located in the static folder (that is configured as default by Flask).</p><pre>&lt;script src=”{{ url_for(‘static’, filename=’js/pagination.js’) }}”&gt;&lt;/script&gt;</pre><p>Overall, you can create your favorite approach and style to show and iterate the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kySVL6KkiMq7_W5z5XkGjQ.png" /><figcaption>Image gallery (source: M. D. Korzec)</figcaption></figure><p>For the tests and above website I used the images provided <a href="https://github.com/MathMagicx/JupyterNotebooks/tree/master/ImageRecommenderResnet18">in the GitHub repository for the top-k list calculation</a>. Due to the few different classes within the 21 images it helps testing the provided recommendations.</p><p>When clicking on one of the images the reference</p><pre>&lt;a href=”{{ url_for(‘recommend’, selectedImage=’’) }}{{image.name }}”&gt;</pre><p>to the recommendation route comes into play. We want to generate a new html page showing the most similar images to the selection.</p><h3><strong>4. The Recommender</strong></h3><p>We just saw that triggering an image sets the variable selectedImage to the name of the image from the images array and the recommend route is called. You can see it in the URL when clicking on an image (e.g. on camper2.jpg from the set)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*w1BScHIo_vOQiiE6gLB1Fg.png" /></figure><p>Let’s use this variable in our application file.</p><pre>from flask import request</pre><pre>@app.route(“/recommend”)<br>def recommend():<br>  selectedImage = request.args.get(‘selectedImage’)<br>  inputImage, images, values = getImages(selectedImage)<br>  return render_template(‘recommend.html’, title=’Recommendations’, customstyle=’recommend.css’, inputImage=inputImage, similarImages=images, similarityValues = values)</pre><p>What happens here after the variable is requested:</p><ul><li>The <strong>getImages </strong>function returns arrays of similar images to the input</li><li>From the template <strong>recommend.html</strong>, based on the input and similar images related to the input, an html site is generated. A custom style is used for the html page.</li></ul><p>In the template the original image is shown based on the corresponding variable <strong>inputImage</strong></p><pre>&lt;div class=”originalImage”&gt;<br>  &lt;h3&gt; Input image&lt;/h3&gt;<br>  &lt;img src=”{{ url_for(‘static’, filename=’site_imgs/images/’) }}{{inputImage}}” alt=”{{inputImage}}” id=”showSimilarInPopup”&gt;<br>&lt;/div&gt;</pre><p>and the similar images are listed based on the <strong>similarImages </strong>array</p><pre>&lt;div class=”galleryContent”&gt;<br>  &lt;h3&gt; Similar images&lt;/h3&gt;<br>  {% for image in similarImages %}<br>    &lt;div class=”item”&gt;<br>      &lt;img id=”popupImage{{loop.index}}” onclick=”imageClicked(this.id)” src=”{{ url_for(‘static’, filename=’site_imgs/images/’) }}{{image}}” alt=”{{image}}” id=”showSimilarInPopup”&gt;<br>    &lt;/div&gt;<br>  {% endfor %}<br>&lt;/div&gt;</pre><p>That’s it for the core Flask elements. Everything else that was done is making the website nice and the gallery functional.</p><p>The last point to discuss is the <strong>getImages </strong>function from above.</p><h3><strong>5. Using the top-k lists</strong></h3><p>When comparing the feature vectors derived from the evaluation of the convolutional neural network for different images, top-k lists are created (for each image the k most similar images from your image set are noted).</p><p>Referring to the implementation presented in the <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=your_stories_page---------------------------">last article</a> (Jupyter Notebook can be found on <a href="https://github.com/MathMagicx/JupyterNotebooks/blob/master/ImageRecommenderResnet18/Recommending%20Similar%20Images.ipynb">GitHub</a> including example images), we store the already derived Pandas dataframes from this notebook <strong>similarNames </strong>and <strong>similarValues</strong>, containing the similar names and the corresponding similarity values, as Pickle files</p><pre><strong>import pickle<br>similarNames.to_pickle(&quot;similarNames.pkl&quot;)<br>similarValues.to_pickle(&quot;similarValues.pkl&quot;)</strong></pre><p>On the website these can be just treated as static content that is loaded and used to provide most similar images, but as for the gallery a database should do the job in production.</p><p>The following snippet is used to return the prescribed number (<strong>recLength</strong>) of most similar images and similarity values.</p><pre>import pickle<br>import os<br>import sys<br>from numpy.testing import assert_almost_equal</pre><pre>global recLength<br>recLength = 3</pre><pre>def getNames(inputName, similarNames, similarValues):<br>  images = list(similarNames.loc[inputName, :])<br>  values = list(similarValues.loc[inputName, :])<br>  if inputName in images:<br>    assert_almost_equal(max(values), 1, decimal = 5)<br>    images.remove(inputName)<br>    values.remove(max(values))<br>    return inputName, images[0:recLength], values[0:recLength]</pre><pre>def getImages(inputImage):<br>  similarNames = pickle.load(open(os.path.join(“static/pickles/similarNames.pkl”), ‘rb’))<br>  similarValues = pickle.load(open(os.path.join(“static/pickles/similarValues.pkl”), ‘rb’))</pre><pre>  if inputImage in set(similarNames.index):<br>    return getNames(inputImage, similarNames, similarValues)<br>  else:<br>    print(“‘{}’ was not found.”.format(inputImage))<br>    sys.exit(2)</pre><p><strong>getImages </strong>loads the pickle files. <strong>getNames </strong>creates simple lists out of them and removes the same images from these lists. <strong>recLength </strong>is the number of similar images you want to work with and should be moved to a configuration file.</p><p>So now we have provided the user input to this Python function that gives back the selected and similar images. These are then used as described before for the html rendering.</p><h3><strong>Outlook: Production perspectives</strong></h3><p>It was shown in a previous article <a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c?source=your_stories_page---------------------------">how to implement a recommender system</a> with PyTorch. In this article it was described how to use the results on a Flask-based website locally. This is great if you want to work with prototypes. It will also work for smaller projects with few extensions.</p><p>For production of an evolving application with some scalability requirements you may work with Flask, but you may need to take care of many more topics that may vary in priority dependent on the scope:</p><ul><li>Project structure</li><li>Using a database</li><li>Deployment to a production system / a cloud environment → overall a reliable continuous integration chain covering a suitable test strategy</li><li>Configuration handling</li><li>Upload of new data (new images) with automated update of top-k lists</li><li>Error handling, logging, and monitoring</li><li>Dependent on your project size these may become the largest topics: Scalability, reliability, and maintainability [1]</li><li>Generating more diversity in the recommendations and general tuning dependent on the particular use-case</li><li>Security, load balancing, …</li></ul><p>There is some work left for your productive application!</p><p><a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">In the next article</a> I explain how to use a PostgreSQL database for this use case, how to structure the project and how to deploy it to Heroku.</p><p>With the presented steps you nevertheless have everything at hand to start the journey connecting your Python code with the user in front of a browser!</p><p>[1] <a href="https://www.amazon.de/Martin-Kleppmann/e/B00Q43XKD6/ref=dp_byline_cont_book_1">Martin Kleppmann</a>, <em>Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems</em>, O’Reilly UK Ltd. 2017</p><h3>Thanks for reading! Liked the topic?</h3><p>If you found the read interesting, you might want to catch up on my related articles:</p><ul><li><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</a></li><li><a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c">Recommending Similar Images Using PyTorch</a></li><li><a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">Image Recommendations with PyTorch + Flask + PostgreSQL + Heroku deployment</a></li><li><a href="https://medium.com/swlh/the-core-value-of-recommender-systems-for-successful-internet-enterprises-7164a7bacdc6">The Core Value of Recommender Systems for Successful Internet Enterprises</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a865e1496a0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-flask-app-for-image-recommendations-a865e1496a0d">A Flask App for Image Recommendations</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>
        <item>
            <title><![CDATA[7 Tips for Product Owners From 7 Years of Experience]]></title>
            <link>https://medium.com/swlh/7-tips-for-product-owners-from-7-years-of-experience-a2aa7ba54770?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2aa7ba54770</guid>
            <category><![CDATA[scrum-agile]]></category>
            <category><![CDATA[product-owner]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[digital-life]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 08:28:55 GMT</pubDate>
            <atom:updated>2020-10-31T22:18:15.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ol_1EpB6dLJeK-3u" /><figcaption>Photo by <a href="https://unsplash.com/@wesleyphotography?utm_source=medium&amp;utm_medium=referral">Wesley Tingey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to product owning there is no manual that guides you through the creation of successful software. You need to stay curious and eager to learn as you work with people that have their own quirks, expectations, and experiences while working on products that are unique.</p><p>As product owner you have to deliver good business results, analyze and develop the business case, display leadership, specify and communicate valuable user stories. You have a vast amount of responsibilities and there are many pitfalls on this challenging path.</p><p>Let me share 7 tips that I learned over 7 years as product owner in the automotive industry within several multi-enterprise B2B projects.</p><h3>1. Control the backlog</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZnfcEycAk9AuZRyL" /><figcaption>Photo by <a href="https://unsplash.com/@jbcreate_?utm_source=medium&amp;utm_medium=referral">Joseph Barrientos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You do not want to be bothered with bugs and technical debt, so they can be just added to your Jira project? Wouldn’t it be good to get improvement suggestions from your stakeholders, too? And while you are at it, you want to give admin rights to your superiors, so that they can put requests into the backlog efficiently?</p><blockquote><em>Don’t open up your development ticket system to become an idea trashcan if you are not fast enough to clean it up.</em></blockquote><p>If you don’t know the issues in your backlog, you will have a hard time. You have to understand the items and know their priority.</p><p>If you lag behind and lost the backlog maintenance war, you may have the following conflicts</p><ul><li>Bugs that are feature requests</li><li>Duplicates</li><li>Stories that contradict each other</li><li>A team and a product owner that have only scattered knowledge about the backlog items</li><li>A backlog spilling over</li><li>Too many tickets that do not fulfill the defined requirements on the definition of ready</li></ul><p>Stakeholders may get the impression that you have lost control over the project.</p><p>But you should benefit from the provided insights and ideas of your stakeholders. Let’s discuss a possible way to gain from this input in the next tip.</p><h3>2. Establish a traceable development process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u20EtJviy5Rkj7cA" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Concerning stakeholder input to the product you may find a solution in using another ticket system, another board, some Wiki or a combination of it.</p><p>Make sure to have an overall traceable development process and communicate it. It is important to generate governance that guarantees</p><ul><li>that the SCRUM team knows about the issues in the backlog</li><li>that other stakeholders are sufficiently well informed what happened to their inquiries</li></ul><p>I suggest working with a service desk for external users. Concerning the team’s and close stakeholders’ submitted improvements, features and found bugs I prefer using Confluence. Here, the main benefit is that you can collect all requirements on Confluence pages and link them to the tickets in the backlog,</p><p>Duplicates can be linked to already available issues — or they can be rejected without having them in the ticket system in the first place.</p><p>When you do this with all your user stories, then you have the following benefits</p><ul><li>It is known (or easy to find out) to anyone involved what is inside your product by collecting a few Confluence pages</li><li>Anyone who has access to the wiki knows the implementation status of the requirements</li><li>You will pass quality assessments with ease if you do document your product development process. It also helps you to keep an overview that you will lose when working solely with a ticket system.</li></ul><p>Now when anyone writes down an issue it is not yet piling up in your ticket backlog. If you have a platform to discuss all new issues within the team (e.g. the refinement sessions), you can clarify the exact meaning, reformulate it, prioritize it — and the whole team will know about it.</p><blockquote><em>Don’t use the agile manifesto as excuse for not writing any documentation and for accepting insufficient processes.</em></blockquote><h3>3. Embrace responsibility</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzVWx1Nw8tFaDy34meaM3w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nick Fewings</a> (adapted) on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is the SCRUM master’s and the developers’ responsibility to establish a good process? Maybe. When it is not happening, when the SCRUM master does not care, or you do not even have one in the team, an efficient product development still needs a process. As a good product owner, you need to make it happen; you have to care about anything that might deteriorate the progress towards a successful product.</p><p>You need to care about the stakeholders, the UI/UX, the DoD, the DoR, the documentation level, technical debt, financials, releases, the team and the company. Some don’t want to do that, but this is what good product owners are made of.</p><p>If the product owner does not care, the product will fail — unless the rest of the team is exceptional. He is the one that needs to emanate leadership and liability. If he does not, it is very likely that the team will drift.</p><p>Quality assurance might be not their responsibility then, or writing end-user documentation, carrying out devops stuff, sitting in some meetings, or something else that is not within the core of a developer’s responsibility. The SCRUM guide loses its meaning.</p><blockquote><em>Don’t promote diffusion of responsibility, but trust and liability.</em></blockquote><h3>4. Stay curious about “the how”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sL1qIVmUy9M2NV6F" /><figcaption>Photo by <a href="https://unsplash.com/@mattwridley?utm_source=medium&amp;utm_medium=referral">Matt Ridley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>…if you can. A general rule is that the product owner states the requirements in terms of user stories. These describe “what” is needed and then the development team realizes a solution by thinking about “how” to do it.</p><p>This approach is generally fine, the product owner needs to have the main focus on the problem and not on the solution.</p><p>However, the product owner should not promote a rather distant customer-supplier relationship between himself and the developers as it deteriorates the team spirit.</p><p>You should try to understand the way the development team is going and whether the approach they have chosen is indeed what is needed. Maybe the “how” does not reflect scalability needs as the “what” was not described clearly enough. You might realize it too late through ignorance.</p><blockquote><em>The product owner’s understanding for how a solution is crafted may be crucial for preventing refactoring and architectural adjustment efforts.</em></blockquote><p>Knowing how stuff works improves the communication with technically interested stakeholders.</p><p>Finally, caring about the “how” helps you to understand the level of quality in your software and the development process. As you cannot get quality into software “at the end”, you must do it continuously to create a successful product.</p><h3>5. Adapt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4rmbNIWpopCQynDu" /><figcaption>Photo by <a href="https://unsplash.com/@chrislawton?utm_source=medium&amp;utm_medium=referral">Chris Lawton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Be agile. I have not seen two projects working with exactly the same process. Depending on the experience, skills, character of the SCRUM team, different expectations, requirements and processes need adaptation.</p><p>When working with a team of experienced postdoctoral algorithm experts that show very strong intrinsic motivation, it will be a completely different way of collaboration than with a team of junior web developers, even when you try to do the same SCRUM approach in both cases.</p><p>For some teams a strong guidance by a SCRUM master is needed, for others it may be more annoying than beneficial as they already know everything they need to know to work as a self-organized, enabled team.</p><p>When you have a fine-grained process in mind that you think everyone needs to stick to, because it worked well in the past, you will not create the highest motivation and efficiency. Hence don’t expect everything to run as it did in your last project or in a book that you read.</p><blockquote><em>Adjust to the circumstances and stay eager to improve.</em></blockquote><h3>6. Read</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ttzovgXhFH9P3AKl" /><figcaption>Photo by <a href="https://unsplash.com/@impatrickt?utm_source=medium&amp;utm_medium=referral">Patrick Tomasso</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As SCRUM became very popular in many industries, everyone seems to have an opinion on it: what it is, what it is not, how the roles are played, what are the benefits and/or drawbacks.</p><p>Many of these opinions may be very superficial due to no direct experience with SCRUM. Still they may seem plausible, or you may have no argument against these opinions even if they lead nowhere.</p><p>If you want to be an expert in your role, you should have a clear view on ‘your’ SCRUM. Even SCRUM masters may have an ideological view on the process that does not consider programming experience, programmer’s emotions and the criticality of certain aspects of software development.</p><p>I suggest that you find two good books on SCRUM and/or agile methods and study these with care. Remember the important lessons and have them available for fruitful discussion. For me two books were easy to read and instructive</p><p>1. Roman Pichler, <em>Agile Product Management With Scrum — Creating Products that Customers Love</em>, Addison-Wesley 2010</p><p>2. Kenneth S. Rubin, <em>Essential Scrum — A Practical Guide to the Most Popular Agile Process</em>, Addison-Wesley 2013</p><p>In a complex project you will encounter situations/process gaps for which you don’t directly see a good solution. You may think, try and evaluate with the team. However, many such problems have already been solved by others.</p><blockquote><em>Do not reinvent the wheel and learn from written down experience.</em></blockquote><h3>7. Work with DoD and DoR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QJLdPMZzSNxs-YeC" /><figcaption>Photo by <a href="https://unsplash.com/@bradencollum?utm_source=medium&amp;utm_medium=referral">Braden Collum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s tempting to neglect the definition of ready (DoR) as product owner, eventually it makes your life harder, doesn’t it?</p><blockquote><em>Comply with the basic SCRUM rules.</em></blockquote><p>What makes a product owner’s life even harder are uncompleted sprints, development artefacts that do not fulfill your expectation, or a pile of questions what your stories are about during the sprint — while you are trying to create roadmaps, clarify requirements, calculate financials and prepare the next workshop.</p><p>While developing a suitable DoR in the SCRUM team, you will realize that the members might expect from you and your user stories something else than you thought.</p><p>The definition of done (DoD) seems to be applied more often, and it is clearly a good idea to have and to use it. If you have requirements on documentation, style guide, test, or whatever fits in your context, you may add it there, the team will usually consent on a reasonable DoD.</p><p>You may create a checklist (e.g. in Jira) that needs to be fulfilled before a story can be really closed, to repeatedly make everyone aware of the existence of the DoD.</p><p>A product owner’s job is challenging and rewarding. Very strong commitment is needed as product owner to cope with the pressure and become successful, and you should be sure that you have it.</p><p>I hope that some of the presented tips will support you on your product journey.</p><h3>Thanks for reading!</h3><p>If you found the read interesting, you might want to catch up on some of my other articles:</p><ul><li><a href="https://medium.com/swlh/the-core-value-of-recommender-systems-for-successful-internet-enterprises-7164a7bacdc6">The Core Value of Recommender Systems for Successful Internet Enterprises</a></li><li><a href="https://medium.com/swlh/iot-a7fd31445902">IoT</a></li><li><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</a></li><li><a href="https://towardsdatascience.com/a-flask-app-for-image-recommendations-a865e1496a0d">A Flask App for Image Recommendations</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2aa7ba54770" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/7-tips-for-product-owners-from-7-years-of-experience-a2aa7ba54770">7 Tips for Product Owners From 7 Years of Experience</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommending Similar Images Using PyTorch]]></title>
            <link>https://medium.com/data-science/recommending-similar-images-using-pytorch-da019282770c?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/da019282770c</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 06:41:27 GMT</pubDate>
            <atom:updated>2020-10-18T15:10:17.480Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Full transfer learning implementation with Resnet18</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0BICenJbn67pM5m1SIc-w.png" /><figcaption>Found similar images using Resnet18 features (Source: M. D. Korzec)</figcaption></figure><p><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">In my last article</a> we introduced the simple logic to create recommendations for similar images within large sets based on the image content by employing transfer learning.</p><p>Now let us create a prototypical implementation in Python using the pretrained Resnet18 convolutional neural network in PyTorch. It will take the content of an image folder and create top-k lists with k most similar images to the input.</p><p>The basic implementation for a simple recommender that uses the Resnet18 net for a fixed set of images will be derived in the following steps</p><p><em>0. Theory rewind: Image recommender logic</em></p><p><em>1. Rescale data</em></p><p><em>2. Use the pretrained Resnet18 network as feature vector generator</em></p><p><em>3. Use the feature arrays to calculate similarity by evaluating cosines of these vectors</em></p><p><em>4. Create top-k lists</em></p><p><em>5. Use top-k lists and visualize recommendations</em></p><p>If you already read my previous article, feel free to skip step 0.</p><p>If you are mainly interested in the prototypical implementation, you can find the Jupyter notebook <a href="https://github.com/MathMagicx/JupyterNotebooks/tree/master/ImageRecommenderResnet18">here</a>. It covers all steps including a sample set of images and a simple visualization for recommended images</p><h3><strong>0.</strong> <strong>Image Recommender Logic</strong></h3><p>We want to recommend similar images to a reference input e.g. for a recommender in an online shop. The similarity is based on the information that are encoded within the pixels, and not its metadata.</p><p>It is assumed that you have gathered data in a folder with jpg images. Then we preprocess the images to fit the input requirements of the selected net (e.g. resize to 224x224 RGB images for Resnet18), we calculate feature vectors for the resized images with the selected net, we calculate similarities based on cosine similarity and store top-k lists to be used for recommendations. Finally, we use the lists for recommendations.</p><p>The overall steps are summarized in the following schematic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VmeJdUM79AtLWKEQINzXw.png" /><figcaption>Full image recommender system schematic (Source: M. D. Korzec)</figcaption></figure><p>The core steps will be carried out with PyTorch, an open source machine learning framework in Python. It comes along with various convolutional networks and weights from pretraining on huge datasets.</p><h3><strong>1.</strong> <strong>Preprocessing</strong></h3><p>The image folder shall be located in the working directory. To fulfill the input requirements from PyTorch’s convolutional networks, independently of the net, we learn from the <a href="https://pytorch.org/docs/stable/torchvision/models.html">PyTorch homepage</a> that for all models we need to normalize the input images in the same way to use the pretrained weights properly. The input needs to</p><ul><li>have 224x224 resolution at least</li><li>be an RGB image (i.e. three color channels)</li><li>have image values that are within the range [0,1]</li><li>consider normalized images with the mean [0.485, 0.456, 0.406] (one value per color channel) and standard deviation [0.229, 0.224, 0.225].</li></ul><p>To rescale the images, we can proceed as follows: Define the transformation, iterate through all image names from the input directory, load the image, apply the transformation, store the transformed image together with the information on its orientation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9c81d149b7eb7d401567b3de8a1d36/href">https://medium.com/media/7b9c81d149b7eb7d401567b3de8a1d36/href</a></iframe><p>The normalization is carried out within the constructor of the conversion class following next.</p><h3><strong>2. Use the pretrained Resnet18 network as feature vector generator</strong></h3><p>To generate features from the rescaled images, we set-up a class containing the relevant information for the network in the constructor</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bedcce3f87b9aa3d6d433e93c382e5c7/href">https://medium.com/media/bedcce3f87b9aa3d6d433e93c382e5c7/href</a></iframe><ul><li>The ToTensor transformation takes our image of the form H x W x C with values between 0 and 255 in each channel and squeezes it to a torch tensor of shape C x H x W with values in [0, 1].</li><li>The normalize operation takes each channel of the image and calculates (image — mean)/std</li><li>The private method getFeatureLayer(self) gives back the feature layer, which is the average pooling layer. It is the last fully connected layer before the small classification vector and it is obtained via model._modules.get(‘avgpool’)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c3bcd77452482c537fef4a4373fa63/href">https://medium.com/media/22c3bcd77452482c537fef4a4373fa63/href</a></iframe><p>The public method getVec(self, img) creates the feature vector from the image input. It uses the defined device (cpu). A function is hooked to the forward call of the network to copy the data from the relevant layer. Therefore the embedding tensor that eventually contains the relevant information needs to have the format of the layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65dc67593f6d0f1c7b43b7549e796d30/href">https://medium.com/media/65dc67593f6d0f1c7b43b7549e796d30/href</a></iframe><p>There is everything at hand to create the feature vectors for all images now. They are collected in the allVectors set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94dde32be8728ebb706762310ae51b13/href">https://medium.com/media/94dde32be8728ebb706762310ae51b13/href</a></iframe><h3><strong>3. Use the feature arrays to calculate similarity by evaluating cosines of these vectors</strong></h3><p>After we calculated all the feature vectors, it is time to calculate the cosines between these. As we calculate the similarity value just by an inner product and normalization, this is one function call employing basic NumPy (numerical linear algebra library) functionality. The matrix is stored as Pandas DataFrame (two-dimensional tabular data structure)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a831fe18b5d1ba41434bc21bb47b97a8/href">https://medium.com/media/a831fe18b5d1ba41434bc21bb47b97a8/href</a></iframe><p>Have in mind that storing the whole similarity matrix is a bottleneck for large scale usage — some more elaborated approach would be needed.</p><h3><strong>4. Use top-k lists for recommendations</strong></h3><p>For the top-k (k most similar image) lists Pandas DataFrames are created from the similarity matrix that contain the similar names to an input and the corresponding similarity values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2969451107505b74ffb6d9a394361ca8/href">https://medium.com/media/2969451107505b74ffb6d9a394361ca8/href</a></iframe><p>tqdm is used to get a progress bar, which is useful when you want to work with many images.</p><h3><strong>5.</strong> <strong>Use top-k lists and visualize recommendations</strong></h3><p>In a last step you should be able to see the similar images to a requested input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d3f081b303863e31f167f5f2ef6e52/href">https://medium.com/media/e6d3f081b303863e31f167f5f2ef6e52/href</a></iframe><p>Let us use this for some of the images provided within the repository</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a891604a6498a2d9f3513a0c35982ae/href">https://medium.com/media/3a891604a6498a2d9f3513a0c35982ae/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*-bjuvYXNxYmrQz1SxnZq6w.png" /><figcaption>Source M. D. Korzec</figcaption></figure><h3><strong>Final notes</strong></h3><p>With the explanations and code above, you should have all the needed basics at hand to work with PyTorch’s pretrained convolutional networks to create a recommender system for similar images. The complete code is available for <a href="https://github.com/MathMagicx/JupyterNotebooks/tree/master/ImageRecommenderResnet18">download</a>.</p><p>If you want to use different models, they are described on the <a href="https://pytorch.org/docs/stable/torchvision/models.html">PyTorch website</a>. When you want to create more experiments, modularize the code and treat the network and its layers only as parameters. When creating experiments with larger sets it is advised to store the intermediate results, e.g. as pickle files.</p><p>If you ask yourself how to run a website that includes such a recommender, you may want to have a look into <a href="https://medium.com/@maciek.korzec/a-flask-app-for-image-recommendations-a865e1496a0d">my follow-up article</a>.</p><h3>Thanks for reading! Liked the topic?</h3><p>If you found the read interesting, you might want to catch up on my other articles on the topic:</p><ul><li><a href="https://towardsdatascience.com/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</a></li><li><a href="https://medium.com/@maciek.korzec/a-flask-app-for-image-recommendations-a865e1496a0d">A Flask App for Image Recommendations</a></li><li><a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">Image Recommendations with PyTorch + Flask + PostgreSQL + Heroku deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da019282770c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/recommending-similar-images-using-pytorch-da019282770c">Recommending Similar Images Using PyTorch</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>
        <item>
            <title><![CDATA[Effortlessly Recommending Similar Images]]></title>
            <link>https://medium.com/data-science/effortlessly-recommending-similar-images-b65aff6aabfb?source=rss-661e2473471a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b65aff6aabfb</guid>
            <category><![CDATA[image-similarity]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[marketing-automation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Maciej D. Korzec]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 07:12:47 GMT</pubDate>
            <atom:updated>2020-10-31T22:15:50.410Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Using features from pretrained convolutional neural networks to generate comparability</strong></h4><figure><img alt="Similar images found within the test set, palaces, forest images and Cathedral in Berlin during the light festival" src="https://cdn-images-1.medium.com/max/1024/1*tODu8i6v5kjxHHco879obg.png" /><figcaption>Automatically selected similar images (Source: M. D. Korzec)</figcaption></figure><p>Let us solve the problem of having an unsorted, huge set of images out of which we want to find a subset of similar images. The solution results in an image-based item-item recommender system that can be used for example in online-shops. To this aim, we will use transfer learning, utilizing pre-trained convolutional neural networks.</p><figure><img alt="Various images from the test set" src="https://cdn-images-1.medium.com/max/605/1*zLaqSIgFoSMR-RwinbAIYg.png" /><figcaption>Private set of images (Source: M. D. Korzec)</figcaption></figure><p>These pictures from my private repository contain varying motives and when facing thousands of images, it becomes exhaustive to find the most similar ones. With the presented solution we will obtain similarity values based on image content (i.e. not on its metadata) as in the example below from the same image set. The first image depicts the queried reference image, a van that we used for a maternity leave trip through Europe, standing on a goat farm somewhere in France.</p><figure><img alt="Query and similar images with similarity values" src="https://cdn-images-1.medium.com/max/1024/1*Ae4Al9x7qBprzXFupEe20Q.png" /><figcaption>Similar images to a query image with similarity values (Source: M. D. Korzec)</figcaption></figure><p>In the row below we see the images that the algorithm selected to be most similar. The numbers beneath the photographs are the similarity values ranging from 0 to 1, with 1 being the highest possible similarity. Not only the images with the red van are shown, also our first rental in yellow that needed to be replaced due to a failing water pump was recommended due to all the other similarities.</p><p>Many online offerings could work with such a recommender to increase conversion rates, be it photographer’s collections, movie recommendations, or other shops that could benefit from image similarities (e.g. CD covers or other products where visual similarity might be conversion increasing). These kind of item-item based system recommender systems are called content-based. For more information you may refer to [1] or for a fast entry one of the blog entries on <em>Towards Data Science</em> [2,3].</p><p>There is a remarkably simple way to achieve such recommendations if you already have basic knowledge of Python and image processing. In the next paragraphs I will provide the high-level logic behind it for a fixed set of images:</p><p>1. Get and preprocess data</p><p>2. Use trained convolutional neural networks as feature vector generators</p><p>3. Use feature vector differences to calculate similarity</p><p>4. Use top-k lists for recommendations</p><p>You can use the neural networks from the shelf, no model engineering or training required. There is no need to clean metadata, there are no hidden efforts, you only need to set-up an efficient data handling once and have no additional work.</p><h3><strong>1. Get and preprocess data</strong></h3><p>To implement even a prototype, a large image test set is needed. I worked with a part of the Coco set [4] and the results were very impressive. Within 15000 images the recommender found very similar contents. However, as the images have different licenses based on the user’s selection in Flickr, I refrain from posting these results here. Instead, I created a different test set for this blog. All posted images are from my local image repository of approximately 5000 images, all in jpg format with different resolutions as Cameras changed.</p><p>Pretrained deep neural networks require input images in a certain format. For this article I used resnet18 [5] within the PyTorch library, it requires 224x224 RGB images as input, with image values in the range [0,1]. The images are normalized to have the mean [0.485, 0.456, 0.406] and standard deviation [0.229, 0.224, 0.225], so they were all rescaled to fit this format (be careful not to lose metadata about the image orientation during transformation). Details about a particular implementation will be presented in my next blog entry. If you want to use other convolutional neural networks, check the input requirements first and adjust the pre-processing accordingly. Furthermore, note that here the weights for resnet18 were obtained from training on ImageNet. Keep in mind that training and test sets shall be different.</p><h3><strong>2. Use trained convolutional neural networks as feature vector generators</strong></h3><p>One characteristic of image related neural networks may strike you as a surprise the first time you realize it:</p><blockquote><strong>Trained convolutional neural networks create feature vectors that can be compared for calculating similarity of images.</strong></blockquote><p>Instead of struggling to find ways to characterize images with classic image processing methods that might be used to compare them (e.g. start with edge detection for different orientations and local edge densities, for example, and then extend for all cases that are not covered with that) use high level feature vectors. The available, trained models already provide everything you need when they have been trained on huge image sets with high motive variability. You do not need to understand any of the entries of the vectors, you just need to know that similar images will have similar entries.</p><p>The following schematic explains the calculation of feature and classification vectors when treating the core network as black box</p><figure><img alt="How a convoluational network works (as black box)" src="https://cdn-images-1.medium.com/max/605/1*AiCylYo6dmSG80i43qa6rw.png" /><figcaption>Convolutional neural net as black box (Source: M. D. Korzec)</figcaption></figure><p>M&gt;n and the feature vector contains a lot of encrypted high-level description of the image. Hence when abstracting all the layers in between and ignoring the classification vector that is not used for the recommender, we just deal with a function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*K--dVFw_-lcoOxMtrCxLfw.png" /></figure><p>that is familiar even from high-school. Here, x is the vectorized RGB image in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*Jvapesf1MbEWa88IiJ6DAA.png" /></figure><p>When using a pre-trained model, all parameters are already fix, so there are no further free variables and they are not listed here. One will have to preprocess given images to fit the used network’s input format as explained in the first part.</p><p><strong>What you don’t need to do</strong></p><p>When you want to train your network from scratch, you need to</p><ul><li>Prepare a lot of data manually (image — classification vector — pairs)</li><li>Spend time on longsome optimization</li></ul><p>The classification vectors (e.g. “the image contains a car” may be represented by a unit vector with the one in the position representing cars) are fixed, the input is fixed, and the weights of the network are optimized to get a guessed classification vector that is as close as possible to the real one. The well-studied form of f(x) allows to optimize the weights with help of automatic differentiation that is used during the optimization iterations and makes deep neural network usage possible in the first place. If you are interested to learn more about related topics, you may refer to <a href="https://towardsdatascience.com/high-school-math-for-machines-differentiable-code-5f588140b148?source=---------2------------------">a former research colleague’s blog post on this topic [6].</a></p><p>A fully connected one-dimensional layer before the classification layer with more entries is a high-level, encrypted description of the contents of the images. Earlier layers only describe low-level features (such as edges) and the classification vector may be rather small, so that the last fully connected layer is a good choice. It will contain usable values even for images with content that was not classified during learning.</p><p>Hence we know that we can spare the efforts of training a neural network and we can still can get feature vectors with one function call f(x) from the image input x. Then we can easily decide when an image is more or less similar to another one.</p><h3><strong>3. Use feature vector differences to calculate similarity</strong></h3><p>To compare the feature vectors derived from the evaluation of the convolutional neural network for different images, employing the cosine similarity is a great and simple approach. Here, you basically just calculate the formula for cosines for all image pairs, doing this for the whole image set yields a similarity matrix.</p><figure><img alt="Cosine similarity visualized" src="https://cdn-images-1.medium.com/max/605/1*ObEFDNrR37K8PgE1x9m8Zg.png" /><figcaption>Cosine similarity (Source: M. D. Korzec)</figcaption></figure><p>In two dimensions the formula is easy to interpret and visualize as it is shown above. It works in the same way in higher dimensions, consider for example the three vectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*0reAfx65LKV0yRUJMxB97A.png" /></figure><p>By intuition, the similarity of a and b shall be higher than that of a and c or b and c. And indeed, when plugging the numbers into above formula, one finds</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*usO6vG03L9w_WML_ToCPDw.png" /></figure><p>Hence, as expected,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*pyDQ_ztNdMuEzlS192ozCg.png" /></figure><p>Similarity calculation is one of the main topics within recommender systems [1]. In our case it should also work to use some other metric describing the difference between the vectors.</p><h3><strong>4. Use top-k lists for recommendations</strong></h3><p>So, overall, when two images are compared, we have already derived the following logical steps to be carried out</p><figure><img alt="Steps from input image to similarity value" src="https://cdn-images-1.medium.com/max/600/1*rfjNHC-AHy76j4lpiTHLyA.png" /><figcaption>Comparing two images (Source: M. D. Korzec)</figcaption></figure><p>You only need to iterate all images from the set of interest. All derived entries (s_kl) together define the full similarity matrix. However, working with the full similarity matrix is not efficient, when using the result for recommendations online. When interested in most similar images, for efficiency one sorts the elements by similarity values and works with a top-k list, the most similar k images. Hence a row k from the matrix (s_kl) is sorted from large to small and highly similar images are kept and used for recommendations. The following diagram explains the collection in smaller vectors/matrices for the generation of top-4 lists from a similarity matrix.</p><figure><img alt="Similarity matrix and top-k lists" src="https://cdn-images-1.medium.com/max/605/1*t6MRS7pkc6_SRdwPLg9yEQ.png" /><figcaption>Similarity matrix and top 4 lists (Source: M. D. Korzec)</figcaption></figure><p>The darker tiles represent the four most similar images to the image represented in that row and are stored separately for efficient requests. Of course, you would use more than four in typical applications.</p><p>When you have all the sorted information in top-k lists and receive a query as input, you only go to the corresponding row of that particular image and present the images stored with the IDs stored in the corresponding row.</p><h3><strong>Takeaway messages</strong></h3><ul><li>When we want to get image-based recommendations, trained convolutional neural networks can do the job.</li><li>We use pretrained models, so there is no need to set-up a training pipeline.</li><li>We essentially only evaluate a function to obtain feature vectors.</li><li>We compare feature vectors by calculating their cosine.</li><li>When new images are added to the set, new similarity values and the top-k lists need to be updated.</li><li>When you start with a sufficiently large image set and a well-trained model, there is no cold-start problem.</li></ul><p>If you have Python code covering the above recommender ideas and it shall be used on a website, there are various ways to do so. In my next posts,<a href="https://medium.com/@maciek.korzec/recommending-similar-images-using-pytorch-da019282770c"> I will explain the main points for a Python implementation of the above steps</a>, and I will explain how a simple Flask based website can be set-up that uses the results.</p><figure><img alt="Similar dandelions found within the test set" src="https://cdn-images-1.medium.com/max/1024/1*BtHhmCF9-Y9D9fNKwBLmuA.png" /><figcaption>Similar dandelion images from the test set (Source: M. D. Korzec)</figcaption></figure><p>[1] C. C. Aggarwal, <a href="https://www.springer.com/de/book/9783319296579">Recommender Systems — The Textbook</a> (2016), Springer</p><p>[2] P. Pandey, <a href="https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7">The Remarkable world of Recommender Systems</a> (2019), towards data science</p><p>[3] B. Rocca and J. Rocca, <a href="https://towardsdatascience.com/introduction-to-recommender-systems-6c66cf15ada">Introduction to recommender systems</a> (2019), towards data science</p><p>[4] T.-Y. Lin et al., <a href="https://arxiv.org/abs/1405.0312">Microsoft COCO: Common Objects in Context</a> (2014); Used: <a href="https://medium.com/images.cocodataset.org/zips/test2017.zip">Test data 2017</a></p><p>[5] K. He, X. Zhang, S. Ren, J. Sun, <a href="https://arxiv.org/abs/1512.03385">Deep Residual Learning for Image Recognition</a>, 2015</p><p>[6] M. Köpf, <a href="https://towardsdatascience.com/high-school-math-for-machines-differentiable-code-5f588140b148">High-School Math for Machines: Differentiable Programming</a> (2020), towards data science</p><h3>Thanks for reading! Liked the topic?</h3><p>If you found the read interesting, you might want to catch up on my other articles on the topic:</p><ul><li><a href="https://medium.com/swlh/the-core-value-of-recommender-systems-for-successful-internet-enterprises-7164a7bacdc6">The Core Value of Recommender Systems for Successful Internet Enterprises</a></li><li><a href="https://towardsdatascience.com/recommending-similar-images-using-pytorch-da019282770c">Recommending Similar Images Using PyTorch</a></li><li><a href="https://medium.com/@maciek.korzec/a-flask-app-for-image-recommendations-a865e1496a0d">A Flask App for Image Recommendations</a></li><li><a href="https://towardsdatascience.com/image-recommendations-with-pytorch-flask-postgresql-heroku-deployment-206682d06c6b">Image Recommendations with PyTorch + Flask + PostgreSQL + Heroku deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b65aff6aabfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/effortlessly-recommending-similar-images-b65aff6aabfb">Effortlessly Recommending Similar Images</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>