<?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 Carlos Domínguez García on Medium]]></title>
        <description><![CDATA[Stories by Carlos Domínguez García on Medium]]></description>
        <link>https://medium.com/@carlos-dg?source=rss-7468545a5eae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CJPUplaW6FLkSWiVuFr-bA.png</url>
            <title>Stories by Carlos Domínguez García on Medium</title>
            <link>https://medium.com/@carlos-dg?source=rss-7468545a5eae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:32:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlos-dg/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[Understanding Heart Disease via Data Science]]></title>
            <link>https://carlos-dg.medium.com/understanding-heart-disease-via-data-science-397f14f22e43?source=rss-7468545a5eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/397f14f22e43</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[heart-disease]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Carlos Domínguez García]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 18:57:21 GMT</pubDate>
            <atom:updated>2021-06-03T18:57:21.209Z</atom:updated>
            <content:encoded><![CDATA[<h4>With Data Science, motivation, and the internet you can work on any domain that interest you.</h4><figure><img alt="A white heart image for decoration" src="https://cdn-images-1.medium.com/max/1024/0*OIBcLfcWY7xoHfkW" /><figcaption>Photo by <a href="https://unsplash.com/@nicolafioravanti?utm_source=medium&amp;utm_medium=referral">Nicola Fioravanti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What is Heart Disease? Why does it happen? As Data Scientists we have the privilege of having a set of tools that allow us to study any topic that interests us 🙂</p><p>Here you’ll find the results of my learning journey on this topic. Hopefully, it will walk you through an intuitive understanding of what is Heart Disease, why it happens, and creating models to determine whether a patient has heart disease or not based on the <a href="https://www.kaggle.com/ronitf/heart-disease-uci">popular Heart Disease dataset</a>.</p><p>You can find <a href="https://www.kaggle.com/carlosdg/a-detail-description-of-the-heart-disease-dataset">the code for this article in this Notebook</a></p><h3>Table of Contents</h3><ol><li>Introduction</li><li>Context</li><li>Dataset</li><li>Heart Disease Prediction</li><li>Bibliography</li></ol><h3>1. Introduction</h3><p>According to the National Heart, Lung and Blood Institute:</p><blockquote>Heart disease is a catch-all phrase for a variety of conditions that affect the heart’s structure and function. Coronary heart disease is a type of heart disease that develops when the arteries of the heart cannot deliver enough oxygen-rich blood to the heart. <strong>It is the leading cause of death in the United States</strong>.</blockquote><blockquote><em>(Source: </em><a href="https://www.nhlbi.nih.gov/health-topics/espanol/enfermedad-coronaria"><em>nhlbi.nih.gov</em></a><em>)</em></blockquote><p>Also, according to the World Health Organization, cardiovascular diseases are the <strong>leading cause of death globally</strong> (source: <a href="https://www.who.int/news-room/fact-sheets/detail/cardiovascular-diseases-(cvds)">WHO</a>).</p><p>In this article, we try to learn enough information about this topic to <strong>understand the </strong><a href="https://www.kaggle.com/ronitf/heart-disease-uci"><strong>Heart Disease UCI</strong></a><strong> dataset and build simple models to predict whether a patient has a disease or not</strong> based on features like the heart rate during exercise or the cholesterol levels in the blood.</p><h3>2. Context</h3><h3>2.1. Blood and heart</h3><p>Blood is very important to ensure the proper functioning of the body. Its functions cover the transport of oxygen and nutrients to the cells of the body as well as the removal of cellular waste products.</p><p>Blood is transported to the rest of the body because it is pumped by the heart. This organ receives oxygen-poor blood and sends it to the lungs to oxygenate it. And sends the oxygen-rich blood that comes from the lungs to the rest of the body.</p><figure><img alt="Animated GIF showing the flow of the blood through the chambers of the heart" src="https://cdn-images-1.medium.com/max/300/0*9lipA3RszmU6yqeq.gif" /><figcaption>By josiño — Own work, Public Domain, <a href="https://commons.wikimedia.org/w/index.php?curid=9396374">https://commons.wikimedia.org/w/index.php?curid=9396374</a>. Flow of the blood through the chambers of the heart. Blue arrows represent oxygen-poor blood received from the rest of the body and sent to the lungs. Red arrows represent oxygen-rich blood coming from the lungs that are sent to the rest of the body.</figcaption></figure><p>An inadequate supply of the blood can result in cells not having enough energy to function properly, causing the death of the cells in the worst case.</p><h3>2.2. Coronary heart disease</h3><p>The heart also needs oxygen and nutrients to function properly, these come through arteries known as “coronary arteries”. When we talk about coronary disease, we often mean difficulty of the blood flow in these arteries due to the accumulation of substances on their walls.</p><figure><img alt="Image showing a coronary artery where the blood cannot flow due to plaque buildup" src="https://cdn-images-1.medium.com/max/400/0*3FZSrnZNBGd6crBg.gif" /><figcaption>By NIH: National Heart, Lung and Blood Institute — <a href="http://www.nhlbi.nih.gov/health/health-topics/topics/heartattack/">http://www.nhlbi.nih.gov/health/health-topics/topics/heartattack/</a>, Public Domain, <a href="https://commons.wikimedia.org/w/index.php?curid=25287085">https://commons.wikimedia.org/w/index.php?curid=25287085</a>. Death of heart cells due to ischemia in the coronary arteries.</figcaption></figure><p>In the worst case, the impact of leaving the cells of the heart without nutrients and oxygen is a heart attack, in other words, the death of part of the heart cells. This, in turn, would have an impact on the rest of the body because the pumping of the heart would be affected.</p><h3>2.3. Glossary of terms</h3><ul><li><strong>Atherosclerosis:</strong> accumulation of substances on the walls of arteries that can hinder the blood flow. Moreover, the rupture of this plaque of substances can cause the formation of a blood clot (thrombus) that, in turn, can block even more the affected area or go to other parts of the body and block those parts (embolism). (Sources: <a href="https://www.heart.org/en/health-topics/cholesterol/about-cholesterol/atherosclerosis">American Heart Association</a>, <a href="https://www.mayoclinic.org/diseases-conditions/arteriosclerosis-atherosclerosis/symptoms-causes/syc-20350569">Mayo Clinic</a>)</li><li><strong>Ischemia:</strong> blood flow reduction to a tissue (a group of cells). This implies a reduction of the supply of oxygen and nutrients, so cells won’t get enough energy to function properly. (Sources: <a href="https://www.heart.org/en/health-topics/heart-attack/about-heart-attacks/silent-ischemia-and-ischemic-heart-disease">American Heart Association</a>, <a href="https://www.mayoclinic.org/diseases-conditions/myocardial-ischemia/symptoms-causes/syc-20375417">Mayo Clinic</a>, <a href="https://en.wikipedia.org/wiki/Ischemia">Wikipedia</a>)</li><li><strong>Angina:</strong> chest pain due to a blood flow reduction in the coronary arteries. (Sources: <a href="https://www.nhs.uk/conditions/angina/">United Kingdom National Health Service</a>, <a href="https://www.youtube.com/watch?v=3UhItS50mRI">(Spanish) Video sobre angina de Alberto Sanagustín</a>)</li><li><strong>Stable angina:</strong> angina caused by situations that require oxygen (for example, exercise or stress) and it goes away on rest.</li><li><strong>Unstable angina:</strong> angina that can happen even on rest.</li><li><strong>Typical &amp; atypical angina:</strong> typical angina usually means chest discomfort. However, looks like some people can experience other symptoms like nausea or shortness of breath. In these cases, people talk about atypical angina. (Sources: <a href="https://www.harringtonhospital.org/typical-and-atypical-angina-what-to-look-for/">Harrington Hospital</a>, <a href="https://en.wikipedia.org/wiki/Angina#Diagnosis">Wikipedia</a>).</li><li><strong>Thrombus:</strong> blood mass in solid-state that hinders the blood flow in a blood vessel. (Source: <a href="https://medlineplus.gov/ency/article/001124.htm">MedlinePlus</a>)</li><li><strong>Embolus:</strong> a thrombus that detaches and goes to other parts of the body. (Source: <a href="https://medlineplus.gov/ency/article/001124.htm">MedlinePlus</a>)</li><li><strong>Acute myocardial infarction:</strong> also known as <em>heart attack</em>, is the death of part of the heart tissue due to ischemia. In other words, it is the death of part of the cells due to the lack of oxygen. (Sources: <a href="https://www.healthline.com/health/acute-myocardial-infarction#causes">Healthline</a>, <a href="https://en.wikipedia.org/wiki/Infarction">Wikipedia</a>)</li><li><strong>Electrocardiogram:</strong> graph record of the electric signals that cause heartbeats. Each part of the record of a normal heartbeat has a name, the most interesting ones for this project are the T wave and the ST segment because they can give some information about the presence of issues like ischemia or infarction. (Sources: <a href="https://www.mayoclinic.org/tests-procedures/ekg/about/pac-20384983">Mayo Clinic</a>, <a href="https://es.wikipedia.org/wiki/Electrocardiograma">Wikipedia</a>, <a href="https://www.youtube.com/watch?v=A67NDj3_RrU">(Spanish) Video sobre electrocardiograma de Alberto Sanagustín</a>, <a href="https://www.youtube.com/watch?v=SLe281LBBRU&amp;list=PL3BE5DA0A5DF3BF75">(Spanish) Serie de videos sobre el electrocardiograma normal de Alberto Sangaustín</a>)</li><li><strong>Nuclear stress test:</strong> a radioactive dye is injected into the patient to see the blood flow on rest and doing exercise. Moreover, during this test, the activity of the heart is also measured with an electrocardiogram. (Sources: <a href="https://www.mayoclinic.org/tests-procedures/nuclear-stress-test/about/pac-20385231">Mayo Clinic</a>, <a href="https://www.healthline.com/health/thallium-stress-test">Healthline</a>)</li><li><strong>Asymptomatic disease:</strong> a disease that a patient has but they experience very few or no symptoms. (Sources: <a href="https://definicion.de/asintomatico/">(Spanish) definicion.de</a>, <a href="https://www.mayoclinic.org/es-es/diseases-conditions/heart-attack/expert-answers/silent-heart-attack/faq-20057777">MayoClinic</a>, <a href="https://en.wikipedia.org/wiki/Asymptomatic">Wikipedia</a>)</li><li><strong>Left ventricular hypertrophy:</strong> thickening of the walls of the main heart chamber that pumps the blood to the rest of the body. This can cause the muscle to lose elasticity which, in turn, causes the heart to not work properly. (Sources: <a href="https://www.mayoclinic.org/diseases-conditions/left-ventricular-hypertrophy/symptoms-causes/syc-20374314">Mayo Clinic</a>)</li></ul><h3>3. Dataset</h3><p>This dataset is hosted on Kaggle (<a href="https://www.kaggle.com/ronitf/heart-disease-uci">Heart Disease UCI</a>) and comes from the <a href="https://archive.ics.uci.edu/ml/datasets/Heart+Disease">UCI Machine Learning Repository</a>. There are records of about 300 patients from Cleveland and the features are described in the following section.</p><h3>3.1. Dataset problems</h3><p>Thanks to the <a href="https://www.kaggle.com/ronitf/heart-disease-uci/discussion/105877">post of <em>InitPic</em> </a>we noted that this dataset is a bit different from the original one while the description is the same.</p><p>Part of these differences is that there were a few null values in the original dataset that have taken some values here:</p><blockquote><em>A few more things to consider:</em></blockquote><blockquote><em>data #93, 159, 164, 165 and 252 have ca=4 which is incorrect. In the original Cleveland dataset they are NaNs (so they should be removed)</em></blockquote><blockquote><em>data #49 and 282 have thal = 0, also incorrect. They are also NaNs in the original dataset.</em></blockquote><p>Because these are just a few instances, I decided to drop them.</p><h3>3.2. Dataset features</h3><h3>3.2.1. target</h3><p>Target variable: whether the patient has heart disease or not</p><ul><li>Value 0: yes</li><li>Value 1: no</li></ul><p>We can see that the distribution is quite balanced. Thanks to this it wouldn’t be a bad idea to use accuracy to evaluate how well the models perform.</p><figure><img alt="Distribution of the target variable" src="https://cdn-images-1.medium.com/max/840/0*5IDNjBAK4bKa2aX2.png" /></figure><h3>3.2.2. age</h3><p>Patient age in years. In the data we can see, as expected, that age is a risk factor. In other words, the higher the age, the more likely it is that the patient has heart disease.</p><figure><img alt="Distribution of age based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*rctbd3DaSbcsqF5V.png" /></figure><h3>3.2.3. sex</h3><p>Patient sex</p><ul><li>Value 0: female</li><li>Value 1: male</li></ul><p>There are approximately half of women than men. And men seem more likely to have heart disease than women. Could this difference be because of sex? 🤔 Maybe it can be due to some other factor, for example, maybe men are more likely to smoke? this could be an interesting topic to do deeper research about 🙂</p><figure><img alt="Distribution of sex based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*lxmKzqoyZFB-WzVO.png" /></figure><h3>3.2.4. cp</h3><p>Chest pain type</p><ul><li>Value 0: asymptomatic</li><li>Value 1: atypical angina</li><li>Value 2: pain without relation to angina</li><li>Value 3: typical angina</li></ul><p>The description of the data doesn’t provide information about how this classification of pain was made. But on the graph below we can see that it is very difficult to tell whether a patient has heart disease attending just to the symptoms of the patients.</p><figure><img alt="Distribution of chest pain based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*waA8i2YfL3EDowAA.png" /></figure><h3>3.2.5. trestbps</h3><p>Resting blood pressure in millimeters of mercury (mm Hg) when the patient was admitted to the hospital.</p><p>By looking at the different peaks, looks like most people tend to have normal blood pressure inside certain groups (could be healthy adults, adults that take medication, seniors…). It also looks like very high pressures can indicate that there is heart disease.</p><figure><img alt="Distribution of blood pressure based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*_TjbXwfj1Yhde1wW.png" /></figure><h3>3.2.6. chol</h3><p>Cholesterol level in mg/dl. This is a variable that we can control to prevent the disease. Looks like the majority of the people in the dataset have high levels of cholesterol. It also looks like up to a certain level, the presence of heart disease is slightly higher on higher cholesterol levels. Though the cases that have the highest levels of cholesterol don’t have heart disease… without much information we could guess that these are outliers, maybe these people weren’t fasting when the blood sample was taken.</p><figure><img alt="Distribution of cholesterol based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*CcIP716QXRWCtJ7R.png" /></figure><h3>3.2.7. fbs</h3><p>Whether the level of sugar in the blood is higher than 120 mg/dl or not. This is another variable that we can control. However, by itself, it doesn’t seem very useful to know if a patient has heart disease or not. Though we shouldn’t drop it right now because it might be useful when combined with other variables.</p><ul><li>Value 0: no</li><li>Value 1: yes</li></ul><figure><img alt="Distribution of sugar in blood based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*XTpLitVbMgtdbw2k.png" /></figure><p>Hereon, variables are related to a nuclear stress test. That is a stress test where a radioactive dye is also injected into the patient to see the blood flow.</p><h3>3.2.8. restecg</h3><p>Results of the electrocardiogram on rest</p><ul><li>Value 0: probable left ventricular hypertrophy</li><li>Value 1: normal</li><li>Value 2: abnormalities in the T wave or ST segment</li></ul><p>When someone has a heart disease the first symptom usually is stable angina (angina during exercise). When angina happens even on rest the disease got worse (usually due to a narrowing of the coronary arteries). This has to be why there are so few patients that show an abnormality in the heart rate on rest, and it is also why seeing this abnormality is very indicative of a presence of heart disease.</p><p>On the other hand, the value 0, <em>probable</em> presence of hypertrophy, doesn’t seem to be very indicative of the presence of heart disease by itself. It can be because this variable is not very accurate (as noted by the “probable presence”).</p><figure><img alt="Distribution of the results of the electrocardiogram on rest based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*GgwycHl3AlBiZCCx.png" /></figure><h3>3.2.9. thalach</h3><p>Maximum heart rate during the stress test</p><p>At first sight, it may seem weird to see that the higher the heart rate the lower the presence of heart disease and vice versa. However, it makes sense to take into account that the maximum healthy heart rate depends on the age (220 — age). Thus, higher rates tend to be from younger people.</p><figure><img alt="Distribution of the heart rate during exercise based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*WJuaMVpEPqnfnO9K.png" /></figure><p><strong>Patients with a heart rate during exercise lower than 100:</strong></p><figure><img alt="Table showing the patients with heart rate lower than 100" src="https://cdn-images-1.medium.com/max/424/1*FNSJLTMdT5n-Oj33Bunxow.png" /></figure><p><strong>Patients with a heart rate during exercise higher than 180:</strong></p><figure><img alt="Table showing the details of patients with heart rate greater than 180" src="https://cdn-images-1.medium.com/max/418/1*X6e4U6UPHCISmoY7SRuVCA.png" /></figure><h3>3.2.10. exang</h3><p>Whether the patient had angina during exercise</p><ul><li>Valor 0: no</li><li>Valor 1: yes</li></ul><p>We can see that this feature is a good indicator of the presence of heart disease. However, we can also see that knowing what is angina is not an easy task, it can be confused with other pains or it can be atypical angina.</p><figure><img alt="Distribution of the presence of angina based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*k54ZhCZ2CJokq_wr.png" /></figure><h3>3.2.11. oldpeak</h3><p>Decrease of the ST segment during exercise according to the same one on rest.</p><p>The ST segment is a part of the electrocardiogram of a heartbeat that is usually found at a certain level in a normal heartbeat. A significant displacement of this segment can indicate the presence of heart disease as we can see in the plot.</p><figure><img alt="Distribution of ST segment displacement based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*XaPGnmEBNghjlsy7.png" /></figure><h3>3.2.12. slope</h3><p>The slope of the ST segment during the most demanding part of the exercise</p><ul><li>Value 0: descending</li><li>Value 1: flat</li><li>Value 2: ascending</li></ul><p>In the first graph, we can see that the slope by itself can help determine whether there is a heart disease or not if it is flat or ascending. However, if the slope is descending doesn’t seem to give much information. Because of this, in the second graph we add a third variable where we can see that, if the slope is descending, the depression of the ST segment can help to determine if the patient has heart disease.</p><figure><img alt="Distribution of ST segment slope based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*WsiXr6O2Mp94EXRD.png" /></figure><figure><img alt="Box plot of ST segment displacement vs slope based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*0R2GPjwHHyi_mQBi.png" /></figure><h3>3.2.13. thal</h3><p>Results of the blood flow observed via the radioactive dye.</p><ul><li>Value 0: NULL (dropped from the dataset previously)</li><li>Value 1: fixed defect (no blood flow in some part of the heart)</li><li>Value 2: normal blood flow</li><li>Value 3: reversible defect (a blood flow is observed but it is not normal)</li></ul><p>This feature and the next one are obtained through a very invasive process for the patients. But, by themselves, they give a very good indication of the presence of heart disease or not.</p><figure><img alt="Distribution of thalium results based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*OP2xaA5ksXnsl6T1.png" /></figure><h3>3.2.14. ca</h3><p>The number of main blood vessels colored by the radioactive dye. The number varies between 0 to 4 but the value 4 represents a null value and these have been dropped previously.</p><p>This feature refers to the number of narrow blood vessels seen, this is why the higher the value of this feature, the more likely it is to have heart disease.</p><figure><img alt="Distribution of the results of coloured blood vessels based on the target variable" src="https://cdn-images-1.medium.com/max/840/0*ZOl2yo5rz_1vxslD.png" /></figure><h3>4. Heart Disease Prediction</h3><h3>4.1. Experiments</h3><p>For this part, I chose to build four models. Three simple ones: logistic regression, Naïve Bayes, and decision trees. And one a bit more complex: random forest.</p><p>To keep the project simple, no extra processing apart from some cleaning was done to the dataset.</p><p>To compare the models we first divide the dataset into a training set with 70% of instances and a test set with the rest of the instances. And this taking into account that the distribution of the target has to be the same in both sets.</p><p>The test set mimics data in the real world, it will only be used at the end of the project to get a more robust measure of the models on unseen data.</p><p>The training set will be used to evaluate the models via 10 fold cross-validation. For simplicity, we’ll leave the hyperparameter selection of the models by default, this means that some random combinations will be chosen and the models will be trained via cross-validation for each combination, keeping the hyperparameter combination that gave the best result.</p><h3>4.2. Results</h3><figure><img alt="Tables with the results of Cross-Validation for the accuracy and kappa metrics" src="https://cdn-images-1.medium.com/max/1024/1*fv-_4LHvWZgPXAN3-b0V4w.png" /></figure><p>Logistic regression was the best. Moreover, its metrics are the ones that vary the least if we take a look at the quartiles.</p><p>On the other hand, the rest of the models have metrics that vary more, this indicates that they might not be reliable to deal with unseen data.</p><p>As for final results, we’ll see how logistic regression performs on the test set. And we’ll take the tree as an example to see that it doesn’t do a good job.</p><h3>4.3. Final results</h3><p><strong>Logistic regression</strong></p><figure><img alt="Confusion matrix and final results on the test set for Logistic Regression" src="https://cdn-images-1.medium.com/max/744/1*GdSPkC6g1j2UgZ9-6W-AQQ.png" /></figure><p>Good news. We have more or less the same results as in cross-validation. We also have a confusion matrix with most observations on the main diagonal.</p><p>However, the results of the tree are much more different than their cross-validation mean as expected:</p><figure><img alt="Confusion matrix and final results on the test set for Decision Tree" src="https://cdn-images-1.medium.com/max/746/1*U0bWFtdsGbaBr4KkQ9ZrNA.png" /></figure><h3>5. Bibliography</h3><p>In addition to the links provided throughout the notebook, the following resources were also consulted to better understand the topic (some may be in Spanish):</p><ul><li>“Heart disease and heart attacks”. Khan Academy. Link: <a href="https://www.khanacademy.org/science/health-and-medicine/healthcare-misc/v/heart-disease-and-heart-attacks">https://www.khanacademy.org/science/health-and-medicine/healthcare-misc/v/heart-disease-and-heart-attacks</a></li><li>“Cellular respiration introduction”. Khan Academy. Link: <a href="https://www.khanacademy.org/science/biology/cellular-respiration-and-fermentation/intro-to-cellular-respiration/v/introduction-to-cellular-respiration">https://www.khanacademy.org/science/biology/cellular-respiration-and-fermentation/intro-to-cellular-respiration/v/introduction-to-cellular-respiration</a></li><li>“Enfermedades cardiovasculares”. Organización Mundial de la Salud. Link: <a href="https://www.who.int/es/news-room/fact-sheets/detail/cardiovascular-diseases-(cvds">https://www.who.int/es/news-room/fact-sheets/detail/cardiovascular-diseases-(cvds)</a>)</li><li>“Heart Disease”. Mayo Clinic. Link: <a href="https://www.mayoclinic.org/diseases-conditions/heart-disease/symptoms-causes/syc-20353118">https://www.mayoclinic.org/diseases-conditions/heart-disease/symptoms-causes/syc-20353118</a></li><li>“Coronary artery disease”. Mayo Clinic. Link: <a href="https://www.mayoclinic.org/diseases-conditions/coronary-artery-disease/symptoms-causes/syc-20350613">https://www.mayoclinic.org/diseases-conditions/coronary-artery-disease/symptoms-causes/syc-20350613</a></li><li>“Heart Attack (Myocardial Infarction)”. Cleveland Clinic. Link: <a href="https://my.clevelandclinic.org/health/diseases/16818-heart-attack-myocardial-infarction">https://my.clevelandclinic.org/health/diseases/16818-heart-attack-myocardial-infarction</a></li><li>“Coronary Artery Disease”. Cleveland Clinic. Link: <a href="https://my.clevelandclinic.org/health/diseases/16898-coronary-artery-disease">https://my.clevelandclinic.org/health/diseases/16898-coronary-artery-disease</a></li><li>Institute of Medicine (US) Committee on Social Security Cardiovascular Disability Criteria. Cardiovascular Disability: Updating the Social Security Listings. Washington (DC): National Academies Press (US); 2010. 7, Ischemic Heart Disease. Available from: <a href="https://www.ncbi.nlm.nih.gov/books/NBK209964/">https://www.ncbi.nlm.nih.gov/books/NBK209964/</a></li></ul><p>Thank you for reading this article! 😄 Any feedback? It would be much appreciated 🙂 Feel free to share your thoughts here in the comments, or on the <a href="https://www.kaggle.com/carlosdg/a-detail-description-of-the-heart-disease-dataset">Notebook</a>, or even on <a href="https://www.linkedin.com/in/carlos-dominguez-garcia/">LinkedIn</a>!</p><p>Have a nice day! 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397f14f22e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing the effect of hyperparameters on Support Vector Machines]]></title>
            <link>https://medium.com/data-science/visualizing-the-effect-of-hyperparameters-on-support-vector-machines-b9eef6f7357b?source=rss-7468545a5eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9eef6f7357b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Carlos Domínguez García]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 21:22:41 GMT</pubDate>
            <atom:updated>2021-02-07T21:22:41.877Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get a visual intuition of what happens when different kernel functions and hyperparameters are used in SVMs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yxa7XTpNjLyMbdYS" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico?utm_source=medium&amp;utm_medium=referral">Kaleidico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The goal of this article is to visually see the effect of each hyperparameter and kernel function of a SVM to understand their effects on the models.</p><p>First a brief introduction to SVMs is presented followed by the dataset. For the purpose of this project, the dataset is a simple one with just two features to easily visualize it in two dimensions. The dataset will be divided into a training and validation dataset. And, for each kernel function, a visualization is presented showing the effects of different hyperparameter.</p><p>You can find <a href="https://www.kaggle.com/carlosdg/effect-of-hyperparameters-and-kernels-on-svms">the source code in this Notebook</a>.</p><h3>Table of Contents</h3><ol><li>Introduction to SVMs</li><li>Dataset</li><li>Popular kernel functions</li><li>Conclusions</li><li>Acknowledgments</li></ol><h3>Introduction to SVMs</h3><p>Support Vector Machines are supervised Machine Learning models used for classification (or regression) tasks. In the case of binary classification, there is a dataset made of 𝑛 observations, each observation made of a vector 𝑥𝑖 of 𝑑 dimensions and a target variable 𝑦𝑖 which can be either −1 or 1 depending on whether the observation belongs to one class or the other.</p><p>Using this data, a SVM learns the parameters of a hyperplane, 𝑤⋅𝑥−𝑏=0 that separate the space in two parts: one for the observations of one class and the other part for the other class. Furthermore, among all possible hyperparameters that separate both classes, a SVM learns the one that separates them the most, that is, leaving as much distance/margin as possible between each class and the hyperplane</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*wiBuzmzjyAPbrnPI" /><figcaption>Maximum-margin hyperplane and margin for an SVM trained on two classes. Samples on margins are called support vectors because they are the only samples needed to define the hyperplane.<br>Image by Larhmam, CC BY-SA 4.0 &lt;<a href="https://creativecommons.org/licenses/by-sa/4.0">https://creativecommons.org/licenses/by-sa/4.0</a>&gt;, via Wikimedia Commons</figcaption></figure><p>To learn the parameters of the hyperplane, a SVM tries to maximize the margin between the observations, with the additional constraint that observations of different classes have to be on different sides of the hyperplane.</p><p>This article will not get into much detail about the math behind how SVMs get these parameters. However, to provide some intuition that may be useful, it is interesting to note that <strong>training data, </strong>𝑥<strong>, will only appear as part of scalar products when computing the parameters of the hyperplane</strong>.</p><p>Thanks to this observation, SVMs can get the advantage of what is called a kernel function. This is a function that returns the same thing as the scalar product between two vectors but without needing to calculate the coordinates of those vectors. And this is very useful because we can simulate applying operations that increase the dimensionality of 𝑥 without the need of going to higher dimensions which is computationally cheaper (this is called the <em>kernel trick</em>).</p><p>Thanks to this, SVMs can work for data that is not linearly separable. Instead of trying to fit some complicated function to the data, <strong>a SVM goes to higher dimensions where the data could be linearly separable and finds the hyperplane to separate the data there</strong> (and back in the original dimension, it won’t look like a linear separation).</p><p>And now is the time to say that, because of this, SVMs do not calculate the parameters of the hyperplane, instead they remember the 𝑥’s that they need to calculate the hyperplane and, when a new input data comes, SVMs performs the scalar products between these 𝑥’s, called Support Vectors, and the input data. Again, this is to keep using scalar products and take advantage of the kernel functions.</p><p>Another interesting thing to note is that it is common to not find a perfect separation between two classes. And this is bad for SVMs, because during training (calculating the hyperplane parameters) they try to maximize the margin between classes with the constraint that observations of one class must be on one side of the hyperplane and observations of the other class, on the other side. To help with this, SVMs have “soft margins”, which is a parameter that relaxes this by regulating how many observations are allowed to pass the margin.</p><h3>Dataset</h3><p>The dataset is a modification of the iris dataset to have just two dimensions so it can be easily visualized. In particular, it consists of sepal length and width for setosa and versicolor iris flowers.</p><p>The next figure shows how this dataset was divided in training and validation sets. Furthermore, the data has been preprocessed to have a mean of 0 and unit variance. This is a good practise because <strong>SVMs use scalar products, so if a variable has a larger range of values than the rest, it will dominate the result of the scalar product</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*HiyMZpCUD4wBcLDt.png" /><figcaption><em>Image by author</em></figcaption></figure><h3>Popular kernel functions</h3><p>This section introduces the four most common kernel functions and a visualization with the effect that each hyperparameter has on the result of the SVM.</p><h3>Linear kernel function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*05-Qa9MH3Q3A_ZC9u0PBow.png" /><figcaption><em>Image by author</em></figcaption></figure><p>This is the simplest kernel function because it is equivalent to not use any kernel function. In other words, it directly computes the scalar product between the inputs. It does not add any extra hyperparameters to the SVM and it is perfect to see the effect of the hyperparameter 𝐶 that regulates the margin.</p><p>Next plots shows the result of training the SVM with a linear kernel on the training dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*6je21A7iEJACUrvm.png" /><figcaption><em>Image by author</em></figcaption></figure><p>The background color represents the decision of the SVM. The training dataset is represented as points in the plane and their class is represented also with color. Highlighted points represent the Support Vectors, that is, the data points that define the hyperplane. Dash-lines represent the margin of the SVM. And above each plot you can find the R2 score of that SVM on the validation dataset and the value of the hyperparameter used.</p><p>As seen in the plots, <strong>the effect of incrementing the hyperparameter </strong>𝐶<strong> is to make the margin tighter</strong> and, thus, less Support Vectors are needed to define the hyperplane.</p><h3>RBF Kernel Function (Radial Basis Function)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*1-CVOxFXSb9Hei1N9s9uDw.png" /><figcaption><em>Image by author</em></figcaption></figure><p>This function adds an extra hyperparameter to tune, 𝛾. But, unlike in the case of the linear kernel function, this function does map the data to a higher dimension. And, as it can be seen in the plots below, now the SVM can represent a non-linear separation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*Fzq5NDwp1ko1uAd_.png" /><figcaption><em>Image by author</em></figcaption></figure><p>From top to bottom we can see the effect of incrementing the hyperparameter 𝐶, which affects the margin of the SVM as seen previously.</p><p>On the other hand, from left to right, we can see the effect of incrementing 𝛾<strong>: lower values result in separations that look more linear and, as </strong>𝛾<strong> increases, it results in more complex separations</strong>.</p><p>With a sufficiently high 𝛾, every observation of the training set are Support Vectors. In other words, every training point is used to define the hyperplane, which indicates a clear overfitting. Moreover, the more support vectors used, the more computationally expensive is the SVM and the more time it needs to make a prediction.</p><p>Finally, it might be interesting to note that, looking at the separations in the original dimension of the data, it looks like a gaussian, just like the kernel function formula looks like a gaussian.</p><h3>Sigmoid Kernel Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*OYKOpB3uz903YKjQRW1Cdw.png" /><figcaption><em>Image by author</em></figcaption></figure><p>In this function there are two extra hyperparameters: 𝑟 and another one also called 𝛾 that, as it can be seen below, it also affects the complexity of the separation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*erG1HjrHKXyXCvs1.png" /><figcaption><em>Image by author</em></figcaption></figure><p>Now the 𝐶 hyperparameter has been fixed because as shown above it affects the margin. From top to bottom can be seen <strong>the effect of varying </strong>𝛾<strong>, which helps making separations more complex as it increases</strong>, just like with the RBF kernel function.</p><p>The 𝑟 hyperparameter doesn’t have a very clear visual effect with small changes. However, looking at the function definition, tanh(γxi⋅xj + r), <strong>the effect of this constant </strong>𝑟<strong> is to shift the hyperbolic tangent:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*ts6isBrMgS8B7y7l.png" /><figcaption><em>Image by author</em></figcaption></figure><p><strong>Higher positive and negative values for the </strong>𝑟<strong> constant dominates the result, it makes it harder for the scalar product to have an impact on the result of the function.</strong></p><p>If we interpret the scalar product as a measure of similarity between two vectors, kernel functions also represent similarities. So we could interpret this effect of 𝑟 as biasing the result, which can be useful if we know that some class is prefered over the other?</p><h3>Polynomial Kernel Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*zfn44yM3kB5MMylECn_o5Q.png" /><figcaption><em>Image by author</em></figcaption></figure><p>This last kernel function has three hyperparameters: a factor 𝛾 that affects the scalar product, a constant 𝑟 and the degree of the polynomial, 𝑑.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3Fh7QCjipnrHclk.png" /><figcaption><em>Image by author</em></figcaption></figure><p>From top to bottom can be seen that <strong>the effect of incrementing the degree of the polynomial and </strong>𝛾<strong> is to make more complex separations</strong>.</p><p>From left to right can be seen that <strong>the effect of varying </strong>𝑟<strong> looks similar to what happens with the </strong>𝑟<strong> in the sigmoid function, at least for lower degrees of the polynomial.</strong></p><h3>Conclusions</h3><p>This article started with a brief introduction to SVMs, followed by the dataset used. Then, it showed the visual effect, in the dimension of the original data, of varying the hyperparameters of the most common kernel functions. These effects could be classified in two categories following the visual intuition: either they affect the margin of the SVM and/or they affect the non-linearity of the separation.</p><p>It is commonly advised to use the RBF kernel as the “go-to” kernel function as it is one with just two hyperparameters to tune and it can model non-linear separations. But, as many things, this might not be the perfect kernel function for any task, depending on the data there could be a kernel function that models better the separation between the classes. Hopefully this article gives the readers an intuition to help choose the kernel function to use and/or better understand SVMs 🙂</p><h3>Acknowledgments</h3><p>Special thanks to <a href="https://www.linkedin.com/in/angeligareta/">Angel Igareta</a> for reviewing this article before publishing it 😊</p><p>Thank you for reading this article! 😄 Any feedback? It would be much appreciated 🙂 Feel free to share your thoughts here on the comments, or on the <a href="https://www.kaggle.com/carlosdg/effect-of-hyperparameters-and-kernels-on-svms">Notebook</a> or even on <a href="https://www.linkedin.com/in/carlos-dominguez-garcia/">LinkedIn</a>!</p><p>Have a nice day! 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9eef6f7357b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/visualizing-the-effect-of-hyperparameters-on-support-vector-machines-b9eef6f7357b">Visualizing the effect of hyperparameters on Support Vector Machines</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>