<?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 Rajesh Kumar on Medium]]></title>
        <description><![CDATA[Stories by Rajesh Kumar on Medium]]></description>
        <link>https://medium.com/@raj2apl?source=rss-62ce992fccf3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FjiLOGbQR4DhAResbPne_w.jpeg</url>
            <title>Stories by Rajesh Kumar on Medium</title>
            <link>https://medium.com/@raj2apl?source=rss-62ce992fccf3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:54:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raj2apl/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[My first project in data science]]></title>
            <link>https://medium.com/@raj2apl/my-first-project-in-data-science-1709e22e8ed2?source=rss-62ce992fccf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1709e22e8ed2</guid>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[healthy-lifestyle]]></category>
            <category><![CDATA[heartbreak]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[heart-disease]]></category>
            <dc:creator><![CDATA[Rajesh Kumar]]></dc:creator>
            <pubDate>Thu, 05 May 2022 08:26:07 GMT</pubDate>
            <atom:updated>2022-05-05T08:26:07.545Z</atom:updated>
            <content:encoded><![CDATA[<p>In my first blog ,I have mentioned about how I got motivated towards data science and what pushed me to select heart failure project.</p><p>Since I am a power plant professional with more than 10 year of experience in a very reputed company and I feel proud to be associated with this company. I could choose project related to my core domain expertise but I selected to go with healthcare because of my curiosity and challenges.</p><p>Here I put down the brief about heart failure project and how I completed with a lot of challenges.</p><ol><li>Introduction:</li></ol><p>Cardiovascular diseases are diseases of the heart and blood vessels and they typically include heart attacks, strokes, and heart failures [1]. According to the World Health Organization (WHO), cardiovascular diseases like ischaemic heart disease and stroke have been the leading causes of deaths worldwide for the last decade and a half [2].</p><p>Dataset Link:</p><p><a href="https://www.kaggle.com/andrewmvd/heart-failure-clinical-data">Heart Failure Prediction</a></p><p>Dataset Description:</p><p><a href="https://www.kaggle.com/datasets/raj2apl/vdf3456vfg">Heart failure prediction with KNN</a></p><p>About the data:</p><p>The dataset was originally released by Ahmed et al., in 2017 [3] as a supplement to their analysis of survival of heart failure patients at Faisalabad Institute of Cardiology and at the Allied Hospital in Faisalabad, Pakistan. The dataset was subsequently accessed and analyzed by Chicco and Jurman in 2020 to predict heart failures using a bunch of machine learning techniques [4]. The dataset hosted on Kaggle cites these authors and their research paper.</p><p>The dataset primarily consists of clinical and lifestyle features of 105 female and 194 male heart failure patients. You can find each feature explained in the figure below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*Gw7xnkgufNWKDjnAQ43wXw.png" /></figure><p>Project Workflow:</p><p>The workflow would be pretty straightforward —</p><p>1. <strong>Data Preprocessing — </strong>Cleaning the data, imputing missing values, creating new features if needed, etc.</p><p>2. <strong>Exploratory Data Analysis — </strong>This would involve summary statistics, plotting relationships, mapping trends, etc.</p><p>3. <strong>Model Building — </strong>Building a baseline prediction model, followed by at least 2 classification models to train and test.</p><p>4. <strong>Hyper-parameter Tuning — </strong>Fine-tune the hyper-parameters of each model to arrive at acceptable levels of prediction metrics.</p><p>5. <strong>Consolidating Results — </strong>Presenting relevant findings in a clear and concise manner.</p><h3>Data Preprocessing:</h3><p>I prefer to use google collaborator whenever I work with machine learning datasets as it provides GPU support and a lot of preloaded libraries. For loading the datasets in google collab we will use the following code.</p><p>From google.colab import files</p><p>Uploaded=files.upload ()</p><p>Let’s read in the .csv file into a dataframe —</p><p>df=pd.read_csv(‘heart_failure_clinical_records_dataset.csv’)</p><p>df.info () is a quick way to get a summary of the dataframe data types. We see that the dataset has no missing or spurious values and is clean enough to begin data exploration.</p><p>&lt;class ‘pandas.core.frame.DataFrame’&gt;<br> RangeIndex: 299 entries, 0 to 298<br> Data columns (total 13 columns):<br> # Column Non-Null Count Dtype <br> — — — — — — — — — — — — — — — <br> 0 age 299 non-null float64<br> 1 anaemia 299 non-null int64 <br> 2 creatinine_phosphokinase 299 non-null int64 <br> 3 diabetes 299 non-null int64 <br> 4 ejection_fraction 299 non-null int64 <br> 5 high_blood_pressure 299 non-null int64 <br> 6 platelets 299 non-null float64<br> 7 serum_creatinine 299 non-null float64<br> 8 serum_sodium 299 non-null int64 <br> 9 sex 299 non-null int64 <br> 10 smoking 299 non-null int64 <br> 11 time 299 non-null int64 <br> 12 DEATH_EVENT 299 non-null int64 <br> dtypes: float64(3), int64(10)<br> memory usage: 30.5 KB</p><p>We observe that –Sex,diabetes,anaemia,high_blood_pressure,smoke &amp; death are categorical features(object), while age, platelets,creatinine_phosphokinase,ejection_fraction,serum_creatinine,serum_sodium and time are numerical features (<em>int64 or float64</em>).</p><p>All features except death would be potential predictors and death would be the target for our prospective ML model.</p><h3>Exploratory Data Analysis:</h3><h3>A. Summary Statistics of Numerical Features</h3><p>Since our dataset has many numerical features, it would be helpful to look at some aggregate measures of the data in hand, with the help of df.describe() (<em>Usually, this method gives values up to 6 decimal places, so it would better to round it off to two by </em>df.describe().round(2)<em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*-MEYcQSwNK9qz2uhvQOfdQ.png" /></figure><p>Note:- Here some features names are converted into short name:</p><p>Plt-platelate count</p><p>· <strong>Age</strong>: We can see that the average age of the patients is 60 years with most of the patients (&lt;75%) below 70 years and above 40 years. The follow-up time after their heart failure also varies from 4 days to 285 days, with an average of 130 days.</p><p>· <strong>Platelets</strong>: <em>These are a type of blood cells that are responsible for repairing damaged blood vessels.</em> A normal person has a platelet count of 150,000–400,000 kiloplatelets/mL of blood [5]. <strong>In our dataset, 75% of the patients have a platelet count well within this range.</strong></p><p>· <strong>Ejection fraction</strong>: <em>This is a measure (in %) of how much blood is pumped out of a ventricle in each contraction. To brush up a little human anatomy — the heart has 4 chambers of which the atria receive blood from different parts of the body and the ventricles pump it to back. The left ventricle is the thickest chamber and pumps blood to the rest of the body while the right ventricle pumps blood to the lungs. </em>In a healthy adult, this fraction is 55% and heart failure with reduced ejection fraction implies a value &lt; 40%[6]. In our dataset, <strong>75% of the patients have this value &lt; 45% </strong>which is expected because they are all heart failure patients in the first place.</p><p>· <strong>Creatinine Phosphokinase</strong>: <em>This is an enzyme that is present in the blood and helps in repairing damaged tissues. A high level of CPK implies heart failure or injury.</em> The normal levels in males are 55–170 mcg/L and in females are 30–135 mcg/L [7]. In our dataset, since all patients have had heart failure, <strong>the average value (550 mcg/L) and median (250 mcg/L) are higher than normal.</strong></p><p>· <strong>Serum creatinine</strong>: <em>This is a waste product that is produced as a part of muscle metabolism especially during muscle breakdown. This creatinine is filtered by the kidneys and increased levels are indicative of poor cardiac output and possible renal failure</em>[8]. The normal levels are between 0.84 to 1.21 mg/dL [9] and in our dataset, the average and median are above 1.10 mg/dL, which is <strong>pretty close to the upper limit</strong> of the normal range.</p><ul><li><strong>Serum sodium</strong>: <em>This refers to the level of sodium in the blood and a high level of &gt; 135 mEq/L is called hypernatremia, which is considered typical in heart failure patients</em> [10]. In our dataset, we find that the average and the median are <strong>&gt; 135 mEq/L</strong>.</li></ul><p>A neat way to visualize these statistics is with a boxenplot which shows the spread and distribution of values (<em>The line in the center is the median and the diamonds at the end are the outliers</em>).</p><h3>B. Summary Statistics of Categorical Features</h3><p>The number of patients belonging to each of the lifestyle categorical features can be summarised with a simple bar plot .</p><p>fig = plt.subplots(figsize=[10,6])bar1 = df.smk.value_counts().values<br> bar2 = df.hbp.value_counts().values<br> bar3 = df.dia.value_counts().values<br> bar4 = df.anm.value_counts().values<br> ticks = np.arange(0,3, 2)<br> width = 0.3<br> plt.bar(ticks, bar1, width=width, color=’teal’, label=’smoker’)<br> plt.bar(ticks+width, bar2, width=width, color=’darkorange’, label=’high blood pressure’)<br> plt.bar(ticks+2*width, bar3, width=width, color=’limegreen’, label=’diabetes’)<br> plt.bar(ticks+3*width, bar4, width=width, color=’tomato’, label=’anaemic’)plt.xticks(ticks+1.5*width, [‘Yes’, ‘No’])<br> plt.ylabel(‘Number of patients’)<br> plt.legend()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*RqDNs6AXl22sbDJYW4T2LA.png" /></figure><p>Additional summaries can be generated using the crosstab function in pandas. An example is shown for the categorical feature smk(smoker) . The results can be normalized with respect to either the total number of smokers (<em>‘index’</em>) or the total number of deaths (<em>‘columns’</em>). Since our interest is in predicting survival, we normalize with respect to death</p><pre>pd.crosstab(index=df[&#39;smk&#39;], columns=df[&#39;death&#39;], values=df[&#39;chk&#39;], aggfunc=np.sum, margins=True)pd.crosstab(index=df[&#39;smk&#39;], columns=df[&#39;death&#39;], values=df[&#39;chk&#39;], aggfunc=np.sum, margins=True, normalize=&#39;columns&#39;).round(2)*100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*sdHmSXkqiI1pr1r9JlpKyA.png" /></figure><p>We see that 68% of all heart failure patients did not smoke while 32% did. Of those who <strong>died</strong>, 69% were non-smokers while 31% were smokers. Of those who <strong>survived</strong>, 67% were non-smokers and 33% were smokers. At this point, it is difficult to say, conclusively, that heart failure patients who smoked have a greater chance of dying.</p><p>In a similar manner, let’s summarise the rest of the categorical features and normalize the results with respect to deaths.</p><p>· 65% of the Male and 35% of the Female heart patients died.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*_OzgwzLI9R3odpFdSkVbPg.png" /></figure><p>· 48% of the patients who died were anemic while 41% of the patients who survived were anemic as well.</p><p>· 42% of the patients who died and 42% who survived were diabetic.</p><p>· 31% of the dead were smokers while 33% of the survivors were smokers.</p><p>· 41% of those who died had high blood pressure, while 33% of those who survived had high blood pressure as well.</p><p>Based on these statistics, we get a rough idea that the lifestyle features are almost similarly distributed amongst those who died and those who survived. The difference is the greatest in the case of high blood pressure, which could perhaps have a greater influence on the survival of heart patients.</p><h3>C. Exploring relationships between numerical features</h3><p>The next step is to visualize the relationship between features. We start with the numerical features by writing a single line of code to plot a pair-wise plotting of features using seaborn’s pairplot—</p><p>sns.pairplot(df[[‘plt’, ‘ejf’, ‘cpk’, ‘scr’, ‘sna’, ‘death’]], <br> hue=’death’, palette=’husl’, corner=True)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*pXAw4nwk_wwi9U_4J3K9DA.png" /></figure><p>We observe a few interesting points —</p><p>· Most of the patients who died following a heart failure seem to have a lower Ejection Fraction that those who survived. They also seem to have slightly higher levels of Serum Creatinine and Creatine Phosphokinase. They also tend to be on the higher side of 80 years.</p><p>· There are no strong correlations between features and this can be validated by calculating the Spearman R correlation coefficient (<em>We consider the spearman because we are not sure about the population distribution from which the feature values are drawn</em>).</p><p>df[[‘plt’,’ejf’,’cpk’,’scr’,’sna’]].corr(method=’spearman’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*mytiZ_qI7FX0dHXVA1XYNg.png" /></figure><p>· As observed, the correlation coefficients are <strong>moderately encouraging</strong> for <strong>age-serum creatinine</strong> and<strong> serum creatinine-serum sodium</strong>. From literature, we see that with age, the serum creatinine content increases [11], which explains their <strong>slightly positive relationship</strong>. Literature also tells us [12] that the sodium to serum creatinine ratio is high in the case of chronic kidney disease which implies a <strong>negative relationship</strong> between the two. The slight negative correlation coefficient also implies the prevalence of renal issues in the patients.</p><h3>D. Exploring relationships between categorical features</h3><p>One way of relating categorical features is to create a pivot table and pivot about a subset of the features. This would give us the number of values for a particular subset of feature values. For this dataset, let’s look at the lifestyle features — smoking, anemic, high blood pressure, and diabetes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*tRDlTJh1jM-QfvBhtEOWdw.png" /></figure><p>A few insights can be drawn —</p><p>· A large number of the patients did not smoke, were not anemic and did not suffer from high blood pressure or diabetes.</p><p>· There were very few patients who had all the four lifestyle features.</p><p>· Many of the survivors were either only smokers or only diabetic.</p><p>· The majority of the deceased had none of the lifestyle features, or at the most were anemic.</p><p>· Many of the deceased were anemic and diabetic as well.</p><h3>E. Exploring relationships between all features</h3><p>An easy way to combine categorical and numerical features into a single graph is bypassing the categorical feature as a hue input. In this case, we use the binary death feature and plot violin-plots to visualize the relationships across all features.</p><p>fig,ax = plt.subplots(6, 5, figsize=[20,22])<br> cat_features = [‘sex’,’smk’,’anm’, ‘dia’, ‘hbp’]<br> num_features = [‘age’, ‘scr’, ‘sna’, ‘plt’, ‘ejf’, ‘cpk’]<br> for i in range(0,6):<br> for j in range(0,5):<br> sns.violinplot(data=df, x=cat_features[j],y=num_features[i], hue=’death’, split=True, palette=’husl’,facet_kws={‘despine’:False}, ax=ax[i,j])<br> ax[i,j].legend(title=’death’, loc=’upper center’)</p><p>Here are a few insights from these plots —</p><p>· <strong>Sex</strong>: Of the patients who died, the ejection fraction seems to be lower in males than in females. Also, the creatinine phosphokinase seems to be higher in males than in females.</p><p>· <strong>Smoking</strong>: A slightly lower ejection fraction was seen in the smokers who died than in the non-smokers who died. The creatinine phosphokinase levels seem to be higher in smokers who survived, than in non-smokers who survived.</p><p>· <strong>Anemia</strong>: The anemic patients tend to have lower creatinine phosphokinase levels and higher serum creatinine levels, than non-anemic patients. Among the anemic patients, the ejection fraction is lower in those who died than in those who survived.</p><p>· <strong>Diabetes</strong>: The diabetic patients tend to have lower sodium levels and again, the ejection fraction is lower in those who died than in the survivors.</p><p>· <strong>High Blood Pressure</strong>: The ejection fraction seems to show greater variation in deceased patients with high blood pressure than in deceased patients without high blood pressure.</p><p><strong>Note:-</strong>Before dealing with outliers we require knowledge about the outlier, the dataset and possibly some domain knowledge. Removing outliers without a good reason will not always increase accuracy. Without a deep understanding of what are the possible ranges that exist within each feature, removing outliers becomes tricky. With little research we could see that all the values in serum_creatinine falls in possible range of values. So they are not outliers. They are actual data points that helps in predicting DEATH_EVENT.</p><p>#We shall select only 4 features from the outlier removed dataframe X = df1[[‘time’, ‘ejection_fraction’, ‘serum_creatinine’,’age’]] y = df1[‘DEATH_EVENT’]</p><p>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state=0)</p><p>Scaler = StandardScaler()</p><p>X_train = scaler.fit_transform (X_train) X_test = scaler.transform(X_test)</p><p>Classifier = LogisticRegression () classifier.fit (X_train, y_train)</p><p>LogisticRegression ()</p><p>logpred=classifier.predict(X_test)</p><p>from sklearn.metrics import confusion_ matrix, classification_report</p><p>confusion_matrix(y_test,logpred)</p><p>array ([[40, 3], [ 4, 13]])</p><p>print (classification_report(y_test,logpred))</p><p>precision recall f1-score support</p><p>0 0.91 0.93 0.92 43 1 0.81 0.76 0.79 17</p><p>Accuracy 0.88 60</p><p>Macro avg 0.86 0.85 0.85 60</p><p>Weighted avg 0.88 0.88 0.88 60</p><p>Now ok..After removing outliers our accuracy and F1 score has increased Signicantly</p><p><strong>#KNN Classication:</strong></p><p>From sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score</p><p><strong>#choosing K value:</strong></p><p>list1=[] for k in range(3,10): classifier=KNeighborsClassifier(n_neighbors=k) classifier.fit(X_train,y_train) y_pred=classifier.predict(X_test) errors=1-accuracy_score(y_test,y_pred) list1.append(errors) plt.plot(list(range(3,10)),list1) plt.show()</p><p>classifier = KNeighborsClassifier(n_neighbors=10) classifier.fit(X_train, y_train)</p><p>KNeighborsClassifier (n_neighbors=10)</p><p>Kpred=classifier.predict (X_test)</p><p>confusion_matrix (y_test,kpred)</p><p>array ([[39, 4],</p><p>[ 5, 12]])</p><p>print (classification_report(y_test,kpred))</p><p>Precision recall f1-score support</p><p>0 0.89 0.91 0.90 43 1 0.75 0.71 0.73 17</p><p>accuracy 0.85 60 macro avg 0.82 0.81 0.81 60 weighted avg 0.85 0.85 0.85 60</p><p>Conclusion on Heart Disease Prediction:</p><p>1.We did data visualization and data analysis of the target variable, age features, sex analysis and others along with its univariate analysis and bivariate analysis.</p><p>2. We also did a complete feature engineering in which summons all the valid steps needed for further steps i.e. model building.</p><p>3. From the above model accuracy, Logistic regression is giving us the accuracy which is 88% and KNN gives only 85% accuracy at k&gt;=5.</p><h3>References:</h3><p><em>[1] </em><a href="https://www.who.int/cardiovascular_diseases/world-heart-day/en/"><em>https://www.who.int/cardiovascular_diseases/world-heart-day/en/</em></a></p><p><em>[2]</em><a href="https://www.who.int/gho/mortality_burden_disease/causes_death/top_10/en/"><em>https://www.who.int/gho/mortality_burden_disease/causes_death/top_10/en/</em></a></p><p><em>[3] Ahmad T, Munir A, Bhatti SH, Aftab M, Ali Raza M. Survival analysis of heart failure patients: a case study. Dataset. </em><a href="https://plos.figshare.com/"><em>https://plos.figshare.com/</em></a><em> articles/Survival_analysis_of_heart_failure_patients_A_case_study/ 5227684/1.</em></p><p><em>[4] Chicco and Jurman, BMC Medical Informatics and Decision Making (2020) 20:16</em></p><p><em>[5]</em><a href="https://www.hopkinsmedicine.org/heart_vascular_institute/centers_excellence/women_cardiovascular_health_center/patient_information/health_topics/platelets.html"><em>https://www.hopkinsmedicine.org/heart_vascular_institute/centers_excellence/women_cardiovascular_health_center/patient_information/health_topics/platelets.html</em></a></p><p><em>[6] </em><a href="https://www.uwhealth.org/health/topic/special/heart-failure-with-reduced-ejection-fraction-systolic-heart-failure/tx4090abc.html#:~:text=A%20normal%20ejection%20fraction%20is,fraction%20is%2040%25%20or%20less."><em>https://www.uwhealth.org/health/topic/special/heart-failure-with-reduced-ejection-fraction-systolic-heart-failure/tx4090abc.html#:~:text=A%20normal%20ejection%20fraction%20is,fraction%20is%2040%25%20or%20less.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1709e22e8ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I motivated towards data science]]></title>
            <link>https://medium.com/@raj2apl/how-i-motivated-towards-data-science-ecb3a4eeaf68?source=rss-62ce992fccf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb3a4eeaf68</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[challenges-and-growth]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[heart-disease]]></category>
            <dc:creator><![CDATA[Rajesh Kumar]]></dc:creator>
            <pubDate>Thu, 05 May 2022 07:31:59 GMT</pubDate>
            <atom:updated>2022-05-05T08:34:08.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*ge_uOLRJNsq0VhC8juD7JQ.jpeg" /></figure><p>You may think you know the human body heart, lungs, brain and bones but it’s time to think again. Your body is full of extraordinary mysteries that science is only just beginning to understand. I took this project because of my curiosity and to know the heart in better way and develop the understanding level about medical science. Since I had been suffering from low platelets counts for last 3 years and it was obvious to check every 6 month report to see my platelets count. So I am very much familiar with the term used in heart failure data set that influenced me to took this project.</p><p>Through this post, I wish to document my work on this task and present it as a research exercise. So this would naturally involve a bit of domain knowledge, references to journal papers, and deriving insights from them.</p><p>While studying Data science from IIT Roorkee, I took project on Heart_failure_prediction to challenge myself to know in depth about heart failure and get expertise in healthcare domain.</p><p>It was quite challenging and interesting to complete this project which I would like to share with all of you in next blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb3a4eeaf68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>