<?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 Maximilian Stäbler on Medium]]></title>
        <description><![CDATA[Stories by Maximilian Stäbler on Medium]]></description>
        <link>https://medium.com/@maximilianstaebler?source=rss-3eec54c995e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5J5phIpivLsbC238yvdHmw.jpeg</url>
            <title>Stories by Maximilian Stäbler on Medium</title>
            <link>https://medium.com/@maximilianstaebler?source=rss-3eec54c995e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:13:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maximilianstaebler/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[Music Genre Prediction by Extracted Audio-Features + Comparison To the Spotify-API]]></title>
            <link>https://pub.towardsai.net/music-genre-prediction-by-extracted-audio-features-and-comparison-to-the-spotify-api-ebf82232e31a?source=rss-3eec54c995e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf82232e31a</guid>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[feature-extraction]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[music-analysis]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <dc:creator><![CDATA[Maximilian Stäbler]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 14:16:12 GMT</pubDate>
            <atom:updated>2021-01-05T02:15:48.812Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/machine-learning">Machine Learning</a></h4><h4>Can we extract features of a piece of music that allow a more precise genre classification than the features provided by Spotify via their API?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vX9D-2xoiLWuNLf5" /><figcaption>Photo by <a href="https://unsplash.com/@sgcreative?utm_source=medium&amp;utm_medium=referral">sgcdesignco</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>No question, for us, it’s super easy to decide whether a piece of music belongs to the genre “<em>classical</em>” or to the genre “<em>punk rock</em>”. But how can you teach a computer to decide between different genres? A computer or an algorithm does not know that the soft piano notes of Mozart belong to the classical genre or that incoming electric guitar riffs are very often used in the punk rock genre. <br>Of course, you can tell an algorithm that all Mozart’s music belongs to the classical genre, but what happens to artists who move between different genres over time and the songs in an album belonging to different genres? Take Machine Gun Kelly (one of my favorites btw.) as an example, and he used to be clearly in the genre of rap. But his latest album (as of late 2020) consists mostly of songs that fit more into the rock genre. <br>Furthermore, although songs were analyzed for this article, the methods used can be transferred to other signal processing tasks without any problems! And since most people like music, I thought this example is the most illustrative.</p><p>So if you are interested in how to use Python to analyze different signals (music tracks), cluster them based on different genres, and end up with a much better classification of songs into 4 different genres than if you use the features provided by Spotify, then this article is for you!</p><h4>Before we start — please don’t skip this section</h4><ul><li>This project includes both signal processing methods and various machine learning techniques such as principal component analysis &amp; support vector machines. Due to the size of the project, not every method used can be explained in detail.</li><li>I am also in no way a specialist in signal processing methods, so the results obtained here should only be considered as a first suggestion and certainly provide room for optimization!</li><li>For privacy and licensing reasons, I can’t provide the raw music data. However, I personally extracted the songs using the great command-line application <strong>youtube-dl</strong> (<a href="https://github.com/ytdl-org/youtube-dl">Github link</a>). An example of a playlist on Youtube I used to extract songs is <a href="https://www.youtube.com/watch?v=NUTGr5t3MoY&amp;list=PLpUmlJahfz1NieOw-QMBaVfxxUA1Fqfst">this one for Punk-Rock songs</a>.<br>However, on the GitHub repository associated with this post, there is a <em>features.csv</em> which contains all the extracted features for all the songs I used. So this file can serve as a basis for your own analyses.</li></ul><p>In order not to overstretch the scope of the project, the following conditions were met:</p><ul><li>Only songs from the four genres,<strong> punk, classic, hardstyle, and house,</strong> were used. A total of <strong>311 songs</strong> were used, with roughly equal distribution among the four genres (detailed distribution below).</li><li>When selecting the genres, I tried to choose very different genres in order to have a certain separation between the songs. An exception here is House and Hardstyle, which overlap in some characteristics. This was also deliberately chosen so that the prediction is not too easy. <br>Since the boundaries between genres like rock &amp; hard rock are becoming more and more blurred, everyone defines these genres a little differently, and each genre could theoretically be divided much more fine-granular. I have chosen quite clear genres. Also important in the definition of the genres was that the same genres are also available on Spotify to be able to draw a comparison later.</li></ul><p>After this is clarified, here is the link to my GitHub page:</p><ul><li><a href="https://github.com/maxistaebler/towardsdatascience/tree/main/music-genre-prediction">GitHub repository</a></li></ul><h4>Plan of attack</h4><ul><li>In the first step, I will describe how and which features I extracted for each of the 311 songs—all with the help of an example.</li><li>The available data will then be presented with a short explorative data analysis, and I will explain the necessity of a dimension reduction.</li><li>After the data has been dimension reduced, we will run a support vector machine and try to classify unseen songs into one of the four genres based on their vocal features.</li><li>Thereafter I will briefly discuss how the Spotify API can be used to extract features for each song available on Spotify. <br>The Spotify features will then also be reduced in dimension and used to train a Support Vector Machine.</li><li>In the last step, both trained models are compared with each other, and it is decided which approach gave a better result.</li></ul><h4>Feature extraction</h4><p>For analyzing these songs and therefore be able to create corresponding features that describe the given sound, we will use different <em>feature extraction</em> tools which are built into librosa. Librosa is a python package for music and audio analysis. It provides the building blocks necessary to create music information retrieval systems.</p><p>Once you have imported a song using the library, you can quickly extract numerous different features that reflect the characteristics of the underlying song. An example of this is the separation of the harmonic and instrumental components of the song, which can be done with a few lines of Python code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b65b54b5cdadf87078c49763dfae6ee/href">https://medium.com/media/3b65b54b5cdadf87078c49763dfae6ee/href</a></iframe><p><strong>But why make this separation?<br></strong>The aim of the harmonic/percussive separation is to decompose the original music signal to the <em>harmonic</em> (i.e., pitched instruments) and the <em>percussive</em> (non pitched instruments, percussion) parts of the signal. Such methods can be applied to audio mixing software or can be adopted as preprocessing on other Music-Information-Retrieval-Methods such as rhythm analysis or chord/tonality recognition. The method is based on the assumption that harmonic components exhibit horizontal lines on the spectrogram while the percussive sounds are evident as vertical lines. By adopting non-linear image filters applied to the spectrogram in order to filter out this component, the proposed method is simple, intuitive and does not make any prior assumption of the genre, style, or instrumentation of the target music.</p><p>A separation into these two parts makes absolute sense with respect to the importance of different instruments for different genres. Genres like classical music often do without a dominant percussion part and focus on harmonic instruments like piano or flute. Hardstyle, on the other hand, is clearly dominated by incoming drum/bass beats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5Uq5ts07K1UFMQJK1yXgg.png" /><figcaption><a href="http://mir.ilsp.gr/harmonic_percussive_separation.html">http://mir.ilsp.gr/harmonic_percussive_separation.html</a></figcaption></figure><p><strong>More extract features:</strong></p><ul><li><strong>RMS values and related features:</strong><br>The RMS (Root-Mean-Square) value is the effective value of the total waveform. It is really the area under the curve. In audio, it is the continuous or music power that the amplifier can deliver. <br>Using RMS values allows for calculations to be completed more easily.<br>Bottom Line: For audio applications, our ears are RMS instruments, not peak reading. So using RMS values makes sense and is normally how amplifiers are rated.</li><li><strong>Spectral Centroid:</strong> It indicates where the ” center of mass” for a sound is located and is calculated as the weighted mean of the frequencies present in the sound. If the frequencies in music are the same throughout, then, spectral centroid would be around a center, and if there are high frequencies at the end of the sound, then the centroid would be towards its end.</li><li><strong>Chroma Frequencies:</strong> Chroma features are an interesting and powerful representation for music audio in which the entire spectrum is projected onto 12 bins representing the 12 distinct semitones (or chroma) of the musical octave. It is a representation of how humans relate colors to notes. In other words, we think of the same notes but from two different octaves to be of the same color. Thus we have 12 possible values at each window. A, A#, B, C, C#, D, D#, E, F, F#, G and G#. Of course, they are not mutually exclusive; hence for a given time frame, one can have more than one note. But to keep things simple, we will only select the most prominent note for a particular window. Let us visualize the chroma vector using a chromagram.</li><li><strong>Spectral bandwidth:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*m33N4cJ5A7zjPE1theS-GA.gif" /><figcaption>Computes the order- p spectral bandwidth</figcaption></figure><p>where <em>S(k)</em> is the spectral magnitude at frequency bin k, <em>f(k)</em> is the frequency at bin k, and fc is the spectral centroid. When p=2, this is like a weighted standard deviation.</p><ul><li><strong>Spectral contrast:</strong><br>Spectral contrast considers the spectral peak, the spectral valley, and their difference in each frequency subband.<br>Automatic music type classification is very helpful for the management of digital music database. Octavebased Spectral Contrast feature is proposed to represent the spectral characteristics of a music clip. It represented the relative spectral distribution instead of the average spectral envelope. Experiments showed that the Octave-based Spectral Contrast feature performed well in music type classification. Another comparison experiment demonstrated that the Octave-based Spectral Contrast feature has better discrimination among different music types than Mel-Frequency Cepstral Coefficients (MFCC), which is often used in previous music type classification system.<br>Each frame of a spectrogram S is divided into sub-bands. For each sub-band, the energy contrast is estimated by comparing the mean energy in the top quantile (peak energy) to that of the bottom quantile (valley energy). High contrast values generally correspond to clear, narrow-band signals, while low contrast values correspond to broad-band noise.</li><li><strong>Polynomial features:</strong><br>Get coefficients of fitting an nth-order polynomial to the columns of a spectrogram.</li><li><strong>Tonal centroid features (tonnetz):</strong><br>In musical tuning and harmony, the Tonnetz (German: tone-network) is a conceptual lattice diagram representing tonal space first described by Leonhard Euler in 1739. Various visual representations of the Tonnetz can be used to show traditional harmonic relationships in European classical music.</li><li><strong>Zero crossing rate:</strong><br>The zero-crossing rate is the rate of sign-changes along with a signal, i.e., the rate at which the signal changes from positive to negative or back. This feature has been used heavily in both speech recognition and music information retrieval. It usually has higher values for highly percussive sounds like those in metal and rock.</li><li><strong>Spectral Rolloff:</strong> It is a measure of the shape of the signal. It represents the frequency below which a specified percentage of the total spectral energy, e.g., 85%, lies.</li><li><strong>Onset strength:</strong><br>Compute a spectral flux onset strength envelope. Onset strength at time t is determined by:<br>mean_f max(0, S[f, t] - ref[f, t - lag]), where the ref is S after local max filtering along the frequency axis. By default, if a time series y is provided, S will be the log-power Mel spectrogram.</li><li><strong>Beat information:</strong><br>Dynamic programming beat tracker. Beats are detected in three stages, following the method of: <em>Measure onset strength, estimate tempo from onset correlation, pick peaks in onset strength approximately consistent with estimated tempo</em></li></ul><h4><strong>Resulting DataFrame of the feature extraction:</strong></h4><p>As a result of the extracting step, we get a 28 x 311 DataFrame, which contains 27 features for each of the songs. Important to mention here is that <strong>not every genre has the same amount of songs within the dataset!</strong> We have the following distribution:</p><ul><li><strong>0:</strong> Classic: 37 (~ 13%)</li><li><strong>1:</strong> Hardstyle: 60 (~ 19%)</li><li><strong>2:</strong> House: 80 (~ 25%)</li><li><strong>3:</strong> Punk: 134 (~ 43%)</li></ul><p>This CSV-file can be found on my <a href="https://github.com/maxistaebler/towardsdatascience/tree/main/music-genre-prediction">GitHub</a> or directly downloaded <a href="https://raw.githubusercontent.com/maxistaebler/towardsdatascience/main/music-genre-prediction/data/features.csv">here</a>.</p><h4>Explorative Data Analysis</h4><p>Now that we have extracted all the features, we can look at the data and prepare it for the prediction. In my experience, the first thing to look at is the nature of the data and the possible correlation of different covariates.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Emaximuskarlson%2F14.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=http%3A%2F%2Fchart-studio.plotly.com%2F%7Emaximuskarlson%2F14&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b977e339561e319ffe474876fbee6a48/href">https://medium.com/media/b977e339561e319ffe474876fbee6a48/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrhRlW2TV2v_gArvGxdhOA.png" /><figcaption>Nature of the DataFrame — Huge difference with regard to the size of the different covariates</figcaption></figure><p>Before we analyze the images shown here, I would like to note that I have also anonymized the names of the individual songs for licensing reasons. The name of the individual songs consists here only of the genre and a consecutive number for each genre.<br>Looking at the two plots, we notice on the one hand that there are features that correlate strongly with others and on the other hand that the range of values of the individual features is completely different. Some covariates contain values that are only between 0.04 and 0.05, and others have values of over 4000. Both of these are nothing unusual and can be easily fixed.</p><p>Since large values would have a much greater impact on a machine learning model in the current version but are not necessarily more important for genre prediction than covariates with a smaller range of values, all columns are scaled to a range between 0 and 1. Next, we minimize the correlation within the data by performing a Principal Component Analysis (PCA). <br>Both methods are absolutely standard in the field of data science and have already been explained in numerous articles. I will, therefore, assume an understanding of these methods.</p><p>Here are two great articles that look at both methods in more detail:</p><ul><li><a href="https://towardsdatascience.com/how-and-why-to-standardize-your-data-996926c2c832">Normalization</a> by <em>Serafeim Loukas</em></li><li><a href="https://towardsdatascience.com/understanding-pca-fae3e243731d">PCA</a> by <em>Tony Yiu</em></li></ul><p>The result of the normalization and the dimension reduction is now shown here. If you are interested, you are welcome to examine the plot on your own. At this point, I would like to manifest what a huge fan I am of interactive visualizations from Plotly! If you don’t know this library yet, you should definitely take the time to explore it! Absolute tip!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Emaximuskarlson%2F8.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Emaximuskarlson%2F8%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b461f7c34078e3c7fcdc85b3cd8b7cb4/href">https://medium.com/media/b461f7c34078e3c7fcdc85b3cd8b7cb4/href</a></iframe><p>After the commercial, now back to the topic: <br>Looking at the PCA plot, we see that while the individual genres overlap in places, they still form four relatively well-separated clusters. This is already a very good sign! On further examination, we can draw further conclusions from the data, which, when considered logically and in the context of the four genres and the respective music, make absolute sense:</p><ul><li>The classical songs represent a kind of outlier and are further away from all other clusters. The classical genre also contains a completely different type of music with different instruments compared to the others.</li><li>Hardstyle and House are more similar than either genre with punk. This also makes absolute sense. Hardstyle and house definitely share more musical components than the genre punk.</li></ul><p>One can certainly draw further insights and interpretations from the PCA plot, such as the dispersion within the clusters, etc., but I leave this to you.</p><p><strong>Summary of steps so far:</strong><br>We have analyzed 311 songs, extracted features, cleaned them up, and reduced their dimensions. So the data is now ready to be used with a Machine Learning Model. After we have found and trained a suitable model, we will compare our model with the Spotify API to evaluate the whole process. Ready? Let’s go!</p><h4>Now the fun part: Train, a model</h4><p>Let’s face it when I first started getting involved with Data Science, and I thought that most of the work of a project was spent on creating and evaluating the Machine Learning Model. Oh boy… If I only knew… Anyone who has ever dealt with Machine Learning knows that the preparation of the data takes up most of the work. The quality of the data is, of course, extremely important to achieve reliable and robust results from the model — but fortunately, we have now done both!</p><blockquote>Machine Learning Models are simple: sh*t in, sh*t out!<br> — My Data Mining Professor</blockquote><p>In the context of this project, I have tested several models, but I would like to present only the best of them in this post. Here, of course, every reader is invited to make their own experiments and find a better model! I would also be super interested to know what other or better analyses can be implemented with the existing data! Feel free to contact me in this regard or leave a comment!</p><p><strong>SVM for classification</strong></p><p>In order to not unnecessarily inflate the size of the article, I will refrain from explaining how an SVM works or my decision-making process for the SVM. However, if you are interested in how to evaluate classification and compare different models, you are welcome to read my article about it (<a href="https://medium.com/towards-artificial-intelligence/data-science-evaluation-metrics-unravel-algorithms-267c55f09fa2">Data Science Evaluation Metrics — Unravel Algorithms for Classification</a>).</p><p>Regarding the implementation of the SVM, I would like to point out that I was able to achieve higher accuracy through stratified training and test data sets. The parameter that can be passed in the classic <em>train_test_split</em> takes care of this and ensures the relative class frequencies are approximately preserved in each train and validation fold.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/311bac5412bb582f9a9832ff08fe4270/href">https://medium.com/media/311bac5412bb582f9a9832ff08fe4270/href</a></iframe><p>We get a prediction accuracy of 95% on average across all four genres. As can be seen from the classification report and the Confusion Matrix, individual genres are even classified “<em>perfectly</em>” with respect to Precision or Recall. <br>In short: Precision means how many selected items are relevant, and recall shows how many relevant items were selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWu4o4NV-6Pf8s03yalQUw.png" /><figcaption>Confusion Matrix and Classification Report</figcaption></figure><p>95% accuracy is already very good, and now we have to find out what kind of accuracy we get with the features provided by the Spotify API and the same machine learning model &amp; preparation steps.</p><h4>Spotify API — a powerful instrument!</h4><p>Spotify, along with AppleMusic, is probably the best-known streaming service for music in the Western world. Rather unknown, however, is the powerful API that is provided to every paying user of Spotify. You could write a whole post about what you could do with the API (maybe I will), but here in this post, I want to refer to the corresponding notebook in my GitHub repository and just briefly explain what I did exactly. There are also numerous articles on how to use the API.</p><p>After registering with Spotify as a developer (anyone can do this) and being assigned an API token, you can use the library <a href="https://spotipy.readthedocs.io/en/2.16.1/"><strong><em>Spotify</em></strong></a> to extract information about any song available on Spotify. Here’s an example of the timeless punk classic <em>Basket Case</em> by the band <em>Green Day</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c116354a997a48db24faa60d65a71ffd/href">https://medium.com/media/c116354a997a48db24faa60d65a71ffd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dd7Mz4DnuqC3SwQptNjwtQ.png" /><figcaption>Spotify Features for Basket Case by Green Day</figcaption></figure><p>The table shows the features provided by Spotify. A detailed description and explanation of the features can be found directly in Spotify’s API documentation. The documentation also offers an interactive part where you can analyze your own songs — check it out [<a href="https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-features/">SPOTIFY API LINK</a>].</p><p>Anyway, the API also offers the possibility to directly analyze whole playlists and extract exactly these features shown above for each track within a playlist.<br>So to get a comparable data set, I created a playlist in my profile with the same songs I had already used for my own feature extraction and then parsed it with the API. Since I’m not sure at this point if I’m allowed to publish this data, I refrained from doing so. But with the notebook I provided, you can create your own dataset with your own playlist (or playlists pre-made by Spotify) by customizing the credentials! The notebook is called <em>SPOTIFY_FEATURES.ipynb</em>.</p><p>After performing the same preprocessing steps, we can again look at the first three main components of the data and make a first comparison to the features we extracted ourselves:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Emaximuskarlson%2F11.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Emaximuskarlson%2F11%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/261ee9ba3cdfeff064a89d74a8b0163b/href">https://medium.com/media/261ee9ba3cdfeff064a89d74a8b0163b/href</a></iframe><p>You can tell at first glance that the classic songs are even more clearly separated from the other three genres than before, but the remaining three genres overlap extremely. There is no clear separation between punk, house, and hardstyle. Therefore, we also expect a much lower accuracy in the implementation of our SVM. This follows the completely identical approach as before and delivers the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kj6wDLStm0uziV9K1wEXfw.png" /><figcaption>Spotify Classification Result</figcaption></figure><p>As expected, the accuracy of the classification is much worse. It seems that the present machine learning model with the present features assigns most of the songs to the genre punk. In any case, the overall accuracy is much worse than that of the model with the self-extracted features.</p><blockquote>Great success<br> — Borat</blockquote><h4>Summary</h4><p>In this article, a method was presented to extract properties from music tracks that allow a more precise classification into four genres than the properties provided by Spotify for each song. Although only 9 features are provided by Spotify and not 27 as in our own approach, it could be shown that these 9 provided features are not really suitable to assign a piece of music to one of the four selected genres. <br>The enormous size and possibilities of the Spotify API are definitely a good starting point for further research in this area. This interface is also certainly suitable for other projects.</p><p>Thank you very much for your attention!</p><p><strong>Stay in touch:</strong></p><p>LinkedIn: <a href="https://www.linkedin.com/in/maximilianstaebler">https://www.linkedin.com/in/maximilianstaebler</a><br>Twitter: <a href="https://twitter.com/ms_staebler">https://twitter.com/ms_staebler</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf82232e31a" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/music-genre-prediction-by-extracted-audio-features-and-comparison-to-the-spotify-api-ebf82232e31a">Music Genre Prediction by Extracted Audio-Features + Comparison To the Spotify-API</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Evaluation Metrics — Unravel Algorithms for Regression [Part 2]]]></title>
            <link>https://pub.towardsai.net/data-science-evaluation-metrics-unravel-algorithms-for-regression-part-2-85201ab14ae0?source=rss-3eec54c995e------2</link>
            <guid isPermaLink="false">https://medium.com/p/85201ab14ae0</guid>
            <category><![CDATA[regresion]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[evaluation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[residual]]></category>
            <dc:creator><![CDATA[Maximilian Stäbler]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 10:06:10 GMT</pubDate>
            <atom:updated>2020-12-31T02:49:57.328Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-science">Data Science</a></h4><h3>Error Formulas Data Science Evaluation Metrics — Unravel Algorithms for Regression [Part 2]</h3><h4>Lessons learned about evaluation metrics for classification tasks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qxxQAIPkAN3VEgpC" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Before we get started: This post deals exclusively with evaluation metrics for regressions! I have already written another post (first part) about methods for determining the quality of classification problems. That article can be opened </strong><a href="https://medium.com/towards-artificial-intelligence/data-science-evaluation-metrics-unravel-algorithms-267c55f09fa2"><strong>here.</strong></a></p><p>Now that this has been clarified let’s turn to the second and remaining method from the field of supervised learning applications. Accordingly, we will again use labeled data sets to predict continuous target variables (<em>y</em>) with the help of different algorithms.<br>Briefly, the goal of the regression model is to build a mathematical equation that defines <em>y</em> as a function of the <em>x</em> variables. Next, this equation can be used to predict the outcome (<em>y</em>) on the basis of new values of the predictor variables (<em>x</em>). The simplest and, at the same time, the best-known form of regression is linear regression. Every student has worked with the formula during their school years. The picture below shows the formula for multiple regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*V7uqWXtRkvnQyJtxoLe42Q.png" /><figcaption>Linear regression formula — <a href="https://towardsdatascience.com/multiple-linear-regression-for-manufacturing-analysis-c057d4af718b">Source</a></figcaption></figure><p>As in <a href="https://medium.com/towards-artificial-intelligence/data-science-evaluation-metrics-unravel-algorithms-267c55f09fa2">Part 1</a> of this series of articles, however, we will not focus on the various regression algorithms or their advantages and disadvantages, but on how to evaluate a regression result. <br>The most commonly used metric here is the so-called <strong><em>error</em></strong>. The error is easy to implement and even easier to understand. Basically, you simply compare the predicted value with the real (true) value and calculate the difference. All of these differences are so-called <strong><em>residuals</em></strong>! Residuals in a statistical or machine learning model are, therefore, the differences between observed and predicted values of data. They are a diagnostic measure used when assessing the quality of a model.</p><p><strong>Residuals — Why should I care?</strong></p><p>In general, one should ALWAYS take a look at the residual plot because, with the correct interpretation, numerous deficiencies and problems of the algorithm used are illustrated there. Here is an overview: (a detailed description of the importance of the residuals can be read <a href="https://www.displayr.com/learn-what-are-residuals/">here</a>)</p><p>— The quality of the model can be assessed by looking at the size of the residuals and any patterning of the residuals.<br> — For a perfect model, all residuals would be 0. The further the residuals are from 0, the less accurate the model is. In the case of linear regression, the larger the sum of squared residuals (<strong><em>Mean squared error </em></strong>— explained later), the smaller the R-squared statistic, all else being equal.<br> — If the average residual is not 0, it means that the model is systematically biased (i.e., consistently over-or under-predicts).<br> — If the residuals contain patterns, it means that the model is qualitatively incorrect because it cannot explain the property of the data. The existence of patterns invalidates most statistical tests.</p><p><a href="https://github.com/maxistaebler/towardsdatascience/tree/main/evaluation-metrics"><em>As in the first part, the corresponding notebook can be cloned on my Github account. All datasets used are also included there.</em></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eed929c0adc002e82431f78fa721ab95/href">https://medium.com/media/eed929c0adc002e82431f78fa721ab95/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*o_lTfJ9vhNFvKfwoBADyRA.png" /><figcaption>Residual Plot — Linear Model for Boston Housing Data</figcaption></figure><p>Before we look at the residuals plot, I would like to remind you that residuals are nothing else than the difference between the real value and the model predicted by our model! With this in mind, let’s now look at the residual plot of our linear regression on the known data set (Boston Housing Data).<br>The goal here is to predict the average value of a property based on its characteristics. Although we have a non-optimized model, we can see an approximately random distribution of the residuals. Generally, a good sign! What should give us something to think about is the slightly upward shifted mean value of the residuals, which can also be seen in the histogram on the right side. There are no patterns to be seen. So we can say that our model is not bad at all but definitely needs some fine-tuning to fix the constant overestimation of the property value.</p><p><strong>Ok, I understood how residuals work — what else can be used?</strong></p><p>Very good question, the answer to which will please some readers and disappoint some:<br>There are not as many different methods or approaches to evaluating the model in regression as there are in classification. There, one could find an indiviudellen analysis approach for each model with the Confusion Matrix or most diverse ROC Plots in many different ways. <br>In a regression task, on the other hand, most of the metrics are based on the residuals presented and only aggregate them in different ways. Why this is so is in the nature of regression:<br>You predict a value for a particular set of covariates and compare that to the true value. There are no categorical variables here, only the ability to calculate how wrong the prediction is.</p><p>Therefore, people who don’t want to remember numerous different methods may be happy here, and people who like to have different approaches to evaluation at hand may be a bit disappointed at this point. For the latter, however, the following applies as always: The approaches presented here in no way constitute a complete overview of all metrics for evaluating regressions! Only the most common metrics are presented.</p><p>Variations of the residuals are, for example, the <strong><em>absolute error</em> </strong>(absolute values of the deviation), the <strong><em>mean absolute error</em></strong> (mean of the absolute error values), the <strong><em>mean squared error</em></strong> (squared error), the <strong><em>root mean squared error</em></strong> (square root of the mean squared error) and <strong><em>R-squared.</em></strong></p><p>Before we implement these in an example, it is worth taking a look at the individual formulas. You can see that the metrics build on each other, and the residuals form the basis for the calculation of each of these metrics.</p><p>For the notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuX2NHk8Pqh8HcNm4H2E0g.png" /><figcaption>Error Formulas</figcaption></figure><p>In my opinion, the formulas of the individual metrics are very easy to understand — I hope you see it the same way. Each of these metrics can be the most appropriate in certain applications. However, it must be clearly stated that the <strong><em>MSE, RMSE,</em></strong> and <strong><em>R-squared</em></strong> are the best known and the most commonly used metrics. For this reason, I would like to explain these three in more detail and say what advantages they can offer.</p><h4>MSE</h4><p>MSE ensures by squaring that the negative values do not offset the positive ones. The smaller the MSE, the better the model fits the data. The MSE has the units squared of whatever is plotted on the vertical axis. As you can see, as a result of the squaring, it assigns more weight to the bigger errors. The algorithm then continues to add them up and average them. If you are worried about the outliers, this is the number to look at. Keep in mind and it’s not in the same unit as our dependent value.</p><h4>RMSE</h4><p>The Root Mean Squared Error (RMSE) is just the square root of the mean square error. That is probably the most easily interpreted statistic since it has the same units as the quantity plotted on the vertical axis. The RMSE is directly interpretable in terms of measurement units, and so is a better measure of goodness of fit than a correlation coefficient. One can compare the RMSE to observed variation in measurements of a typical point. The two should be similar for a reasonable fit.</p><h4>R-squared</h4><p>The coefficient of determination of the regression R-squared, also the empirical coefficient of determination, is a dimensionless measure that expresses the portion of the variability in the measured values of the dependent variable, which is “explained” by the linear model. Given the sum-of-squares decomposition, the coefficient of determination of the regression is defined as the ratio of the sum-of-squares explained by the regression to the total sum-of-squares.<br>R-squared has the useful property that its scale is intuitive: it ranges from zero to one, with zero indicating that the proposed model does not improve prediction over the mean model and one indicating perfect prediction. Improvement in the regression model results in proportional increases in R-squared.<br>One pitfall of R-squared is that it can only increase as predictors are added to the regression model. This increase is artificial when predictors are not actually improving the model’s fit.</p><h4>Metrics in action</h4><p>To compare the metrics, we will compare a Support Vector Regression with a Linear Regression and decide based on the values which method gives better results.<br>Important: There is no emphasis on the optimization of the individual methods. Simply the default settings are used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c254b530d56972efabd8b2bb9485ce0b/href">https://medium.com/media/c254b530d56972efabd8b2bb9485ce0b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*4pF5A8baa2sogKzbxVqVhA.png" /><figcaption>Results for the three different metrics</figcaption></figure><p>We can see that our linear regression model performs better than SVR in every metric. The decision of which model to use in further steps is therefore not difficult.</p><h4>Summary</h4><p>To conclude this article, I would like to summarize the most important points once again:</p><p>In contrast to classification tasks, regressions do not have so many different metrics that can be used to evaluate different models.<br>The most common metrics are MSE, RMSE, and R2. <br>My personal favorite is R2, simply because the interpretation is intuitive, and it makes comparing different models very easy.</p><p>I hope I could give a deeper insight into the evaluation metrics for classification and regression tasks with these two posts.</p><p><strong>Thank you very much for your attention!</strong></p><p>Here is some more useful and deeper information:</p><p><a href="http://www.sthda.com/english/wiki/regression-analysis-essentials-for-machine-learning">Regression essentials</a><br><a href="https://www.theanalysisfactor.com/assessing-the-fit-of-regression-models/">R squared explained</a><br><a href="https://www.vernier.com/til/1014">MSE and RMSE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85201ab14ae0" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/data-science-evaluation-metrics-unravel-algorithms-for-regression-part-2-85201ab14ae0">Data Science Evaluation Metrics — Unravel Algorithms for Regression [Part 2]</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Evaluation Metrics — Unravel Algorithms]]></title>
            <link>https://pub.towardsai.net/data-science-evaluation-metrics-unravel-algorithms-267c55f09fa2?source=rss-3eec54c995e------2</link>
            <guid isPermaLink="false">https://medium.com/p/267c55f09fa2</guid>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Maximilian Stäbler]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 09:01:14 GMT</pubDate>
            <atom:updated>2020-12-30T10:08:21.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pnQa_5B3SdT1Ov2o" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><a href="https://towardsai.net/p/category/data-science">Data Science</a>, <a href="https://towardsai.net/p/category/machine-learning">Machine Learning</a></h4><h3>Data Science Evaluation Metrics — Unravel Algorithms for Classification [Part 1]</h3><h4>Lessons learned about evaluation metrics for classification tasks.</h4><blockquote>If you do not know how to ask the right question, you discover nothing.<br><strong>- W. Edwards Deming</strong></blockquote><p>In the machine learning world, there are countless evaluation possibilities, and every day, new ones are added. Right at the beginning of this article, I would also like to mention that there is no cure-all for every data science problem, which always provides the best way to analyze the results. <br>There are prevalent and very robust methods, but in many cases, they have to be adapted, or an application specific method is developed.<br>In order not to inflate this article unnecessarily, I would like to divide the metrics into the two classic data science application groups, classification, and regression. The latter will be discussed in the second part of this article series, and this article is dedicated to the metrics that can be used to evaluate Classification algorithms.</p><p><strong><em>Edit 30.12.2020: Article was just published and can be accessed </em></strong><a href="https://maximilianstaebler.medium.com/data-science-evaluation-metrics-unravel-algorithms-for-regression-part-2-85201ab14ae0"><strong><em>here.</em></strong></a></p><blockquote>Less talk, more content.<br><strong>- Me</strong></blockquote><p><strong>Basics:</strong> To guarantee the understanding of this article and the reproducibility, all code used here is available on my <a href="https://github.com/maxistaebler/towardsdatascience/tree/main/evaluation-metrics">Github [LINK]</a>. The used notebook only needs the libraries <em>pandas, scikit-learn, yellowbrick, matplotlib, and seaborn</em>. All used data sets can also be imported via <em>scikit-learn </em>or are included.</p><p><strong>Classification method: </strong>For the classifications, a logistic regression (binary class) is used. An explanation of the algorithms is not provided. However, excellent descriptions can be found under the following links.</p><p>Logistic Regression: <a href="https://towardsdatascience.com/introduction-to-logistic-regression-66248243c148">LINK</a><br>[1] Pant, A., <em>Introduction to Logistic Regression (2019)</em>, TowardsDataScience</p><p>Furthermore, I can only advise every <em>abitioinated </em>data-scientist to use the library Seaborn to create plots quickly, but I will not go into the creation of these plots. The exact procedure can also be seen in the <a href="https://github.com/maxistaebler/towardsdatascience/tree/main/evaluation-metrics">available notebook.</a></p><h3>Subjected metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9RfhZO89EYSeZ5J" /><figcaption>Photo by <a href="https://unsplash.com/@katertottz?utm_source=medium&amp;utm_medium=referral">Katie Rodriguez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most common and metrics we will focus on are:</p><ul><li><strong><em>Accuracy</em></strong></li><li><strong><em>Precision</em></strong></li><li><strong><em>Recall</em></strong></li><li><strong><em>F1-Score</em></strong></li><li><strong><em>ROC &amp; AUC curve</em></strong></li></ul><p>The first metric we consider in this article is perhaps the easiest to understand metric in the entire field of data science: accuracy.<br><strong>A simple example:</strong> Like every Saturday, I guess the outcome of the German soccer league, and like every Saturday, I guess the right winner of only one of the ten games. Like every Saturday, I lose my money, and like every Saturday, my <em>accuracy is 10%</em>.</p><p>A better example (and cheaper for me) can be described with the very well known <em>breast_cancer</em> record from <em>scikit-learn</em>. This data set describes with a total of 30 covariates whether a patient has cancer or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsqSWyZD5qBoJwgTzlLWIw.png" /><figcaption>Distribution of the binary target variable (cancer or cancer-free)</figcaption></figure><p>As for all other examples, we will now train a model that divides never before seen data sets into two classes and forms the basis for our evaluation metrics. Here we will use logistic regression.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ed4c64040a0efbba115605fd770c2d/href">https://medium.com/media/02ed4c64040a0efbba115605fd770c2d/href</a></iframe><p><strong>Accuracy</strong> — absolute basic knowledge</p><p>All we have to do now to calculate our first metric (<strong>accuracy</strong>) is to compare how our model predicted the correct class for many patients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9dd1c7ca30a226e464cd4577a80709/href">https://medium.com/media/5b9dd1c7ca30a226e464cd4577a80709/href</a></iframe><p>So, we get an accuracy of 94% — not bad for a simple model, right?<br>The answer is yes, and no. Yes, an accuracy of 94% is quite good in most cases, unless you have made a technical mistake such as a wrong train-test-split. <br>But now imagine that you have a total of 100 patients, of whom 94 have no cancer and 6 have cancer cells in their bodies. In this case, the data set would be skewed, and you could reach 94% with a model that predicts a constant 0 (no cancer). <br>Generally speaking, skewed means that one of the binary classes exceeds the others by far ergo has many more entries. <br>In these cases, it is recommended not to use accuracy as a metric for the accuracy of the prediction.</p><p>To tackle these problems, we will use the same approach as in school when learning foreign languages: First, the vocabulary, then the application.<br>We use again the same data set as before, but for simplicity will assume the states as follows:<br> — <em>0 = no cancer<br> — 1 = cancer cells in the chest</em>.<br>Our model will again make predictions for different patients, which will then be compared with the known states. Accordingly, our predictions can assume 4 states, as shown in the figure:</p><figure><img alt="Confusion Matrix with the four states of our predictions" src="https://cdn-images-1.medium.com/max/1024/1*vbfuOkRGdcNkUXp8uEi4BA.png" /><figcaption>Confusion Matrix with the four states of our predictions</figcaption></figure><p>BTW: Check the post about confusion matrices by Mr. Mohajon [<a href="https://towardsdatascience.com/confusion-matrix-for-your-multi-class-machine-learning-model-ff9aa3bf7826">LINK</a>] where I also stole the picture above :-)</p><p><strong>True Positive (TP): </strong>Our model predicts the patient has cancer, and the patient really has cancer. — <em>Top Left</em><br><strong>True Negative (TN): </strong>Our model predicts the patient doesn’t have cancer, and the patient is cancer-free. — <em>Bottom-Right<br></em><strong>False Positive (FP):</strong><em> </em>Our model predicts a patient has cancer, but the patient is cancer-free.<em> — Top-Right<br></em><strong>False Negative (FN):</strong><em> </em>Our model predicts a patient is cancer-free, but the patient has cancer.<em> — Bottom-Left</em></p><p>Nice, now we know how to label our predictions. The size (amount of predictions) labeled with each state can now be used to give us a better understanding of what our model does well and what needs to be improved. For example, in medicine (or in our application case), it is extremely important to detect all cancerous diseases. No patient should be overlooked if possible. If some patients are wrongly classified as “ill,” this is not a good thing, but with further tests, these patients will be detected in almost all cases.</p><p><strong>Precision</strong> <strong>and Recall </strong>— the panacea?</p><p>Precision and recall can be used for exactly such an application. Here are the formulas of the two metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGx9U6VsgLv8riLOCu6flg.png" /><figcaption><a href="https://towardsdatascience.com/confusion-matrix-for-your-multi-class-machine-learning-model-ff9aa3bf7826">https://towardsdatascience.com/confusion-matrix-for-your-multi-class-machine-learning-model-ff9aa3bf7826</a></figcaption></figure><p>You can see directly from the previously made definitions and the formulas that a good model should have the highest possible values for <strong>Precision</strong> and <strong>Recall</strong>. For our first model, the scores are:</p><p><em>Precision: 93,27% — Recall: 98,88%</em></p><p>Both scores are quite high, so is that the final proof that we found the best model ever? Nope. Our dataset is just well-balanced. Let’s change that and create a more realistic real-world user-case. <br>As a reminder, we previously had an approximately balanced data set with class sizes ~200 and ~350, but now that the class sizes have been changed to 1919 and 357, respectively - we should see a big difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lu_N95o3Uhl57QadC7JjEQ.png" /><figcaption>Skewed dataset — Breast cancer</figcaption></figure><p>Metric results:</p><pre>Accuracy: 0.71<br>Precision: 0.5244<br>Recall: 0.8543</pre><p>Well, well, well… One can clearly see that all metrics have dropped dramatically. I do not want to diminish the influence of the model here, but the interpretation of the metrics is more important:<br>Due to the <strong>low precision,</strong> we can conclude that our model produces <strong>quite a lot of false-positives. </strong>This means that we predict a lot of patients have cancer when they are cancer-free in reality.<br>Furthermore, the <strong>okay value for the recall</strong> is a good thing, because as described above, we don’t want to say patients are cancer-free when they actually have breast-cancer. We have <strong>fewer false-negatives.</strong></p><p>That’s all well and good so far, but what do we do if our values for Precision and Recall are not satisfactory?<br>To answer this question, you have to understand how a Machine Learning Model comes to a decision in a binary classification: <strong>The Threshold</strong>.<br>In most models where a probability is predicted, the threshold is set to 0.5, but what does that mean? Basically, only that every probability of a random variable <em>less than the threshold (0.5) is classified as 0,</em> and <em>every probability greater than the threshold is classified as 1</em>. <br>Although this threshold is a common baseline model, it is certainly not ideal for every application. Depending on the value of the threshold, the precision and recall values can change dramatically. <br>How about calculating the precision and recall values for numerous threshold values and plotting them? Damn good idea — congratulations: We just derived the <strong>Precision-Recall curve</strong>.</p><p>Note: Many of the following plots were created with the <em>Yellowbrick library</em>, which makes analysis of scikit-learn models extremely easy! Absolute recommendation! <a href="https://www.scikit-yb.org/en/latest/index.html">[LINK]</a></p><p><strong>Precision-Recall-Curve</strong></p><p>For the visualization of the curve, we will use a new data set. It contains NLP-features of an email and the information if the mail is spam or not. So we want to classify it binary again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ffa2ea68959db89ccabc9ce400c777/href">https://medium.com/media/63ffa2ea68959db89ccabc9ce400c777/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*unyEehzclO5lM2hesDYYPw.png" /><figcaption>Threshold plot for the spam dataset with logistic regression.</figcaption></figure><p>The displayed plot offers a lot of helpful information about the model, its capabilities, and potential limitations. <em>The optimal threshold is 0.44.<br></em>What we can see directly is that while the accuracy increases as the threshold increases, the recall curve simultaneously decreases more and more. <br>An explanation for the shape of the two curves is absolutely logical after reading the upper part attentively (hopefully):<br>If we increase the threshold more and more until every mail is marked as spam, we will not miss any real spam mail (maximum precision). Still, we will also label all mails that do actually not spam as unwanted messages (very low recall).</p><p>A value that is also directly shown in the plot and represents a harmonic mean value of Precision and Recall is the <strong>F1 value.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*cdmfghgZw3d7-rm0YYZPAQ.png" /><figcaption>F1 Formula — Source:<a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c</a></figcaption></figure><p>So you can analyze the <strong>red F1 plot</strong> instead of looking at the two plots for precision (blue) and recall (green). This value is also always between 0 and 1, where 1 would mean a perfect prediction. Because the value is derived from the precision and recall curve, this value is very well suited for skewed data sets.</p><p>Similar to Precision and Recall or the F1 value, other metrics can be calculated from the results of the Confusion Matrix. The names of these metrics give a clear overview of their meaning:<br><em>TPR — True Positive Rate:</em> Exact the same as precision<br><em>FPR — False Positive Rate:</em> 1-FPR is also called specificity (True Negative Rate)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwcHM66BdXun7UtwT83rBw.png" /><figcaption>TPR &amp; FPR — source: <a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c</a></figcaption></figure><p><strong>ROC &amp; AUC Curve — Visualization of the Confusion Matrix</strong></p><p>The AUC — ROC curve is an output measurement in different threshold settings for classification problems. In detail:<br><strong>ROC is a curve of probability<br>AUC is the degree or measure of separability.</strong> <br><strong>Both together show how much the model can differentiate between groups.</strong></p><p>The better the model is at correctly predicting classes, the higher the AUC (best value 1, worst 0). In the context of our spam-dataset, a higher AUC means that the model will better predict whether a mail is a spam or not. <em>Graphically speaking, the AUC is the area under the ROC curve!</em> As always, it is much easier to understand by looking at an example. Here is the code and generated plot for the ROC-AUC curve of our spam-dataset and model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9275f2b4e6cfc4e0b57a142762ff0426/href">https://medium.com/media/9275f2b4e6cfc4e0b57a142762ff0426/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*FKCkdKkM75uhbsbMhQbBNg.png" /><figcaption>ROC — AUC curve</figcaption></figure><blockquote>Nice plot maxi, but how can you use it now?</blockquote><p>Similar to the threshold-plot before, this plot can be used to select the best threshold. In addition, this plot gives direct information about how the respective threshold influences the <em>FPR (False-Positive-Rates) </em>and the <em>TPR (True-Positive-Rate)</em>, which is crucial for some applications!</p><p>Take our spam example: Here, the overall goal is to detect all spam. If single mails should end up in the spam folder without authorization, this is to a certain degree to be acceptable (under the realistic assumption that there is no perfect model). Translated into technical terms, this means that we want a very high true positive rate and a low false-negative rate. <br>This translated to the ROC curve, which would mean that we want the highest possible <strong>TPR value (Y-axis)</strong> with the lowest possible <strong>FPR value (X-axis)</strong>. But since spam detection has priority, one is theoretically willing to make concessions on the X-axis. If you want fewer <em>false-positives,</em> you get more <em>false-negatives</em> in return. So for this example, you can see that if you want to have a 100% probability of detecting spam, you’ll get almost 40% of the mails as wrongly marked spam. On the other hand, a model with another threshold that “only” detects about 97% of spam would only mark about 7% of normal mails as spam. As said before, the decision is made by the user.</p><p>The <em>AUC</em> is also widely used when dealing with skewed datasets! What the <em>AUC</em> does, is that it notifies you that you have several wrongly classified positives (FP) despite the fact that you have high accuracy because of the dominant class, and therefore it would return a low score in this case. The reason for this is that the number of false positives will grow, and therefore the denominator is becoming larger (TP / (TP + <strong>FP</strong>)).</p><h3>Summary</h3><p>In these articles, the important metrics for the evaluation of classification problems were presented. Although the accuracy alone may be sufficient in some (simple) use cases, it is recommended to include other metrics to analyze the results. Since the <em>ROC &amp; AUC</em> curve gives a very detailed insight into the capabilities and problems of the classification model, it is probably the most used of the presented methods. <br>However, it should be noted that there are many other more accurate, complex, and possibly much better-suited methods.</p><p><em>Part 2 of this article then deals with the most common methods for evaluating regression problems.</em></p><p><strong>Stay in touch:</strong></p><p>LinkedIn: <a href="https://www.linkedin.com/in/maximilianstaebler">https://www.linkedin.com/in/maximilianstaebler</a><br>Twitter: <a href="https://twitter.com/ms_staebler">https://twitter.com/ms_staebler</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267c55f09fa2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/data-science-evaluation-metrics-unravel-algorithms-267c55f09fa2">Data Science Evaluation Metrics — Unravel Algorithms</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>