<?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 Alex Simkiv on Medium]]></title>
        <description><![CDATA[Stories by Alex Simkiv on Medium]]></description>
        <link>https://medium.com/@alex-simkiv?source=rss-831f45a955ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*kgNB-WbIZ1DiRPL_ow33xQ.png</url>
            <title>Stories by Alex Simkiv on Medium</title>
            <link>https://medium.com/@alex-simkiv?source=rss-831f45a955ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:00:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex-simkiv/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[Enhancing Recommender Systems with Hybrid Knowledge-Graph Attention Networks (KGAT)]]></title>
            <link>https://alex-simkiv.medium.com/enhancing-recommender-systems-with-hybrid-knowledge-graph-attention-networks-kgat-23870e18a16b?source=rss-831f45a955ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/23870e18a16b</guid>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[graph-attention-networks]]></category>
            <category><![CDATA[attention-network]]></category>
            <dc:creator><![CDATA[Alex Simkiv]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 08:03:27 GMT</pubDate>
            <atom:updated>2023-12-18T08:03:27.304Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhancing Recommender Systems with Hybrid Knowledge-Graph Attention Networks (KGAT)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*axHzxajp6xseGktq" /></figure><p>In the competitive digital market, keeping customer interest is crucial for any business. Recommender systems are key tools in this, helping to keep users engaged and loyal. Graph-based recommender models are particularly effective, and able to handle complex data and relationships within their networks.</p><p>Especially for businesses with frequently changing products, finding a recommender system that can adapt is essential. Our KGAT-based system is built for this kind of environment, making use of a variety of data to provide recommendations that keep up with your product’s development.</p><p>KGAT (Knowledge Graph Attention Network) is one such system that initially focused on item-side information to guide user preferences. By integrating user-side features into the KGAT framework, we’ve transformed it into a hybrid model, a pioneering architecture that not only understands items but also the multifaceted users interacting with them.</p><h3>Why graph recommender?</h3><p>Graph-based architectures for recommendation systems represent a transformative leap from traditional matrix-based models and offer a compelling suite of benefits that can significantly enhance the performance and relevance of recommendations:</p><ol><li><strong>Complex Relationship Mapping</strong>: Graphs are adept at illustrating intricate relationships between users and items, capturing the subtle nuances of user preferences.</li><li><strong>Scalability</strong>: They can easily scale by adding new users, items, and interactions, making them ideal for growing businesses.</li><li><strong>Improved Recommendation Quality</strong>: The interconnected nature of graphs facilitates more accurate predictions by considering the broader context of user-item interactions.</li><li><strong>Sparse Data Management</strong>: Graphs can handle sparse datasets efficiently, making meaningful connections even with limited user interaction data.</li></ol><p>In practice, sparse datasets are a challenge, especially with constantly changing products. This variety can result in gaps where interactions are minimal or entirely missing, posing a challenge for traditional matrix factorization methods which require dense data to function optimally. Graph architecture offers a practical solution by naturally incorporating various data types into a single model. This approach allows for effective recommendations even when direct user-item interactions are limited, making KGAT a more suitable option in these situations.</p><h3>Knowledge graph structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*-KArPr2SUrLpf7G4" /></figure><p>At its core, a knowledge graph is an intricate network that links entities — such as users, items, and their features — through various types of relationships. It organizes information into nodes and edges. Nodes represent entities (e.g., users, products, categories) and edges depict their relationships (e.g., purchased, viewed, rated). This allows the creation of a detailed map of interactions and interests. It’s a versatile structure where additional layers of information can be integrated, such as location info, social networks, and semantic information, enabling a comprehensive understanding of the user’s context and environment.</p><h3>KGAT modification</h3><p>The <a href="https://arxiv.org/abs/1905.07854">original KGAT model</a> uses item-side information to construct a knowledge graph that captures the relationships between items and user interactions. It applies an attention mechanism to this graph, which allows it to learn the importance of different items and their features, thus generating recommendations based on the items’ interconnected attributes.</p><p>The modification of the KGAT model to include user-side features is a strategic enhancement designed to refine the accuracy and relevance of recommendations further. This modification enriches the model’s understanding of user behavior and preferences, leading to predictions that are not only based on item attributes but also shaped by individual user characteristics, which significantly improves the relevance of the recommendations provided.</p><p>As the first step, we created a comprehensive knowledge graph that represents users, items, their attributes, and the interactions between them. This graph is constructed with nodes representing both users and items, while the edges represent the interactions (ratings) or relationships between users or items and their features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*Gxt3vUBDD5_DX3MF" /></figure><p>It is crucial to differentiate between various types of interactions; for instance, positive and negative ratings are treated as distinct relations, each with its unique influence on the user’s preference profile.</p><pre># Extract knowledge graph head and tail nodes<br>features_kg = self.features_kg<br>entity_head = features_kg[self.entity_head_key]<br>entity_tail = features_kg[self.entity_tail_key]<br># Extract user and item nodes from interactions<br>features_interaction = self.features_interaction<br>user_data = features_interaction[self.user_field_key]<br>item_data = features_interaction[self.item_field_key] + self.n_users<br># Source and target tensors for the graph<br>source_entities = torch.cat([user_data, item_data, entity_head])<br>target_entities = torch.cat([item_data, user_data, entity_tail])<br># Rating relation transformation to KG token<br>interaction_rating = torch.clone(features_interaction[self.rating_field_key])<br>mapped_ratings = interaction_rating.apply_(lambda x: self.map_rating_to_token(x))<br># Relation extraction from the knowledge graph<br>kg_relation = features_kg[self.relation_key_field]<br>interaction_relation = mapped_ratings.repeat(2).type(kg_relation.dtype)<br>graph_edges = torch.cat([interaction_relation, kg_relation])</pre><p>Following the construction of the knowledge graph, the model training process is divided into two phases. In the initial phase, the model uses direct user-item interactions to develop robust user and item embeddings. This is achieved by creating a user-item graph and applying the Bayesian Personalized Ranking (BPR) loss function. BPR works on the principle that a user prefers an item they have positively interacted with over items they have a negative experience with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XJMHHkqWeN52-5ki" /></figure><p>The second phase of training broadens the scope to include all additional connections and external side information. This phase builds upon the user and item embeddings obtained from the first phase, integrating side information such as user demographics or item categories into the model. Attentive embedding propagation layers blend this diverse data into a unified vector. These layers recursively propagate embeddings from the neighbors of a node to refine its representation.</p><p>During this propagation, a knowledge-aware attention mechanism is used to determine the weight of each neighbor’s influence. This mechanism ensures that each feature, whether related to the user or the item, is appropriately factored into the overall recommendation. It’s a process that not only considers direct interactions but also the broader context of those interactions, thereby enhancing the model’s ability to make nuanced and contextually aware recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YaZ8V4Jyf4y9zLQt" /></figure><p>This systematic approach transforms the KGAT model into a hybrid system that captures both direct user-item preferences and the wider context of those preferences, resulting in a sophisticated recommender system capable of delivering personalized user experiences.</p><h3>Evaluation</h3><p>One reason for utilizing Knowledge Graphs (KG) is to mitigate the sparsity problem that often constrains the effectiveness of recommendation systems. It is challenging to create ideal representations for users with minimal interactions. We evaluated the adapted KGAT on a specialized dataset characterized by low sparsity and obtained the following metric outcomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/0*shQX7LmU9nkG5z3W" /></figure><p>Also, we evaluated the CatBoost model trained on the same dataset and compared metric results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/0*WuVEvjfvlEXs3QQx" /></figure><p>The KGAT model has shown better performance in this evaluation compared to CatBoost.</p><h3>Limitations</h3><p>One of the primary challenges is the complexity of the knowledge graph itself. As the number of users, items, and features grows, so does the graph, which can lead to increased computational demands. This complexity can affect the model’s scalability and performance, particularly when processing real-time updates or handling large-scale data.</p><h3>Summary</h3><p>KGAT, enhanced to include user-side features, offers more personalized and contextually relevant recommendations using a comprehensive knowledge graph. The performance of KGAT, as demonstrated by key metrics, surpasses traditional algorithms like CatBoost, providing both higher accuracy and a broader diversity of recommendations. However, the system’s complexity presents ongoing challenges. Despite this limitation, KGAT’s ability to dynamically adapt to new information and model complex relationships holds promise for businesses looking to leverage advanced recommender systems.</p><h3>Acknowledgments</h3><p>I want to thank my colleagues <a href="https://medium.com/@andy.bosyi">Andy Bosyi</a>, <a href="https://medium.com/@volodymyrsendetskyi">Volodymyr Sendetskyi</a>, <a href="https://medium.com/@vladyslav.fliahin_1709">Vladyslav Fliahin</a>, <a href="https://medium.com/@ivanna.chovhan131">Ivanna Chovhan</a>, and <a href="https://medium.com/@nazarsavchenko">Nazar Savchenko</a> for fruitful discussions, cooperation, and helpful tips as well as the entire <a href="https://mindcraftshaft.medium.com/">MindCraft.ai</a> team for their constant support.</p><p>Alex Simkiv,</p><p>Data Scientist, MindCraft.ai</p><p>Information Technology &amp; Data Science</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23870e18a16b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting information from unstructured sources]]></title>
            <link>https://medium.com/data-science/extracting-information-from-unstructured-sources-b9d8bd14e70a?source=rss-831f45a955ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9d8bd14e70a</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[unstructured-data]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[web-search-engine]]></category>
            <dc:creator><![CDATA[Alex Simkiv]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 07:37:59 GMT</pubDate>
            <atom:updated>2021-01-18T23:19:40.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*Tg5bkkpMHZ1-Zei7" /></figure><h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h3>Extracting Information from Unstructured Sources</h3><h4>Searching for Related Organizations Addresses with Web-Search, spaCy, and RegEx</h4><h3>Problem Statement</h3><p>Recently, one of our clients has contacted us with an interesting problem. It was an investment company, which needed to calculate potential risks for their objects of investment. They required a solution that would help generate a list of all addresses (or GPS coordinates) that were associated with a specific company name. The problem our client faced was that a lot of companies could have many different subdivisions with different names in different languages. Plus, a lot of companies have departments all over the world. Also, the company could have different hidden locations, associated with them, which are not stated directly on their legal documents.</p><p>We started with a small Proof of Concept to check if there is an approach that can solve one or a few of these problems. The result had to be presented as a graph of geo-locations, with described relations to other vertices and a given company name.</p><p>The interesting challenge was that we were not provided with any data or directions. So the first problem we focused on was data sources. After a short research, we divided all available and relevant data sources into three major categories:</p><ol><li>Public or private registries</li><li>Social networks</li><li>Search engines</li></ol><p>Considering drawbacks of each datasource we decided to use the last category for our PoC, since registries and social networks are hard to interact with. In addition to being hard to find, registries provide data in various formats. This makes it hard to use even a few of them for a short PoC.</p><p>The approach we chose in the end was not an easy fruit. We have to try a few approaches which didn’t work for several reasons. We will briefly describe what we did and how to point out the most promising results and causes of failure.</p><h3>The First Approach</h3><p>Our main idea for solving this problem was based on using <a href="https://spacy.io/"><strong>spaCy</strong></a>. This framework has a built-in ability to tag organizations and locations in a text, the ability which we found very useful for this problem. As soon as we chose a data source, we started to analyze web-pages related to a few randomly chosen organizations. After having tagged a few web-pages texts with <strong>spaCy</strong>, we found patterns, which appeared mostly when a company address was involved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8mQkLfYWgjWwcH2Jtj0qQ.png" /></figure><p>With this pattern in mind, we started working on the following idea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQbPU_n63GzGbNVb" /></figure><p>We search the web for a term that looks like “&lt;Company&gt; address”. The returned pages are proclaimed to be depth 1 pages. Then, we look for the above-stated pattern on each of the returned web-pages and extract a corresponding text — organization name and its address. After this, we grab all the links on those pages, proclaim their pages to be depth 2 pages and continue in a similar fashion with these pages. This process gives us a graph with vertices, corresponding to web-pages and organizations (with their addresses). The first ones are connected, while the second ones are only connected to the first ones.</p><p>The implementation of the process described above was a simple <a href="https://scrapy.org/"><em>scrapy</em></a> web-crawler. After receiving an initial list of links (depth 1 pages), the crawler looked for a pattern, collected links and proceeded to other pages, saving all results in a CSV-file. To check the pattern we used a tag-by-tag sliding window approach, which simply meant counting the number of specific tags or numerical tokens fitting into a sliding window.</p><p>Despite the simplicity of this approach, it had instantly failed due to many reasons. First, even for a few initial links (say 100), the number of web-pages linked to them was measured in gigabytes. The process took too much time and resulted in a very small number of useful texts. Second, there were a lot of texts that contained neither the organization’s name, nor its address but still fit into our pattern filter. This was mostly because many words related to addresses were tagged as organizations or persons by <strong>spaCy </strong>or were not tagged at all.</p><p>We decided to analyze the collected data and label them. Only ~20% of collected texts contained both an organization name and its address. The other ~80% had a lot of extra text, missing an organization name or a meaningful part of the address. This kind of data is hard to work with. However, while analyzing this data we saw that <strong>spaCy </strong>works well with organization names themselves. But our pattern was ignoring the majority of such occurrences. Another thing we found out was that almost every country has a different address template. Even although that we used corresponding <strong>spaCy </strong>models for different languages, such a simple pattern could not cover even a few address templates.</p><p>This has driven us to the conclusion that such an approach is not working well for the given problem.</p><h3>The Second Approach</h3><p>Having taken into account all this information, we decided to simplify our PoC and focus only on US-based organizations and English pages. Plus, we decided to divide the problem into two parts: looking for related organizations and extracting the address for a single organization.</p><p>To solve the first problem, we decided to try this: if some organization is mentioned on the web-pages related to a given company, then this organization is somehow connected to this company. For a moment, we would omit the question of how exactly an organization is connected to a company (opponents, subsidiaries, the same foundation group, etc.) since it appears to be a more complex problem to solve. To strengthen the observed relation, we assumed, that the company must be also mentioned on some company’s web-pages.</p><h4>Extracting Potential Organization Names</h4><p>We started with a simple search for related organizations using web-search and <strong>spaCy</strong>. We used Bing, however, you can use any other search engine available. We will show you the pieces of code in Python, which we used to collect data. Note that our code does not strive for elegance since it was written for a PoC and of course, can be enhanced or optimized.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e1f9084df7ab8d7087537c3e5a4808/href">https://medium.com/media/76e1f9084df7ab8d7087537c3e5a4808/href</a></iframe><p>First, we searched for a term that looks like this: “&lt;given company name&gt; companies”. Thus, if a given company is Samsung, then the search term would be: “Samsung companies”.</p><pre>companies_search = bing_search(“{} companies”.format(COMPANY_NAME))</pre><p>That is how we received ten search results, enough for a start. Then, we extracted each corresponding web-page, tagged its text with <strong>spaCy </strong>(we didn’t need to tag HTML tags, scripts, attributes and so on), and extracted only those that were named <strong>ORG</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cce1c0de47ae531164404a8b5908f17/href">https://medium.com/media/5cce1c0de47ae531164404a8b5908f17/href</a></iframe><p>As we already mentioned, we also strengthened the power of the observed relation by checking if a given company was mentioned on the pages related to the found named entities. For this purpose, we performed a search for each found named entity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289d001bd6bf4479ab7931d57c47acbc/href">https://medium.com/media/289d001bd6bf4479ab7931d57c47acbc/href</a></iframe><p>Then, we preprocessed all collected data and saved them into csv files for further use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee2978cebbb22fd1b952adeb7be0c021/href">https://medium.com/media/ee2978cebbb22fd1b952adeb7be0c021/href</a></iframe><p>Now, to check if a given company is related to found named entities, we implemented a scrapy crawler. Using a list of URLs and a company’s name it processed each URL and counts all mentions of a given company. Please find it’s main method without the whole initialization, which mostly deals with files infrastructure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0955c1e0ea4769c1da86b3d9a2e33996/href">https://medium.com/media/0955c1e0ea4769c1da86b3d9a2e33996/href</a></iframe><p>We simplified the code removing some needed <strong>try</strong> … <strong>except</strong> statements or other very specific parts of the code. Also, the decision to count the number of mentions appeared to be not completely correct: it would fail in some (not all) complex cases when the given company name consisted of two or more words. The more proper way to do this would be using the <strong>spaCy </strong>tokenizer and comparing tokens.</p><p>Once the crawler had finished the work, we got a CSV file with IDs of only those potential organizations, that had a strong observed relation to a given company. A list of nearly a thousand found named entities for Samsung decreased to a list of just nearly 6 hundred. What remained looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQij78TtWHl7BgCD1yPlSw.png" /></figure><p>At first sight, it looked good. However, if we take a closer look at this list, we will find that a lot of named entities there are not organization names at all. For example, <em>Samsung Annual Report</em> is perhaps just a header of some text, but not an organization name. And there is nothing to blame <strong>spaСy </strong>for: all these named entities do look like organizations.</p><p>We labeled the collected data manually. And what we saw was that this approach gives a pretty good recall. In fact, for the Samsung company, our list contained nearly 80 of their different subdivisions, legally related organizations as well as their opponents in different areas. However, it had a low precision rate: nearly 60% of those named entities were not valid organization names (nor parts of full organization names)</p><p>So we needed some kind of a model for filtering out what was not a valid organization name. The approach we settled for was a little bit complex and too big to describe it here. <a href="https://towardsdatascience.com/classifying-spacys-org-named-entities-with-statistical-text-analysis-and-machine-learning-7e99ed7a58c3">We wrote a separate article on this topic.</a></p><p>Additionally, we tried to build a model for classifying organizations by their relationship to a given company. That model was supposed to be based on correlations between specific words and the number of mentions of a given company alongside some named entities. This approach, however, did not work.</p><h4>Addresses Extraction</h4><p>With the above-mentioned model, we filtered out what was not an organization name. Now that we have a list of organizations related to a given company, we need their addresses. To achieve this goal, we performed a search for each organization with a search term that looked like <strong>“&lt;organization name&gt; address USA”</strong>. It gave us a list of web-pages that potentially contained USA addresses of related organizations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcd77c47cfcf578c2ad10b9dd6cc931f/href">https://medium.com/media/bcd77c47cfcf578c2ad10b9dd6cc931f/href</a></iframe><p>In general, extracting addresses from an HTML page is quite tricky. The process must include finding different patterns that are common for separate countries, dealing with a list of predefined words ( like country names, states, regions, etc.), and understanding what piece of text is an address. This is harder when you need to extract an address that is written in a different language or is presented on a web-page in the form of a table with rows like <em>Street, House #, State, </em>etc.</p><p>As for the PoC, we decided to focus on the simplest case — USA addresses written in a single <em>p</em> tag. For this we built a simple regex which took into account the order of <strong>spaCy’s</strong> named entities, numbers, states and, perhaps, the country. An interesting point here was that we needed to include <strong>spaCy</strong>’s organization (ORG) tag in it, since very often parts of an address where tagged with this tag. Also, we needed to build a custom regex for the US states. Even despite the fact that most of the states had a proper context around them, they were still rarely tagged by <strong>spaCy</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3c991b996fc7ff04e421305b4bbd079/href">https://medium.com/media/f3c991b996fc7ff04e421305b4bbd079/href</a></iframe><p>For the address_re here: n — is a small number, followed by up to 4 <strong>spaCy </strong>ORG, LOC, FAC or GPE tags ((l|f|g|o){0,4}), then state(s) and zip(z) and, perhaps GPE tag(g?), which would most likely by country.</p><p>From this text we extract addresses in the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c16391e9df32918e4f875488af0c16ff/href">https://medium.com/media/c16391e9df32918e4f875488af0c16ff/href</a></iframe><p>All the code above we use in our scrapy crawler to collect addresses. Again, its main method looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4683106b7043214a969fd01d5620f46/href">https://medium.com/media/c4683106b7043214a969fd01d5620f46/href</a></iframe><p>With this, we passed through each search result and extracted addresses of organizations. For sure, this solution is not perfect. A lot of extracted texts were not addresses at all or contained plenty of extra text. However, this happened relatively rarely compared to the amount of extracted data. All these actions resulted in a list that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QBp7rDqMwgXfdoal" /></figure><p>We used <em>geopy</em> Python package to get GPS coordinates of the address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/374af942d8b0731cb8d0c5276dcf0cae/href">https://medium.com/media/374af942d8b0731cb8d0c5276dcf0cae/href</a></iframe><p>Note that those geocoders don’t play well when you perform multiple requests sequentially. That’s why we added a random delay, just for fun :-).</p><p>Now, having visualized all collected data, we received a map with specified locations of organizations related to some given company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*oi854PhuTAvOSEb7" /></figure><h3>Conclusion and Further Steps</h3><p>Here is a list of further steps that have the highest priority:</p><ol><li>Building a model to classify the type of relationship between two companies. Or, at least, between a given company and a found one. This can be achieved in various ways, starting with the analysis of word frequencies, like in the model mentioned above, and ending with complex ML systems, depending on the needed result and complexity of the problem.</li><li>Enhancing the address extraction. This would include dictionaries of predefined words, formats for different countries, and different language tagging systems.</li><li>An analysis of organizations now related to extracted addresses, since often a few related companies are registered or located at the same address.</li><li>Enhancing the existing approach. A lot of things were done in the simplest way possible. Many pieces of code could be improved to achieve more accuracy or more proper data.</li></ol><p>Perhaps, some specific language systems or translators will be needed for countries like China, Japan, Korea, and others.</p><p>To sum up, we now have data to build a two-layer graph of entities related to a given company. The first layer of the graph would be a layer of organizations, somehow related to a given company. It can include different types of subsidiaries, opponents, legally connected companies, etc. The second layer is a layer of addresses of those organizations. This graph can be used for building a general company profile, calculating investment risks, company stock price, and much more.</p><h3>Acknowledgments</h3><p>I want to thank my colleagues <a href="https://medium.com/u/8bc8d2a62041">Andy Bosyi</a>, <a href="https://medium.com/u/5b6f8e76e312">Mykola Kozlenko</a>, <a href="https://medium.com/u/29c9ae323b06">Volodymyr Sendetskyi</a>, <a href="https://medium.com/u/a1d9d09474e8">Viach Bosyi</a> and <a href="https://medium.com/u/7656f83999e3">Nazar Savchenko</a> for fruitful discussions, cooperation, and helpful tips as well as the entire <a href="https://medium.com/u/bad3e22805b3">MindCraft.ai</a> team for their constant support.</p><p>Alex Simkiv,</p><p>Data Scientist, MindCraft.ai</p><p>Information Technology &amp; Data Science</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9d8bd14e70a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/extracting-information-from-unstructured-sources-b9d8bd14e70a">Extracting information from unstructured sources</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[Practical Guide to Semantic Segmentation]]></title>
            <link>https://medium.com/data-science/practical-guide-to-semantic-segmentation-7c55b540489c?source=rss-831f45a955ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c55b540489c</guid>
            <category><![CDATA[semantic-segmentation]]></category>
            <category><![CDATA[document-management]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[ner]]></category>
            <dc:creator><![CDATA[Alex Simkiv]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 11:02:06 GMT</pubDate>
            <atom:updated>2021-01-04T16:25:58.469Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>A baseline approach to detecting documents in images for further processing — Optical Character Recognition, Document Type Detection, Named Entity Extraction and similar tasks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7QQ72xVOOuvGNov" /><figcaption>Photo by <a href="https://www.instagram.com/silantevdan/">Daniil Silantev</a>.</figcaption></figure><h3>Introduction</h3><p>Object detection and extracting, especially with semantic segmentation, is a well-studied problem with a developed set of almost standard solutions. So if you’re a seasoned data scientist, most likely you won’t find anything new or special in this article. But if you’re relatively new to data science and image processing, in particular, this article may become your practical tutorial on making your first semantic segmentation model. Please note, that we’re not going to discuss any theoretical basis for semantic segmentation. This is only an example of a code\solution that was developed as a baseline approach during a proof of concept.</p><p>Our journey begins with a simple customer request. She needed to detect documents of a kind in images. To deliver this we need a dataset of sample documents. Most datasets that contained photos of documents do not provide the ground truth data we needed to train and evaluate our PoC. Fortunately, we found a dataset suitable for this particular problem: <a href="https://arxiv.org/abs/1807.05786">MIDV500</a> : A Dataset for Identity Documents Analysis and Recognition on Mobile Devices in Video Stream. All source document images used in MIDV-500 are either in the public domain or distributed under public copyright licenses.</p><h3>OpenCV Approach</h3><p>Before we start showing and explaining the code, we would like to point out that it usually takes a few futile attempts and trying out things that don’t work in order to get to the working result, it is a necessary learning curve. This time we started our efforts performing some straight actions with OpenCV, like:</p><ul><li>filtering</li><li>edges detection</li><li>brightness\contrast,etc.</li><li>thresholding the image</li><li>extracting contours</li><li>selecting the one that fits our given criteria.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*8zFBKuDUYrvXKpU_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*ERuDIKhtweBNBgi1" /></figure><p>There were, of course, a few images, where this relatively simple approach worked well (like the one in the bottom right corner of the bottom image). But for most of the images, we had to conclude that their colors, lightning, shadows, blur, and other conditions were so versatile, that one simple image processing algorithm can’t cover it all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*GltKZwg7Ea37xw7_" /></figure><p>Although we believed that there might exist an algorithm that can perform well under these conditions, we saw no point in continuing to work on this approach. So we switched to a little more complex approach: neural networks.</p><h3>Semantic Segmentation Approach</h3><p>Specifically, we decided to try semantic segmentation. That’s mostly because we have created a few of them, that developing a new one took only a few hours to write generators and train the model. We didn’t even tune hyperparameters, since we achieved our purpose on the very first try.</p><p>To create a model we need to prepare the data and implement the model itself. Generally, most NN models may be split into 3 main parts: the generator, the predictor, and the neural network itself. Additionally, there might be some trainers.</p><h3>Data Preparation</h3><p>We converted the data in our dataset (mentioned above) into the following format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*bCd9jFD__C0VyaZ2" /></figure><p>Here:</p><ul><li><strong>path</strong> — stands for the path to an image inside a dataset</li><li><strong>x0, y0, x1, y1, x2, y2, x3, y3 </strong>— ground truth quadrangle coordinates</li><li><strong>part</strong> — a number specifying a part of the dataset (the number that goes first in the name of each folder)</li><li><strong>group</strong> — background used on the image (name of the folder containing the image)</li></ul><h3>The Generator</h3><p>The purpose of a generator is to provide batches for training. Therefore, it should provide both input and output images. An example of initialization of such a generator may look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a2c7aff7f3fa4f71c7474c7e8ef916/href">https://medium.com/media/55a2c7aff7f3fa4f71c7474c7e8ef916/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2fc44dcf822068576b4a91f26aabff/href">https://medium.com/media/9a2fc44dcf822068576b4a91f26aabff/href</a></iframe><p>Here the <strong>samples</strong> parameter is simply a part of the dataframe we prepared beforehand, <strong>data_path</strong> — a path to the dataset. The idea is simple: iterate through all of the images, resize them, draw the ground truth on a blank image, and store them in the corresponding variables. We believe the code above to be self-explanatory (just read it sequentially and don’t jump into the middle). Feel free to contact me if any doubts :-). Then, we can return a batch using <strong>__getitem__</strong> method, as simple as that:</p><pre>#create you generator<br>your_sample_generator = BatchGenerator(your_df,<br>                                       your_data_path, <br>                                       batch_size)<br>#return a batch<br>next(your_sample_generator)<br>#return a butch number i<br>your_sample_generator[i]</pre><h3>Neural Network Architecture</h3><p>Now let’s create our neural network architecture. The provided architecture has proved to work well enough for a great variety of similar tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4af825b19cd8eaaa0836b44fe8008044/href">https://medium.com/media/4af825b19cd8eaaa0836b44fe8008044/href</a></iframe><p>The idea behind this model is the next: we downsample the input image to the size 8x8 while learning some features about most of the regions. Then, we pass those features to a few dense layers that, in fact, make a decision on whether there is an ID card on the image and if yes, where it is located. And finally, we use that decision as well as the features calculated during the downsampling part (all those <strong>Concatenate</strong> layers are implementing so-called skip-connections in CNN) to clarify the exact shape of the prediction. Despite this decision layer inside the model, it is still a semantic segmentation network that produces a probability map to define whether a pixel belongs to an ID card or not.</p><h3>Training The Model</h3><p>Now we proceed to the training of our model. First, let’s split the data into training and testing sets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8912ef4311c6c0b17687e25c33732fd/href">https://medium.com/media/b8912ef4311c6c0b17687e25c33732fd/href</a></iframe><p>and initialize the generators:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f97ecac08f915b4fbb732367ae56f8f/href">https://medium.com/media/9f97ecac08f915b4fbb732367ae56f8f/href</a></iframe><p>Build the model and compile it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab327218d83d6369b4b5fc4b2bd5991/href">https://medium.com/media/eab327218d83d6369b4b5fc4b2bd5991/href</a></iframe><p>We got the next model architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*OMC6S5rUTmloiUSVLA-cIw.png" /></figure><p>Well, the model appears to be not too big (832Kb). So, perhaps, it can even fit into a phone :-)</p><p>Finally, we can train our model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5174d0121e73b779a5ac36003f5ab288/href">https://medium.com/media/5174d0121e73b779a5ac36003f5ab288/href</a></iframe><p>We used a few simple callbacks to monitor training process, delivering easy to interpret plots and storing training results for further usage. If you are interested in actual code please let me know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IVfH1PRh2hhKva_7" /></figure><p>To analyze model results we plot accuracy against IoU threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*rhBAE7kexZ9o9S0r" /></figure><p>We can see that for an IoU threshold of 0.8 we reached a ~71% accuracy. It’s not perfect, but we didn’t even perform any optimizations for this model. There is room for improvement. Please find an example of the model input, ground truth, and its prediction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*73FXSKynH_3qEl7y" /></figure><p>Looks promising, right?</p><h3>The Predictor</h3><p>With all that said and done, we can finally extract ID cards from images. For this let’s prepare a few helper functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766c53b4c908d3d4431884281912fc25/href">https://medium.com/media/766c53b4c908d3d4431884281912fc25/href</a></iframe><p>And use them in our final model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f2821309acfde26ded54aed790f84d/href">https://medium.com/media/a7f2821309acfde26ded54aed790f84d/href</a></iframe><p>Explanation: after NN makes its prediction on the resize of a given image, we threshold the result by 0.5 and search it for all the contours. After we smooth each contour, we check whether it has 4 edges and if it occupies the minimum allowed area. If yes, it is checked to be the biggest among other such contours. The selected contour is resized correspondingly to an input image and the rectangle is extracted using OpenCV tools. The result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/0*_zi5IW8CTWtM3a9r" /></figure><p>That is, of course, not even close to what can be called a solution. There are still many things that can be improved and tested. Here are a few of them:</p><ol><li>Trying object detection instead of semantic segmentation (YOLO, perhaps)</li><li>Tuning the hyperparameters, as a potentially better data split strategy</li><li>Analyzing the nature of mistakes</li><li>Improving the prediction processing algorithm to better select hardcoded values</li></ol><p>This turns into an even greater list when you need to generalize this solution to process arbitrary documents. But still, this may be a good starting point for the task.</p><h3>Acknowledgments</h3><p>I want to thank my colleagues <a href="https://medium.com/u/8bc8d2a62041">Andy Bosyi</a>, <a href="https://medium.com/u/5b6f8e76e312">Mykola Kozlenko</a>, <a href="https://medium.com/u/29c9ae323b06">Volodymyr Sendetskyi</a>, <a href="https://medium.com/u/a1d9d09474e8">Viach Bosyi</a> and <a href="https://medium.com/u/7656f83999e3">Nazar Savchenko</a> for fruitful discussions, cooperation, and helpful tips as well as the entire <a href="https://medium.com/u/bad3e22805b3">MindCraft.ai</a> team for their constant support.</p><p>Alex Simkiv,</p><p>Data Scientist, MindCraft.ai</p><p>Information Technology &amp; Data Science</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c55b540489c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/practical-guide-to-semantic-segmentation-7c55b540489c">Practical Guide to Semantic Segmentation</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[Point Cloud Data: Simple Approach]]></title>
            <link>https://medium.com/data-science/point-cloud-data-simple-approach-f3855fdc08f5?source=rss-831f45a955ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3855fdc08f5</guid>
            <category><![CDATA[categorization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[point-cloud]]></category>
            <category><![CDATA[lidar]]></category>
            <dc:creator><![CDATA[Alex Simkiv]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 14:38:58 GMT</pubDate>
            <atom:updated>2020-11-10T11:54:43.564Z</atom:updated>
            <content:encoded><![CDATA[<h4>LIDAR data for power line detection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xv_c-AlZZAaD_lhQ" /></figure><h4>Introduction</h4><p>In recent years, there was great progress in the development of LIDAR detectors that resulted in huge amounts of raw data. LIDARs are now more accurate and provide a much higher resolution than even 10 years ago. Aerial-based LIDARs have become an efficient method for receiving information about the environment. Nevertheless, the data you get is in fact only a collection of sparse points that may provide some nice visualization but require extensive processing when it comes to more practical purposes. Unfortunately, as of now, the progress of computer vision mostly concerns structured two-dimensional data (photo, video). The current methods do not generalize to multidimensional sparse data like Point Cloud that we receive after a basic LIDAR data pre-processing. Extensive research is being done in the field. We</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWZsQ66k0Vz_rVKz" /></figure><p>should particularly mention PCL — a graf of libraries developed by a great international community to provide instruments for both 2D and 3D data for a wide variety of applications. Unfortunately, at the moment it is not an easy task to apply the library to some solution of interest. It often means that you have to dive into the library too deep. It makes sense for production-grade products that need high scalability. But it may be too costly for a PoC development. Therefore, I decided to try what can be done with point cloud data using a simple approach and pretty standard Python libraries (PCL can be used from Python but only so far, since only small subsets can be integrated seamlessly).</p><h4>Data for the Experiment</h4><p>As an example let’s use the data generated by an aerial-based LIDAR for the detection of power lines. Power lines are often clearly visible in point cloud visualization. However, mapping the points that belong to a power line requires a lot of manual efforts. On the other hand, simple geometrical consideration may provide us with means to greatly simplify or even automate such processing.</p><p>The power line on the picture is actually a collection of points which form certain geometrical patterns. To simplify further categorization, I decided to check how we can form clusters out of these points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rQYVqcZSNFGXu9qf" /></figure><h4>Software Used for the Experiment</h4><p>I will use NumPy, Sklearn, Laspy and SciPy libraries for the purpose of cluster formation and matplotlib for visualization.</p><pre>import laspy</pre><pre>import scipy</pre><pre>import numpy as np</pre><pre>import matplotlib.pyplot as plt</pre><pre>from sklearn.cluster import DBSCAN</pre><pre>from sklearn import metrics</pre><pre>from sklearn import preprocessing</pre><pre>from mpl_toolkits.mplot3d import Axes3D</pre><pre>from matplotlib import path</pre><p>Laspy is great for handling point cloud data in Python. We read point cloud data from a las file and check the shape of the actual dataset.</p><pre># Open a file in read mode:</pre><pre>inFile = laspy.file.File(“./LAS/simple.las”)</pre><pre># Grab a numpy dataset of our clustering dimensions:</pre><pre>dataset = np.vstack([inFile.x, inFile.y, inFile.z]).transpose()</pre><pre>dataset.shape</pre><p>(5942479, 3) — our point cloud consists of 5942479 points. It is not enough if you want to get to small details. But the number is too big if you try to convert this DataFrame into a three-dimensional NumPy array, as in this case, we will get a huge 5942479³ = 2.09*10²⁰ array. It will use an enormous amount of RAM for the storage of really sparse data. The obvious thing to do is to use a NumPy sparse array. But as a matter of fact, a sparse array works great for 2D but fails with 3D data. Matrix manipulation functions are not fully compatible with sparse 3D matrices. We have to stick to working with a DataFrame instead of a NumPy array due to memory requirements.</p><h4>Eliminating Out-of-Scope Points</h4><p>We need to find a method to eliminate those points that are not power lines. Power lines are placed high above the ground for safety reasons and to ensure their optimal performance. But for the rugged terrain, we have to take into account that some ground points can be higher than power lines in different parts of the image due to the ground incline. To avoid this let’s divide our point cloud to small vertical parts.</p><pre>%%time</pre><pre>def frange(start, stop, step):</pre><pre>  i = start</pre><pre>  while i &lt; stop:</pre><pre>    yield i</pre><pre>    i += step</pre><pre>#ground points grid filter</pre><pre>n = 100 #grid step</pre><pre>dataset_Z_filtered = dataset[[0]]</pre><pre>zfiltered = (dataset[:, 2].max() — dataset[:, 2].min())/10 #setting height filtered from ground</pre><pre>print(‘zfiltered =’, zfiltered)</pre><pre>xstep = (dataset[:, 0].max() — dataset[:, 0].min())/n</pre><pre>ystep = (dataset[:, 1].max() — dataset[:, 1].min())/n</pre><pre>for x in frange (dataset[:, 0].min(), dataset[:, 0].max(), xstep):</pre><pre>  for y in frange (dataset[:, 1].min(), dataset[:, 1].max(), ystep):</pre><pre>    datasetfiltered = dataset[(dataset[:,0] &gt; x)<br>                             &amp;(dataset[:, 0] &lt; x+xstep)<br>                             &amp;(dataset[:, 1] &gt; y)<br>                             &amp;(dataset[:, 1] &lt; y+ystep)]</pre><pre>    if datasetfiltered.shape[0] &gt; 0:</pre><pre>      datasetfiltered = datasetfiltered[datasetfiltered[:, 2]<br>                        &gt;(datasetfiltered[:, 2].min()+ zfiltered)]</pre><pre>      if datasetfiltered.shape[0] &gt; 0:</pre><pre>        dataset_Z_filtered = np.concatenate((dataset_Z_filtered,<br>                                             datasetfiltered))</pre><pre>print(‘dataset_Z_filtered shape’, dataset_Z_filtered.shape)</pre><p>With the help of this simple approach, we can greatly reduce the number of points in the cloud in no time even using moderate computing power. In our case, it was the reduction of the number of points by an order of magnitude in 3 minutes — not bad for a few lines of code, given that we made no real efforts for any optimization.</p><pre>dataset_Z_filtered shape (169862, 3)</pre><pre>CPU times: user 3min 16s, sys: 7.14 ms, total: 3min 16s</pre><pre>Wall time: 3min 16s</pre><p>Now we’ll be using a much smaller filtered dataset.</p><h4>Exploring Our Data</h4><p>Let’s explore our data:</p><pre>print(“Examining Point Format: “)</pre><pre>pointformat = inFile.point_format</pre><pre>for spec in inFile.point_format:</pre><pre>print(spec.name)</pre><pre>Examining Point Format:</pre><pre>X</pre><pre>Y</pre><pre>Z</pre><pre>intensity</pre><pre>flag_byte</pre><pre>raw_classification</pre><pre>scan_angle_rank</pre><pre>user_data</pre><pre>pt_src_id</pre><pre>gps_time</pre><p>During my experiments, I try to use the 4D representation of data (X, Y, Z and intensity) but the results do not improve over 3D (X, Y, Z) so let’s stick to the latter subset of data.</p><pre>print(‘Z range =’, dataset[:, 2].max() — dataset[:, 2].min())</pre><pre>print(‘Z max =’, dataset[:, 2].max(), ‘Z min =’, dataset[:, 2].min())</pre><pre>print(‘Y range =’, dataset[:, 1].max() — dataset[:, 1].min())</pre><pre>print(‘Y max =’, dataset[:, 1].max(), ‘Y min =’, dataset[:, 1].min())</pre><pre>print(‘X range =’, dataset[:, 0].max() — dataset[:, 0].min())</pre><pre>print(‘X max =’, dataset[:, 0].max(), ‘X min =’, dataset[:, 0].min())</pre><pre>Z range = 149.81</pre><pre>Z max = 181.78999908447264 Z min = 31.979999084472652</pre><pre>Y range = 622.9700000002049</pre><pre>Y max = 2576396.509974365 Y min = 2575773.539974365</pre><pre>X range = 556.4400000000605</pre><pre>X max = 711882.7199987792 X min = 711326.2799987792</pre><h4>Data Normalization</h4><p>As you can see, the values are in different ranges. For better results, we should normalize the dataset.</p><pre>dataset = preprocessing.normalize(dataset)</pre><h4>Clustering the Points That Are Geometrically Close</h4><p>Now we are ready to process our data. Our power lines are actually spatial clusters of points so it is natural to try a clustering algorithm. After a short investigation, I found that DBSCAN provided by the Sklearn library works best out-of-the-box.</p><pre>clustering = DBSCAN(eps=2, min_samples=5, leaf_size=30).fit(dataset)</pre><p>Now let’s visualize our results.</p><pre>core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)</pre><pre>core_samples_mask[clustering.core_sample_indices_] = True</pre><pre>labels = clustering.labels_</pre><pre># Number of clusters in labels, ignoring noise if present.</pre><pre>n_clusters_ = len(set(labels)) — (1 if -1 in labels else 0)</pre><pre>n_noise_ = list(labels).count(-1)</pre><pre>print(‘Estimated number of clusters: %d’ % n_clusters_)</pre><pre>print(‘Estimated number of noise points: %d’ % n_noise_)</pre><pre>Estimated number of clusters: 501</pre><pre>Estimated number of noise points: 1065</pre><h3>Visualization</h3><p>Most of our points were grouped into clusters. Let’s see what it looks like in practice:</p><pre># Black removed and is used for noise instead.</pre><pre>fig = plt.figure(figsize=[100, 50])</pre><pre>ax = fig.add_subplot(111, projection=’3d’)</pre><pre>unique_labels = set(labels)</pre><pre>colors = [plt.cm.Spectral(each)</pre><pre>  for each in np.linspace(0, 1, len(unique_labels))]</pre><pre>for k, col in zip(unique_labels, colors):</pre><pre>  if k == -1:</pre><pre>    # Black used for noise.</pre><pre>    col = [0, 0, 0, 1]</pre><pre>  class_member_mask = (labels == k)</pre><pre>  xyz = dataset[class_member_mask &amp; core_samples_mask]</pre><pre>  ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], c=col, marker=”.”)</pre><pre>plt.title(‘Estimated number of cluster: %d’ % n_clusters_)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gWIhJiQkR2d7W8tr" /></figure><p>It is clear now that simple geometrical consideration and a pretty standard clustering method help us to simplify the point categorization using moderate computing resources.</p><p>Each cluster of points can be categorized separately if needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R1r_OujHGj-1rvyP" /></figure><h3>Results</h3><p>Our experiment showed that a combination of geometrical consideration and standard Python libraries can result in a significant reduction of efforts needed to categorize raw point cloud data for further usage.</p><h3>Acknowledgments</h3><p>I want to thank my colleagues <a href="https://medium.com/u/8bc8d2a62041">Andy Bosyi</a>, <a href="https://medium.com/u/5b6f8e76e312">Mykola Kozlenko</a>, <a href="https://medium.com/u/29c9ae323b06">Volodymyr Sendetskyi</a> for their discussions, cooperation, and helpful tips as well as the entire <a href="https://medium.com/u/bad3e22805b3">MindCraft.ai</a> team for their constant support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3855fdc08f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/point-cloud-data-simple-approach-f3855fdc08f5">Point Cloud Data: Simple Approach</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>