<?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 Mehmed Kadric on Medium]]></title>
        <description><![CDATA[Stories by Mehmed Kadric on Medium]]></description>
        <link>https://medium.com/@mkadric?source=rss-3c6913b887cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BNGVJOhPShEGvCA--KfCSg.jpeg</url>
            <title>Stories by Mehmed Kadric on Medium</title>
            <link>https://medium.com/@mkadric?source=rss-3c6913b887cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:21:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mkadric/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[Anomaly Detection Learning Platform]]></title>
            <link>https://mkadric.medium.com/anomaly-detection-learning-platform-b3749f88b21a?source=rss-3c6913b887cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3749f88b21a</guid>
            <category><![CDATA[anomaly-detection-tool]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[learning-platform]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <dc:creator><![CDATA[Mehmed Kadric]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 14:00:38 GMT</pubDate>
            <atom:updated>2023-08-18T14:02:54.674Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>Anomaly detection algorithms are highly potent tools used to identify abnormal behaviors. Understanding their functioning is essential for those delving into data science.</p><p>For instance, in creating an educational anomaly detection demo, key steps include defining the use case, generating simulated data, and coding in Python for execution and visualization.</p><p>In this blog post we will go through the some basics of Machine Learning based Anomaly Detection algorithms. The idea is to generate Bookstore transaction data, analyze it and find potential anomalies.</p><p>Code related to this post is available <a href="https://github.com/mehmedkadric/anomaly-detection-platform/blob/main/Anomaly_Detection_Book_Store.ipynb">here</a>. Based on this concept, <a href="https://github.com/mehmedkadric/anomaly-detection-platform">Anomaly Detection Learning Platform</a> has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDKec6iFJeN1rox6jFXfQA.png" /><figcaption>Anomaly Detection Learning Platform — Showcase: Transaction is looking good!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkCE_y9JQA87JWnYhhnWOA.png" /><figcaption>Anomaly Detection Learning Platform — Showcase: It looks like book price and number of pages are anomaluos!</figcaption></figure><h3>Generate and Analyze Fake Dataset</h3><p>Firstly, let’s define some patterns. For example, if a book genre is romance it is expected for the price of a book to be lower compared to books with mystery genre. That means, we can create the following patterns:</p><pre>genre_price_patterns = {<br>    &#39;fiction&#39;: (10, 30),<br>    &#39;mystery&#39;: (15, 40),<br>    &#39;romance&#39;: (5, 50),<br>    &#39;non-fiction&#39;: (20, 60)<br>}</pre><p>Another example is that every store has it’s own peek hours. That means we can create a data following normal distribution around the peek hours by providing mean and std values like in the code below.</p><pre>time_mean = 12<br>time_std = 3<br>time_data = np.random.normal(loc=time_mean, scale=time_std, size=num_data_points)<br>time_data = np.clip(time_data, 0, 24)</pre><p>Combining all theese rules, we can create a fake data. Example of generated bookstore transaction record is shown below.</p><pre>{&#39;time&#39;: &#39;13:00-14:00&#39;, &#39;genre&#39;: &#39;romance&#39;, &#39;price&#39;: 32, &#39;pages&#39;: 256}<br>{&#39;time&#39;: &#39;14:00-15:00&#39;, &#39;genre&#39;: &#39;mystery&#39;, &#39;price&#39;: 28, &#39;pages&#39;: 324}<br>{&#39;time&#39;: &#39;14:00-15:00&#39;, &#39;genre&#39;: &#39;fiction&#39;, &#39;price&#39;: 17, &#39;pages&#39;: 367}</pre><p>The following plots are showing the histograms of the distributions for time data, price data, and pages data, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMPOnWTWJ9I4D6LkPDWIgw.png" /></figure><h3>Anomaly detection — Isolation Forest, Gaussian Mixture and One Class SVM</h3><p>In the code below, we use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html">Isolation Forest</a> algorithm from the scikit-learn library to perform anomaly detection. Here’s a breakdown of the steps:</p><ol><li>We convert the dataset into a numerical matrix X where each row represents a data point with numerical features (price and pages).</li><li>We create an instance of the IsolationForest model, adjusting the <em>contamination</em> parameter based on your desired threshold for what is considered an anomaly. This parameter determines the expected proportion of anomalies in the data.</li><li>We fit the Isolation Forest model to the dataset by calling the fit() method.</li><li>We use the decision_function() method to obtain anomaly scores for each data point. The anomaly score represents the model&#39;s confidence in classifying a point as an anomaly.</li><li>We use the predict() method to obtain the binary predictions (-1 for anomalies and 1 for normal points).</li><li>Finally, we print the original data, anomaly scores, and predictions to analyze the results.</li></ol><pre>from sklearn.ensemble import IsolationForest<br>from sklearn.preprocessing import OneHotEncoder, LabelEncoder<br><br># One-hot encode the &#39;time&#39; feature<br>time_encoder = OneHotEncoder(sparse=False, handle_unknown=&#39;ignore&#39;)<br>time_encoded = time_encoder.fit_transform([[d[&#39;time&#39;]] for d in fake_data])<br><br># Label encode the &#39;genre&#39; feature<br>genre_encoder = LabelEncoder()<br>genre_encoded = genre_encoder.fit_transform([d[&#39;genre&#39;] for d in fake_data])<br><br># Concatenate &#39;price&#39;, &#39;pages&#39;, one-hot encoded &#39;time&#39;, and label encoded &#39;genre&#39; into X<br>X = [[d[&#39;price&#39;], d[&#39;pages&#39;]] + list(time_encoded[i]) + [genre_encoded[i]] for i, d in enumerate(fake_data)]<br>X = np.array(X)<br># Train the Isolation Forest model<br><br># Parameter &#39;contamination&#39;: ‘auto’ or float, default=’auto’<br># The amount of contamination of the data set,<br># i.e. the proportion of outliers in the data set.<br># Used when fitting to define the threshold on the scores of the samples.<br><br>isolationforest_model = IsolationForest(contamination=0.1)<br># isolationforest_model = IsolationForest()  # contamination: auto<br>isolationforest_model.fit(X)<br><br># Predict the anomalies<br>anomaly_scores = isolationforest_model.decision_function(X)<br>isolationforest_predictions = isolationforest_model.predict(X)<br><br># Print the anomaly scores and predictions<br>isolationforest_anomalies = []<br>for i in range(len(fake_data)):<br>    if isolationforest_predictions[i] == -1:  # Anomalies are indicated by a prediction value of -1<br>      print(fake_data[i])<br>      isolationforest_anomalies.append(fake_data[i])</pre><p>By running the code above, you’ll get the anomaly scores and predictions for each data point in your dataset. Anomalies are indicated by a prediction value of -1, as shown in the image below. You can adjust the threshold for anomaly detection by tuning the <em>contamination</em> parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJZfTgYQg43kIKxbi0rTtA.png" /><figcaption>IsolationForest — Predictions and Anomaly Scores</figcaption></figure><p>The similar is done with other two anomaly detection algorithms (Gaussian Mixture and One Class SVM). Results are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*lZUpc5y4JpviWzq_LP1ylw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*RiTNPkbS4BBIlxb8Y6vHMA.png" /><figcaption>Left: Gaussian Mixture | Right: One Class SVM</figcaption></figure><h3>Comparison</h3><p>When it comes to anomaly detection, different algorithms have their own strengths and weaknesses.</p><p><strong>Isolation Forest</strong>: Good for efficient anomaly detection in large datasets, particularly suitable for high-dimensional data; however, might struggle with complex interconnected anomalies.</p><p><strong>Gaussian Mixture</strong>: Good for capturing complex data distributions with multiple modes using probabilistic clustering; but sensitive to initialization and varying cluster shapes.</p><p><strong>One Class SVM: </strong>Good for rare anomaly detection in binary classification, can handle nonlinear boundaries using kernels; however, sensitive to kernel choice and data distribution differences.</p><h3>Conclusion</h3><p>Overall, all three algorithms were able to identify anomalies in the dataset, but the specific anomalies detected may differ due to the variations in the algorithms’ underlying assumptions and techniques. For testing purposes, 210 records were generated and here are the results:</p><ul><li>Isolation Forest flagged 21/210 data points as anomalous.</li><li>Gaussian Mixture identified 15 anomalies. 14 overlap with the anomalies detected by Isolation Forest.</li><li>One-Class SVM detected 22 anomalies, with 12 of them overlapping with the anomalies identified by IsolationForest model.</li></ul><p>It’s worth noting that the choice of algorithm and its parameter settings should depend on the specific characteristics and requirements of the dataset and the anomaly detection task at hand. Experimenting with different algorithms and tuning their parameters can help fine-tune the anomaly detection process for optimal results.</p><p>Please note that the effectiveness of the anomaly detection algorithms heavily relies on the quality and representativeness of the dataset used for training and evaluation. Additionally, domain knowledge and further analysis are crucial in interpreting and validating the detected anomalies.</p><h3>GitHub</h3><p><a href="https://github.com/mehmedkadric/anomaly-detection-platform">https://github.com/mehmedkadric/anomaly-detection-platform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3749f88b21a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large Dataset Filtering with Python]]></title>
            <link>https://mkadric.medium.com/large-dataset-filtering-with-python-6d039d17a157?source=rss-3c6913b887cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d039d17a157</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-filtering]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mehmed Kadric]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 12:57:16 GMT</pubDate>
            <atom:updated>2023-08-18T12:57:16.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the world of data science, the ability to efficiently process and analyze large datasets is a crucial skill. However, working with massive CSV or Excel files can quickly become a daunting task, especially when the task at hand involves filtering specific data points. In this blog post, I’ll share a real-world problem I encountered and the <a href="https://github.com/mehmedkadric/data-filter-app">solution</a> I devised using Python.</p><h3>GitHub</h3><p><a href="https://github.com/mehmedkadric/data-filter-app">https://github.com/mehmedkadric/data-filter-app</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEVT26ObhLsHTCVgmoRdRQ.png" /></figure><h3><em>The Problem</em></h3><p>Consider a scenario where managing an extensive CSV file laden with city records becomes imperative. The task is to distill specific cities meeting certain criteria, such as identifying cities with “New York” in the “City” field or matching the value “Chicago.” Common in data analysis, this challenge grows complex when datasets surge to the scale of 20 GB or even 200 GB. How do we efficiently uncover requisite data from such colossal datasets?</p><h3><em>The Solution</em></h3><p>Addressing this challenge demanded ingenuity, culminating in a Python script melding the prowess of the <strong>pandas</strong> library for data manipulation and <strong>tkinter</strong> for a user-friendly graphical interface. The script is designed to ingest CSV or Excel files, enabling users to specify filtering conditions and subsequently orchestrating swift data filtration. Furthermore, it seamlessly generates output files in both CSV and XLSX formats, simplifying subsequent analysis.</p><h3><em>Showcasing Data Science Expertise:</em></h3><ol><li><strong>Optimized Data Processing</strong>: Harnessing pandas’ chunking mechanism, the script intelligently processes data in manageable chunks. This strategem curtails memory usage and augments overall performance.</li><li><strong>Advanced Data Querying</strong>: Exploiting pandas’ DataFrame querying capabilities, a nuanced logic was implemented for efficient row filtration based on user-defined conditions. This ensures rapid data extraction while upholding accuracy.</li><li><strong>GUI Development</strong>: Leveraging tkinter, an intuitive graphical interface emerged, simplifying the filtration process for non-technical users. This underscores adeptness in crafting interfaces that transcend technical barriers.</li><li><strong>Tailored Configurability</strong>: Facilitating user-specified filter conditions and output formats enhances the script’s adaptability. This hallmark showcases the aptitude to tailor solutions to unique exigencies.</li></ol><h3>In Conclusion</h3><p>Executing the Python script we’ve detailed here unveils the elegance of data manipulation, performance enhancement, and user-centric design. This narrative serves to inspire and empower fellow data scientists on their journeys, highlighting that with the right tools, even the most complex challenges can be gradually unraveled, revealing their underlying insights.</p><h3>Key Benefits of the Solution</h3><p>Compared to alternatives like Java, C++, or web applications, our Python script offers notable advantages. Its efficiency, simplicity, and resource optimization arise from Python’s versatile syntax and the prowess of pandas for large dataset handling.</p><p>The script’s local execution sidesteps web-based latency issues and ensures a seamless experience. Moreover, its portability across platforms and customizable filtering conditions make it a cost-effective and adaptable solution.</p><p>By solving the challenge of efficient large dataset filtering, this approach underscores the modern data scientist’s need for efficiency, accessibility, and adaptability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d039d17a157" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-centric AI / Big data vs. Good data]]></title>
            <link>https://mkadric.medium.com/data-centric-ai-big-data-vs-good-data-ebeaac21ffa8?source=rss-3c6913b887cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebeaac21ffa8</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-centric-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mehmed Kadric]]></dc:creator>
            <pubDate>Tue, 16 May 2023 10:25:00 GMT</pubDate>
            <atom:updated>2023-05-16T10:36:42.659Z</atom:updated>
            <content:encoded><![CDATA[<p>We can agree that AI is not a one-size-fits-all solution. However, for many companies, AI can provide significant benefits and help drive growth and success. Some potential benefits include the following:</p><ul><li>Improved efficiency: AI can automate tasks and processes, saving time and resources for other activities.</li><li>Increased accuracy: AI can make more accurate predictions and decisions than humans, reducing the risk of errors.</li><li>Enhanced customer experience: AI can personalize customer interactions, providing a more tailored and seamless experience.</li><li>Cost savings: AI can help businesses reduce costs by automating tasks, improving efficiency, and reducing the need for human labor.</li><li>Competitive advantage: Companies that use AI can gain a competitive advantage over those that don’t by being able to analyze and act on data faster and more effectively.</li></ul><p>The last decade has brought significant growth in the field of Data Science in general. However, the total value of AI is still locked in many sectors, such as health care, manufacturing, and government technology. In a study published by <a href="https://www.accenture.com/_acnmedia/Thought-Leadership-Assets/PDF-2/Accenture-Built-to-Scale-PDF-Report.pdf#zoom=50">Accenture</a>, 80% of all Proof of Concepts (PoCs) do not make it into production. What exactly is going wrong, and why is AI not as successful in the real world as it is in academic studies?</p><h3>Model-centric vs. Data-centric approach</h3><p>A strong model-centric AI (traditionally presented in academia) considers data only as a static parameter. If a model’s performance is not as expected, AI/ML engineers will try to tune the model’s hyperparameters or even change the model while data stays untouched.</p><p>Subject Matter Experts do not play a vital role in the whole process of developing AI-based systems in a model-centric approach. Instead, AI/ML engineers usually make business-related decisions during that process.</p><p>As per Andrew Ng, an AI system is a combination of code and data. While a significant amount of time and resources have been dedicated to developing code and algorithms, it is now necessary to prioritize improving data quality and relevance to achieve desired outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*xUfoVg5DXzpiefsyY275-g.png" /><figcaption>The Concept of Data Centric AI</figcaption></figure><p>By shifting the focus to data, we are basically moving from model-centric to data-centric AI.</p><p>In a data-centric approach, the role of Subject Matter Experts is significant, and AI systems are much closer to every business.</p><p>Adopting a data-centric approach in the real world or during work on a practical project is more fruitful. That means the model stays fixed and focuses on feeding the model with good or high-quality data. A decent algorithm with good data may even outperform a great algorithm with not-so-good data.</p><p>Data should not be the only priority in the development process. It is also important to consider the structure and functionality of the model and code used. The choice of model can significantly impact the accuracy, as demonstrated in the analysis of the <a href="https://www.atlantbh.com/titanic-disaster-through-data-analysis/">Titanic disaster,</a> where the prediction accuracy varied from 78% to 94%, depending on the algorithm.</p><h3>Big Data vs. Good Data: What’s More Important for AI?</h3><p>Good Data and Big Data are two terms often used in the field of Data Science and AI. Good data refers to data that is accurate, relevant, and well-organized. Big data, on the other hand, refers to large datasets that are too large and complex to be processed and analyzed using traditional data processing tools and techniques.</p><p>In order for AI algorithms to make accurate predictions and decisions, they need to be trained on large amounts of data. However, simply having a lot of data is not enough. The data must also be high-quality and well-organized for the AI model to learn effectively.</p><p>In many cases, companies only have access to small datasets, which can lead to poor results if the focus is solely on the model. Andrew Ng emphasizes the benefits of a data-centric approach to machine learning and suggests that there should be a shift towards this approach within the community. He uses the example of a steel defect detection problem, in which the data-centric approach improved the model’s accuracy by 16% compared to a model-centric approach [Source: <a href="https://neptune.ai/blog/data-centric-vs-model-centric-machine-learning#:~:text=It&#39;s%20sometimes%20referred%20to%20as,permanent%20asset%2C%20whereas%20applications%20change.">neptune.ai</a>].</p><h3>Data Quality Issues</h3><p>Many famous datasets have data quality issues. For instance, The COCO and ImageNet datasets are widely used in the field of computer vision for tasks such as object detection, image classification, and image segmentation. While these datasets are widely used and generally considered high quality, some issues have been discovered with them that may impact their usefulness for specific tasks. Some of the problems detected in the COCO dataset include mislabelled objects (first image) and labeling inconsistencies (second image) [Source: <a href="https://www.neuralception.com/mislabelled-traffic">neuralception.com</a>].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CaNy9UvVutVHdiKz9voRlg.png" /><figcaption>Mislabelled traffic lights</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*_KNtklQp__snqop4CbPkYw.png" /><figcaption>Labelling inconsistency</figcaption></figure><h3>Ensuring Data Quality in Machine Learning Development</h3><p>While the specific methods for improving data quality may vary depending on a specific problem, some general steps can be applied in many situations:</p><ol><li>Verify data sources.</li></ol><ul><li>Ensure that data sources are reliable and accurate.</li><li>Make sure your model gets enough data to be able to generalize.</li></ul><p>2. Validate and clean data.</p><ul><li>Check labeling inconsistencies — Perform validation checks and look-ups on labeled data if applicable.</li><li>Check labeling inconsistencies — Check labels distribution and manually check entries with low-frequency labels.</li><li>Check labeling inconsistencies — Try to make a tool that will give you suspicious labels so you can check them manually.</li></ul><p>3. Standardize data to a common format or schema.</p><p>4. Involve Subject Matter Experts.</p><p>5. Document agreements after discussing inconsistencies with labelers.</p><p>6. Analyze data and perform feature engineering.</p><p>7. Train a model with labeled data and apply the model to training data. Check the diffs.</p><p>8. Perform error analysis.</p><p>The development of machine learning-based systems is a highly iterative process. Keeping track of your notes, findings, and conventions in a documentation system can help maintain data quality. By following mentioned steps and being vigilant about potential issues, you can help ensure that your data is of high quality and ready for use in your machine-learning projects.</p><h3>Wrapping Up</h3><p>It is important to consider the quality and quantity of data and the structure and functionality of the model and code used. By prioritizing data quality and involving subject matter experts, companies can improve the accuracy and effectiveness of their AI systems, drive growth and success, and gain a competitive advantage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebeaac21ffa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random String Detection]]></title>
            <link>https://medium.com/atlantbh/random-string-detection-1ed48de05a0e?source=rss-3c6913b887cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ed48de05a0e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gibberish]]></category>
            <category><![CDATA[keyboard-smash]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[random-string]]></category>
            <dc:creator><![CDATA[Mehmed Kadric]]></dc:creator>
            <pubDate>Tue, 09 May 2023 14:03:47 GMT</pubDate>
            <atom:updated>2024-06-23T10:58:49.204Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://pypi.org/project/random-string-detector/">https://pypi.org/project/random-string-detector/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8krMy25yEcQfOLXirrjrZQ.jpeg" /></figure><p>Data analysis often presents us with the challenge of dealing with noisy inputs. This is particularly evident when working with large datasets of user inputs. Detecting and filtering out random string inputs can prove invaluable in various scenarios, such as data validation, quality control or the development of machine learning (ML) based natural language processing (NLP) systems (check for data quality improvement steps in <a href="https://www.atlantbh.com/data-centric-ai-big-data-vs-good-data/">this blog post</a>).</p><figure><img alt="Image 1 — Random Strings" src="https://cdn-images-1.medium.com/max/1024/1*3aXECpbyV0mqEvQ1KrC_4A.png" /><figcaption><em>Image 1 — Random Strings</em></figcaption></figure><h3>What should/can be considered a ‘random string’?</h3><p>The term “random string” may seem straightforward at first glance, but its interpretation can be subjective and context-dependent. What one person perceives as a random string, another may see as a meaningful pattern or representation. This relativity is particularly evident when considering visual or linguistic aspects.</p><p>Let’s delve into a few examples to highlight the importance of relativity when defining random strings. Take, for instance, the string ‘\__o__/’. At first glance, it might appear random, but one could argue that it resembles a stick figure of a man with raised hands. In this case, the interpretation of randomness becomes subjective, as different individuals may perceive different patterns or associations.</p><p>Similarly, let’s consider the word “Szczesny.” In the English language, it may appear as a random combination of letters, devoid of any meaning. However, in Polish, it happens to be the surname of a famous goalkeeper (Image 2). This example demonstrates how the interpretation of randomness can be influenced by language and cultural context. What may seem random in one language could hold significance or meaning in another.</p><figure><img alt="Image 2 [Source: Yahoo/Reuters] — Wojciech Szczesny, a Polish professional footballer" src="https://cdn-images-1.medium.com/max/1024/1*Aubsp9vf8IMyTYxo_bphgQ.jpeg" /><figcaption><em>Image 2 [Source: </em><a href="https://ca.sports.yahoo.com/news/ll-probably-banned-szczesny-reveals-235708569.html"><em>Yahoo/Reuters</em></a><em>] — Wojciech Szczesny, a Polish professional footballer</em></figcaption></figure><p>It’s crucial to acknowledge that randomness is not an inherent property of a string itself but rather a perception based on patterns or associations that individuals may perceive. In the context of data analysis and ML, understanding this relativity is vital when developing algorithms or models that aim to detect and filter out random strings.</p><p>When designing systems to identify random strings, it becomes essential to consider the specific domain, context, and purpose of the analysis. What may be considered random noise in one scenario could be a valuable signal in another. For instance, when analyzing social media data, a sequence of random characters might indicate spam or bot-generated content. On the other hand, in cryptography, random strings play a crucial role in generating secure encryption keys.</p><p>Moreover, the concept of randomness itself can vary depending on the intended application. Some algorithms generate strings that may appear random to human observers but possess specific statistical properties that make them suitable for cryptographic purposes. In contrast, other applications require strings that exhibit specific patterns or structures to serve their intended function.</p><h3>How to detect a random string of characters in a specific locale?</h3><p>If the goal is to detect random strings which consist of a specific set of characters (e.g., English alphabet characters), one possible way of detecting random strings is using bigrams.</p><p>To be able to do that, you need to create a reference dictionary of bigrams for the considered locale. For the English language, we can use bigrams and their frequencies from <a href="http://norvig.com/mayzner.html">Peter Norvig’s analysis</a>. For example, in English language text, the bigram “th” is very common, while the bigram “zx” is not. Using the available list of bigrams and their frequencies, it is possible to normalize it (e.g., min-max normalization) and create a reference dictionary. An important note here is that you can easily create your own list of bigrams (extracted from word corpus) for any locale if you are able to find open-source books, newspapers or magazines.</p><p>Reference dictionary is a dictionary of all 26² = 676 combinations of English bigrams with associated frequency numbers (from 0 to 100) where higher values represent more frequent bigrams (like “th”) and lower values represent less frequent bigrams (like “zx”). Users are able to adjust the threshold value (default value is 0.1) in order to define a boundary between less common and common bigrams. For example, if the threshold is 0, all bigrams will be considered as common bigrams. Otherwise, if the threshold is 100, all bigrams will be considered as less common bigrams. You can find a reference dictionary of bigrams <a href="https://github.com/mehmedkadric/random-string-detector/blob/main/random_string_detector/random_string_detector.py">here</a>.</p><p>To consider whether a word is a random string or not, here is a list of steps that are used to help detect random strings:</p><ol><li><strong>Length and Character Validation</strong>: The first checkpoint of the algorithm verifies that the word is longer than three characters (words up to three characters may be regular abbreviations) and consists solely of English alphabetic characters. This ensures that we are working with meaningful words rather than arbitrary combinations of symbols</li><li><strong>Repeating Characters</strong>: If the entire word is made up of the same character, such as “hhhhhhh”, it is immediately labeled as random. This is because the presence of repeating characters indicates a lack of complexity and structure, suggesting a random generation</li><li><strong>Lowercasing the Word</strong>: To eliminate the case sensitivity, the algorithm converts the word to lowercase. This prevents the distinction between uppercase and lowercase characters from affecting the detection process</li><li><strong>Bigrams Analysis</strong>: A bigram refers to a sequence of two consecutive characters in a word. The algorithm generates a list of all possible bigrams within the word. For example, the word “random” would produce the following bigrams: <em>ra, an, nd, do, om</em></li><li><strong>Common and Uncommon Bigrams</strong>: Each bigram is compared against a reference dictionary of common English bigrams. If a bigram has a frequency above a given threshold, it is considered common; otherwise, it is classified as uncommon. The choice of threshold depends on the desired sensitivity of the algorithm</li><li><strong>Counting Common and Uncommon Bigrams</strong>: The algorithm calculates the number of common and uncommon bigrams in the word. If the count of common bigrams exceeds that of uncommon bigrams, the word is classified as non-random. Conversely, if the count of uncommon bigrams surpasses that of common bigrams, the word is deemed random</li></ol><p>Here are Python and Java codes for the proposed algorithm:</p><p><strong><em>Edit</em></strong>: Check for the updated version of random-string-detector at <a href="https://github.com/mehmedkadric/random-string-detector">https://github.com/mehmedkadric/random-string-detector</a>.</p><p>Python:</p><pre>def is_random_string(word, threshold=0.1):<br>    # Allow only words longer than 3 characters which contains only English alphabetic characters<br>    if len(word) &lt; 4 or not word.isalpha():<br>        return False<br><br>    # Repeating characters<br>    if len(set(word)) == 1:<br>        return True<br><br>    # Turn word into lowercase<br>    word = word.lower()<br><br>    # Get list of bigrams from the word<br>    bigrams = [word[i:i + 2] for i in range(len(word) - 1)]<br><br>    # Get number of common and uncommon bigrams<br>    num_common_bigrams = sum(1 for bigram in bigrams if en_bigrams_dict.get(bigram, 0) &gt; threshold)<br>    num_uncommon_bigrams = len(bigrams) - num_common_bigrams<br><br>    # Higher number wins<br>    if num_common_bigrams &gt; num_uncommon_bigrams:<br>        return False<br>    else:<br>        return True</pre><p>Java:</p><pre>package checker;<br><br><br>import java.util.HashMap;<br>import java.util.Map;<br><br><br>public class RandomStringChecker {<br>   private static final double DEFAULT_THRESHOLD = 0.1;<br>   private static final Map&lt;String, Double&gt; enBigramsDict = new HashMap&lt;&gt;();<br><br><br>   static {<br>       // Populate the dictionary of English bigrams here<br>       enBigramsDict.put(&quot;ab&quot;, 6.461565670356169);<br>       enBigramsDict.put(&quot;bc&quot;, 0.0531330714265234);<br>       enBigramsDict.put(&quot;cd&quot;, 0.06273467822837461);<br>       // ...<br>   }<br><br><br>   public static boolean isRandomString(String word) {<br>       return isRandomString(word, DEFAULT_THRESHOLD);<br>   }<br><br><br>   public static boolean isRandomString(String word, double threshold) {<br>       // Allow only words longer than 3 characters which contain only English alphabetic characters<br>       if (word.length() &lt; 4 || !word.matches(&quot;[a-zA-Z]+&quot;)) {<br>           return false;<br>       }<br><br><br>       // Repeating characters<br>       if (word.chars().distinct().count() == 1) {<br>           return true;<br>       }<br><br><br>       // Turn word into lowercase<br>       word = word.toLowerCase();<br><br><br>       // Get list of bigrams from the word<br>       String[] bigrams = new String[word.length() - 1];<br>       for (int i = 0; i &lt; word.length() - 1; i++) {<br>           bigrams[i] = word.substring(i, i + 2);<br>       }<br><br><br>       // Get number of common and uncommon bigrams<br>       int numCommonBigrams = 0;<br>       for (String bigram : bigrams) {<br>           if (enBigramsDict.containsKey(bigram) &amp;&amp; enBigramsDict.get(bigram) &gt; threshold) {<br>               numCommonBigrams++;<br>           }<br>       }<br>       int numUncommonBigrams = bigrams.length - numCommonBigrams;<br><br><br>       // Higher number wins<br>       return numCommonBigrams &lt;= numUncommonBigrams;<br>   }<br>}</pre><p>This algorithm has been released as a <a href="https://pypi.org/project/random-string-detector/">Python package</a> and can easily be installed using the command:</p><pre>pip install random-string-detector</pre><h3>Examples</h3><p>Python method calls:</p><pre>from random_string_detector.random_string_detector import is_random_string<br><br>print(is_random_string(&#39;abcd&#39;)) # True<br>print(is_random_string(&#39;Thgrbh&#39;)) # False<br>print(is_random_string(&#39;Thgrbh&#39;, 5)) # True - threshold adjusted</pre><p>Java method call:</p><pre>public static void main(String[] args) {<br>   System.out.println(isRandomString(&quot;abcd&quot;)); // true<br>}</pre><h3>Conclusion</h3><p>The interpretation of randomness depends on the specific domain, context, and purpose of the analysis. What may be considered random noise in one scenario could be valuable information or a critical signal in another. It is essential to align the definition of random strings with the objectives and requirements of the particular application to ensure the reliability and quality of results.</p><p>While the proposed algorithm is not foolproof and cannot definitively determine randomness, it serves as a useful tool for various applications that require distinguishing between random and non-random strings.</p><p>A potential algorithm improvement would be to have the bigram dictionary in a separate file that we could load into memory.</p><h3>Appendix</h3><p>PyPI: <a href="https://pypi.org/project/random-string-detector/">https://pypi.org/project/random-string-detector/</a></p><p>GitHub: <a href="https://github.com/mehmedkadric/random-string-detector">https://github.com/mehmedkadric/random-string-detector</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ed48de05a0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/atlantbh/random-string-detection-1ed48de05a0e">Random String Detection</a> was originally published in <a href="https://medium.com/atlantbh">Atlantbh Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using YOLO for Object Detection: How to Extract People Images]]></title>
            <link>https://mkadric.medium.com/how-to-use-yolo-object-detection-model-1604cf9bbaed?source=rss-3c6913b887cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1604cf9bbaed</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mehmed Kadric]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 09:06:30 GMT</pubDate>
            <atom:updated>2023-01-16T09:41:39.240Z</atom:updated>
            <content:encoded><![CDATA[<p>YOLO (You Only Look Once) is a popular open source neural network model for object detection. In this post, we will explain how to use YOLO to extract images where a bunch of people are in (or at least one person is in).</p><p>Firstly, we need to install the YOLO library and dependencies. For this, we will use the pip package manager and install the following libraries:</p><pre>pip install numpy<br>pip install opencv-python<br>pip install tensorflow<br>pip install keras</pre><p>Next, we will download the pre-trained YOLO weights and configuration file from the official website. These files can be found at <a href="https://pjreddie.com/darknet/yolo/">https://pjreddie.com/darknet/yolo/</a>.</p><p>Once we have the weights and configuration files, we can use them to perform object detection on our images. Here is an example of how to use YOLO to detect people in an image:</p><pre>import cv2<br>import numpy as np<br><br># Load YOLO model<br>net = cv2.dnn.readNet(&quot;./yolov3.weights&quot;, &quot;./darknet/cfg/yolov3.cfg&quot;)<br><br># Define input image<br>image = cv2.imread(&quot;image.jpg&quot;)<br><br># Get image dimensions<br>(height, width) = image.shape[:2]<br><br># Define the neural network input<br>blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)<br>net.setInput(blob)<br><br># Perform forward propagation<br>output_layer_name = net.getUnconnectedOutLayersNames()<br>output_layers = net.forward(output_layer_name)<br><br># Initialize list of detected people<br>people = []<br><br># Loop over the output layers<br>for output in output_layers:<br>    # Loop over the detections<br>    for detection in output:<br>        # Extract the class ID and confidence of the current detection<br>        scores = detection[5:]<br>        class_id = np.argmax(scores)<br>        confidence = scores[class_id]<br><br>        # Only keep detections with a high confidence<br>        if class_id == 0 and confidence &gt; 0.5:<br>            # Object detected<br>            center_x = int(detection[0] * width)<br>            center_y = int(detection[1] * height)<br>            w = int(detection[2] * width)<br>            h = int(detection[3] * height)<br><br>            # Rectangle coordinates<br>            x = int(center_x - w / 2)<br>            y = int(center_y - h / 2)<br><br>            # Add the detection to the list of people<br>            people.append((x, y, w, h))<br><br># Draw bounding boxes around the people<br>for (x, y, w, h) in people:<br>    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)<br><br># Show the image<br>cv2.imshow(&quot;Image&quot;, image)<br>cv2.waitKey(0)</pre><p>In this example, we first load the YOLO model using the cv2.dnn.readNet method. Then, we define the input image and get its dimensions. Next, we define the neural network input by creating a blob from the image and normalizing its pixel values. Finally, we perform forward propagation and loop over the output layers to extract the detections and extract the bounding box coordinates around the people (our interest is in person detection). We can then draw these bounding boxes around the people on the original image using the cv2.rectangle method.</p><p>After running this code, you should be able to see an image with bounding boxes around any people that were detected. Check the image below!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSZj_laRnUHdHyMSK48szA.png" /><figcaption>YOLO Object Detection | <a href="https://unsplash.com/photos/kY8m5uDIW7Y">Source</a></figcaption></figure><p>If you want to get rid of duplicated rectangles, you can use NMS, for example:</p><pre>cv2.dnn.NMSBoxes(boxes, confidences, score_threshold=0.5, nms_threshold=0.4)</pre><p>Also, it is possible to add a caption for each detection:</p><pre>cv2.putText(image, label, (x, y + 30), font, 2, color, 3)</pre><p>And the output is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGzDUaBcGWuAamNVQW7vjA.png" /><figcaption>YOLO Object Detection (objects with labels) | <a href="https://unsplash.com/photos/kY8m5uDIW7Y">Source</a></figcaption></figure><p>Now you can easily count the number of persons in provided image.</p><p>If you want to learn more about object detection or YOLO, there are plenty of resources available online. Some good places to start include the official YOLO website and the TensorFlow object detection API documentation.</p><p>We encourage you to try out the code sample provided in this article and share your results with us. If you have any questions or feedback, please don’t hesitate to reach out.</p><p>Thank you for reading, and we hope you found this article helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1604cf9bbaed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>