<?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 Ravsehaj Singh Puri on Medium]]></title>
        <description><![CDATA[Stories by Ravsehaj Singh Puri on Medium]]></description>
        <link>https://medium.com/@ravsehajsinghpuri?source=rss-751694db0065------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*yLTYttcqPqe5JGYKh1OZnA.jpeg</url>
            <title>Stories by Ravsehaj Singh Puri on Medium</title>
            <link>https://medium.com/@ravsehajsinghpuri?source=rss-751694db0065------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:50:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ravsehajsinghpuri/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[The Ultimate Beginner’s Guide To Implement A Neural Network From Scratch]]></title>
            <link>https://medium.com/data-science/the-ultimate-beginners-guide-to-implement-a-neural-network-from-scratch-cf7d52d91e00?source=rss-751694db0065------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf7d52d91e00</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <dc:creator><![CDATA[Ravsehaj Singh Puri]]></dc:creator>
            <pubDate>Thu, 14 May 2020 23:46:54 GMT</pubDate>
            <atom:updated>2020-05-15T16:33:55.057Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learning the calculus and mathematics behind neural networks and converting equations to code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C99phV75NuJi_zJY" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Abstract</h3><p>Neural networks have been with us for a long time but they have gathered importance in recent years due to advancement in computing machinery as well as growing needs of technology in various aspects of life.</p><p>From the perspective of a beginner in machine learning, a neural network is considered as a black box which can ingest some data and spit out predictions or classification categories depending upon the problem at hand. The beauty of neural networks is that they are based on simple calculus and linear algebra or a combination of both. These work together to come up with close to accurate results when provided with high quantity and quality data.</p><p>So, if you are motivated to learn the basics of how a neural network actually works, you have reached the right place. Follow me along this post and you’ll be able to build your own neural network from scratch.</p><h3>What Are Neural Networks?</h3><p>A neural network’s architecture is derived from the structure of a human brain while from a mathematical point of view, it can be understood as a function which maps a set of inputs to desired outputs. The main idea of this post is to understand this function in detail and implementing it in python.</p><p>A neural network comprises of 7 Parts :</p><ol><li><strong>Input Layer (X) </strong>: This layer contains the values corresponding to the features in our dataset.</li><li><strong>A set of weights and biases (W₁,W₂,..etc); (b₁,b₂,..etc)</strong> : These weights and biases are represented in the form matrices and they decide the importance of each feature/column in our dataset.</li><li><strong>Hidden Layer</strong> : This layer acts as a brain of the neural network and also as an interface between the input and the output layer. There can be one or more than one hidden layers in a neural network.</li><li><strong>Output Layer (<em>ŷ) </em></strong>: The values transmitted from the input layer will reach this layer via the hidden layer(s).</li><li><strong>A set of activation functions (A)</strong> : This is the component which adds a non-linearity flavour to an otherwise linear model. These functions are applied to the output of each layer except the input layer and activate/transform them.</li><li><strong>The Loss function (L) : </strong>This function calculates the measure as to how well our guess/prediction is, and it is used while back propagating through the network.</li><li><strong>Optimiser</strong> : This optimiser is a function that updates the model parameters according to gradients which are calculated during back propagation (You’ll learn shortly).</li></ol><h3>The Learning Process</h3><p>Neural networks learn/train from the training data and then their performance is tested using test data. There are 2 parts of the training process:</p><ol><li>Feed forward</li><li>Back-propagation</li></ol><p>Feed forward is basically traversing the neural network from input layer to the output layer by predicting a value. On the other hand, back-propagation makes the network actually learn by computing gradients and pushing them back through the network and finally updating the model parameters. Let us first see how these 2 processes work on paper and then we will convert our equations into code.</p><p>Let us first design our neural network architecture. The architecture which we will be using for this post is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktgUTrYq6TMUQyPvhnGbWw.png" /><figcaption>Neural Network Architecture</figcaption></figure><h4>Feed Forward</h4><p>As far as our architecture is concerned, we just need 2 equations to carry out the feed forward process and for future purposes, you may remember:</p><p><strong><em>number of layers of the neural network = number of hidden layers + 1(output layer)</em></strong></p><p><strong><em>number of weight matrices = number of layers</em></strong></p><p>We will be using <strong>ReLu</strong> and <strong>Sigmoid</strong> activation functions in this post but other activation functions can alse be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Cf1bEOsSYOBcJ329b-qPgw.png" /><figcaption>Equation-1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1a4gyfpR_BALhGA_VMBEpw.png" /><figcaption>Equation-2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HXsQBidbO6brYPnPRdmq0g.png" /><figcaption>Sigmoid function definition</figcaption></figure><p>Here, X, W₁, b₁, W₂ and b₂ are matrices and matrix level computations are done in both the equations above. For better understanding, we can have a look at these matrices representing X, W₁, b₁, W₂ and b₂. In this post, we are ignoring the bias terms b₁ and b₂ but they can be dealt with in a similar manner.</p><p>Let us define a few values first :</p><p><strong>n₁</strong>= number of neurons in the input layer, <strong>n₂</strong>= number of neurons in the hidden layer, <strong>n₃</strong>= number of neurons in the output layer.</p><p>Now, you might be thinking of how to decide the number of neurons for Input layer, hidden layer and output layer. Here is the answer.</p><p><strong>number of neurons in the input layer (n₁)</strong>= number of features/columns in our dataset i.e. the number of independent variables.</p><p><strong>number of neurons in the hidden layer (n₂)</strong> is flexible.</p><p><strong>number of neurons in the output layer (n₃)</strong> =</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65qu0lwpiUaRtl2KVxmGzw.png" /><figcaption>Number of output neurons</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBhEViu71lDAjoJD79VNeQ.png" /><figcaption>Matrices Representing X, W1 and W2</figcaption></figure><p>Dimensions of X: [m, n₁] ; Dimensions of W₁: [n₁, n₂] ;</p><p>Dimensions of W₂: [n₂, n₃]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2ojwGyBIz2eWsWsN" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Back Propagation</h4><p>Back propagation is an essential part in training a neural network. It is a method of learning on the basis of gradients which are calculated using the most beautiful part of calculus i.e. the <strong>Chain Rule.</strong> This<strong> </strong>chain rule is repetitively applied to calculate gradients across the network. To make it more clear, a gradient is the derivative of loss function w.r.t. to a model parameter (weight or bias).</p><p>As mentioned earlier, we won’t be using bias terms and will only consider weights as model parameters. So, we have 2 model parameters i.e. W₁ and W₂. The loss function which we will be using is MSE (Mean Square Error). Now let us see how back propagation actually works mathematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*eDwiHtEbftEM17tKe49pvg.png" /><figcaption>Loss Function</figcaption></figure><p>where m= number of training examples/rows in the dataset</p><p>y= ground truth/label in the dataset</p><p>Let us calculate the gradient of loss w.r.t. W₂ using chain rule :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pmwxg0kfDRDEv3ypnFnkRw.png" /></figure><p>The derivation of ‘Sigmoid_derivative’ term is not in context of this post but it has been beautifully explained <a href="https://beckernick.github.io/sigmoid-derivative-neural-network/">here</a>.</p><p>Therefore, our first gradient term simply turns out to be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNuiuYRVJOkVsAbJB1lbpA.png" /><figcaption>Equation-3</figcaption></figure><p>Now, moving further, we calculate our second gradient term i.e. the derivative of loss w.r.t. W₁ in a similar way :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PDmLU_pV9BKTAuDzuX7WA.png" /><figcaption>Equation-4</figcaption></figure><p>You can also refer to this post to know more about these activation functions and their derivatives.</p><p><a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Activation Functions in Neural Networks</a></p><p>So, now that we have calculated the gradients w.r.t. W₁ and W₂, it is time to perform the optimisation steps. We will be using<strong> Gradient Descent Optimizer</strong> which is also called <strong>Vanilla Gradient Descent</strong> to update W₁ and W₂. You might be knowing that gradient descent algorithm has a hyper-parameter named as <strong>learning rate</strong>, which has a great importance in the training process. Tuning of this hyper-parameter is very essential and is done by using validation testing which is not in scope of this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*pt_nys6B52YxdY5W7u3Xzg.png" /><figcaption>Updating Weights of the Neural Network</figcaption></figure><p>Now that we have learnt the mathematical concepts behind a neural network, let us convert these concepts into code and train a neural network on a real-world machine learning problem. We will be using the famous IRIS dataset to train our network and then predict flower categories. You can download the dataset from <a href="https://www.kaggle.com/uciml/iris">here</a>.</p><h3>Implementing A Neural Network in Python</h3><h4>Importing Necessary Libraries</h4><pre>import numpy as np<br>import pandas as pd<br>from sklearn import preprocessing<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.model_selection import train_test_split</pre><h4>Data Loading and Preprocessing</h4><pre>data=pd.read_csv(&#39;IRIS.csv&#39;)<br>X=data.iloc[:,:-1].values<br>Y=data.iloc[:,-1].values<br>StandardScaler=StandardScaler()<br>X=StandardScaler.fit_transform(X)<br>label_encoder=LabelEncoder()<br>Y=label_encoder.fit_transform(Y)<br>Y=Y.reshape(-1,1)<br>enc=preprocessing.OneHotEncoder()<br>enc.fit(Y)<br>onehotlabels=enc.transform(Y).toarray()<br>Y=onehotlabels  </pre><p>After doing aforesaid basic pre-processing on the input data, we move on to create our neural network class which contains the feed forward and back-propagation functions. But first, let us split our data into train and test.</p><pre>X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0)</pre><p>I am also writing code to define functions which can calculate function values and function derivative values. I have written code for 3 activation functions and used only two (Relu and Sigmoid) out of them. However, you can try out various combinations of these activation functions and also incorporate other activation functions in your code.</p><pre>def ReLU(x):<br>   return (abs(x.astype(float))+x.astype(float))/2</pre><pre>def ReLU_derivative(x):<br>   y=x<br>   np.piecewise(y,[ReLU(y)==0,ReLU(y)==y],[0,1])<br>   return y</pre><pre>def tanh(x):<br>   return np.tanh(x.astype(float))</pre><pre>def tanh_derivative(x):<br>   return 1-np.square(tanh(x))</pre><pre>def sigmoid(x):<br>   return 1/(1+np.exp(-x.astype(float)))</pre><pre>def sigmoid_derivative(x):<br>   return x*(1-x)</pre><p>Defining the neural network class :</p><pre>class Neural_Network:<br>   def __init__(self,x,y,h):<br>      self.input=x<br>      self.weights1=np.random.randn(self.input.shape[1],h)<br>      self.weights2=np.random.randn(h,3)<br>      self.y=y<br>      self.output=np.zeros(y.shape)</pre><p>The class ‘Neural_Network’ accepts 3 parameters: x, y and h which are corresponding to X_train, Y_train and number of neurons in the hidden layer. As mentioned earlier, number of neurons in the hidden layer is flexible and therefore we will pass its value along with X_train and Y_train while creating an instance of our class.</p><p>‘weights1’ and ‘weights2’ matrices are initialized from a random distribution and by passing the dimensions required for the respective weight matrices. As previously W₁ and W₂ matrices have been shown along with their dimensions, we pass these dimensions to this random function to generate our initial weights.</p><pre>   def FeedForward(self):<br>      self.layer1=ReLU(np.dot(self.input,self.weights1))<br>      self.output=sigmoid(np.dot(self.layer1,self.weights2))</pre><p>Our first function in the class is ‘FeedForward’ which is the first step in the training process of a neural network. The code follows ‘Equation-1’ and ‘Equation-2’ described earlier.</p><p>Next, we move on to the most essential part, the back-propagation.</p><pre>def BackPropogation(self):<br>      m=len(self.input)<br>      d_weights2=-(1/m)*np.dot(self.layer1.T,(self.y-self.output)       *sigmoid_derivative(self.output))</pre><pre>d_weights1=-(1/m)*np.dot(self.input.T,(np.dot((self.y-    self.output)*sigmoid_derivative(self.output),self.weights2.T)*    ReLU_derivative(self.layer1)))</pre><pre>self.weights2=self.weights2 - lr*d_weights2<br>      self.weights1=self.weights1 - lr*d_weights1</pre><p>The back-propagation step calculates gradients w.r.t. the model parameters while traversing back in the network from output layer to the input layer. This is governed by ‘Equation-3’ and ‘Equation-4’ which we obtained using chain rule. You will observe that both the terms ‘d_weights2’ and ‘d_weights1’ consist of 2 types of operations i.e. dot product and normal multiplication. In NumPy, np.dot(X,Y) represents matrix multiplication between X and Y whereas np.multiply(X,Y) or simply X*Y represents element wise multiplication between X and Y. To get more insights on how this piece of code is working, I will give you a small task which i myself did when i first implemented this from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktgUTrYq6TMUQyPvhnGbWw.png" /><figcaption>Neural Network Architecture</figcaption></figure><p>If you look at the hidden layer, <strong>for each neuron</strong> (blue), there are 3 connections entering the neuron. Each such connection is emerging from a distinct neuron in the input layer. The basics of neural network suggest that there is a linear relation between the blue neuron of hidden layer and the set of neurons from which it is receiving information through the connections. This relation can be represented in the form of an equation. mentioned below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*zlzo1eAkduBcOT-sQpyQZw.png" /></figure><p>Now, extending this equation to each and every neuron(blue) of the hidden layer, we obtain 4 such equations as we have 4 neurons in the hidden layer. The work that has been done till now, only represents 1 training example/row. In order to send our training data all at once into the feed forward function, we will have to use matrices to perform this operation. But the task really is to verify with full confidence that solving(on paper) the above piece of code which includes dot products and element-wise multiplications matches these 4 linear equations we discussed. But this time we will be applying these equations on all the rows of our training data simultaneously.</p><p>I hope you enjoyed getting your hands dirty in solving matrices and equations but trust me it is worth spending time on.</p><p>Moving further, we define a function which will predict the output class at run time after our model is trained.</p><pre>def predict(self,X):<br>   self.layert_1=ReLU(np.dot(X,self.weights1))<br>   return sigmoid(np.dot(self.layert_1,self.weights2))</pre><p>This is the last function in the ‘Neural_Network’ class and the ‘predict’ function does nothing but normal feed forward using the final optimized weights.</p><p>Now that we have defined our class, it is time to actually use it.</p><pre>#----Defining parameters and instantiating Neural_Network class----#</pre><pre>epochs=10000 #Number of training iterations<br>lr=0.5 # learning rate used in Gradient Descent<br>n=len(X_test)<br>m=len(X)</pre><pre>nn1=Neural_Network(X_train,Y_train)<br>#creating an object of Neural_Network class</pre><pre>#----------------------Training Starts-----------------------------#<br>for i in range(epochs):<br>   nn1.FeedForward()<br>   y_predict_train=enc.inverse_transform(nn1.output.round())<br>   y_predict_test=enc.inverse_transform(nn1.predict(X_test).round())<br>   y_train=enc.inverse_transform(Y_train)<br>   y_test=enc.inverse_transform(Y_test)<br>   train_accuracy=(m-np.count_nonzero(y_train-y_predict_train))/m<br>   test_accuracy=(n-np.count_nonzero(y_test-y_predict_test))/n<br>   nn1.BackPropogation()<br>   cost=(1/m)*np.sum(np.square(nn1.y-nn1.output))<br>   print(&quot;Epoch {}/{}  ==============================================================:- &quot;.format(i+1,epochs))</pre><pre>#----------------Displaying Final Metrics--------------------------#<br>print(&quot;MSE_Cost: {} , Train_Accuracy: {} , Test_Accuracy: {} &quot;.format(cost,train_accuracy,test_accuracy))</pre><p>After training for 10000 epochs, the following is the result:</p><p><strong>Train accuracy : 0.97777</strong></p><p><strong>Test accuracy : 0.9</strong></p><p>The results look amazing as compared to other machine learning models when applied to the same problem at hand. This network can be extended to a 3- layer network which will have 2 hidden layers using same concepts. You can also try different optimizers like AdaGrad, Adam etc.</p><p>You can access my additional work on the ‘Adult Income Prediction’ dataset which uses a similar neural network in my GitHub repository, the link to which is provided below:</p><p><a href="https://github.com/Ravsehajsinghpuri/Neural_Network_from_scratch">Ravsehajsinghpuri/Neural_Network_from_scratch</a></p><h3>Conclusion</h3><p>In this post, we started learning the basic architecture of a neural network and went further into the components of a neural network architecture. We also witnessed the mathematics behind the working of the same and got a detailed explanation of application of chain rule and basic calculus in developing equations for back-propagation which is a major part of the training process. Finally, we converted our mathematical concepts and equations into code and implemented a full fledged neural network on the IRIS dataset.</p><p>Thanks a lot for reading through the article. I hope you understood each and every aspect of it. Feel free to ask any question in the responses section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf7d52d91e00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-ultimate-beginners-guide-to-implement-a-neural-network-from-scratch-cf7d52d91e00">The Ultimate Beginner’s Guide To Implement A Neural Network From Scratch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Medical Prognostic Models For Patients With Primary Biliary Cirrhosis]]></title>
            <link>https://medium.com/data-science/building-medical-prognostic-models-for-patients-with-primary-biliary-cirrhosis-71bd4ceb7db1?source=rss-751694db0065------2</link>
            <guid isPermaLink="false">https://medium.com/p/71bd4ceb7db1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[medicine]]></category>
            <category><![CDATA[primary-biliary-cirrhosis]]></category>
            <dc:creator><![CDATA[Ravsehaj Singh Puri]]></dc:creator>
            <pubDate>Sat, 09 May 2020 19:01:01 GMT</pubDate>
            <atom:updated>2020-05-12T04:13:18.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to apply Machine Learning techniques to medical datasets and establishing metrics to evaluate them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Lsmi-ER83tu66lE" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Abstract</h3><p>Medical Prognosis is emerging as a field with direct application of Artificial Intelligence. This post discusses the idea of AI for medical prognosis along with a detailed tutorial for building a prognostic model. Prognosis is a medical term for predicting the likely or expected development of a disease, including whether the signs and symptoms will improve or worsen or remain stable over time.</p><p>In this post, I’ll be explaining my work on Building a Risk model for patients with primary biliary cirrhosis(PBC). We’ll be using the PBC dataset which is maintained <a href="https://www.mayo.edu/research/documents/pbchtml/doc-10027635">here</a>.</p><h3>How Prognostic Models work?</h3><p>Prognostic models work on a basic principle, the probability of survival of a patient past a given time, given his patient profile. Prognostic models can be broadly classified into two categories:</p><ol><li>Built at patient population level</li><li>Built at individual patient level</li></ol><p>Here, We will be working on the individual patient level and will be using two separate approaches and then comparing them. The two approaches are mentioned below:</p><ol><li>Linear proportionality approach which uses the Cox Proportional hazard model.</li><li>Tree based approach which uses the Random Survival Forest model.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vpEPymzjqaZ9SOgA" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building the Cox Proportional Hazard Model</h3><h4>Importing necessary libraries and packages</h4><pre>import sklearn<br>import os<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from lifelines import CoxPHFitter<br>from lifelines.utils import concordance_index as cindex<br>from sklearn.model_selection import train_test_split</pre><p>We are using the <strong>lifelines library</strong>, which is an open-source library for importing models and metrics used in survival models.</p><h4>Loading our Dataset and performing data preprocessing</h4><pre>df = pd.read_csv(&#39;pbc.csv&#39;)<br>df.head()<br>df = df.drop(&#39;id&#39;, axis=1)<br>df = df[df.status != 1]<br>df.loc[:, &#39;status&#39;] = df.status / 2.0<br>df.loc[:, &#39;time&#39;] = df.time / 365.0<br>df.loc[:, &#39;trt&#39;] = df.trt - 1<br>df.loc[:, &#39;sex&#39;] = df.sex.map({&#39;f&#39;:0.0, &#39;m&#39;:1.0})<br>df = df.dropna(axis=0)</pre><p>Let&#39;s have a look at our data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZrOiK9Yz6B_UsxOfxjlzA.png" /></figure><p>The time is in days, so we convert it to years and drop the ‘id’ column as it is not required. We transform and scale the ‘status’ and ‘trt’ columns along with label encoding the ‘sex’ column.</p><pre>np.random.seed(0)<br>df_dev, df_test = train_test_split(df, test_size = 0.2)<br>df_train, df_val = train_test_split(df_dev, test_size = 0.25)</pre><p>Before proceeding to modeling, let’s normalize the continuous covariates to make sure they’re on the same scale. To prevent Data Leakage, we should normalize the test data using statistics calculated from the train data.</p><pre>continuous_columns = [&#39;age&#39;, &#39;bili&#39;, &#39;chol&#39;, &#39;albumin&#39;, &#39;copper&#39;, &#39;alk.phos&#39;, &#39;ast&#39;, &#39;trig&#39;, &#39;platelet&#39;, &#39;protime&#39;]<br>mean = df_train.loc[:, continuous_columns].mean()<br>std = df_train.loc[:, continuous_columns].std()<br>df_train.loc[:, continuous_columns] = (df_train.loc[:, continuous_columns] - mean) / std<br>df_val.loc[:, continuous_columns] = (df_val.loc[:, continuous_columns] - mean) / std<br>df_test.loc[:, continuous_columns] = (df_test.loc[:, continuous_columns] - mean) / std</pre><p>Cox proportional hazard model is based on the following mathematical equation:</p><p><strong>𝜆(𝑡,𝑥)=𝜆₀(𝑡)exp(𝛉ᵀXᵢ)</strong></p><p>The 𝜆₀ term is a baseline hazard and incorporates the risk over time, and the second term in the equation incorporates the risk due to the individual’s covariates/features. After fitting the model, we can rank individuals using the person-dependent risk term i.e. exp(𝛉ᵀXᵢ)</p><p>Lets, convert our categorical columns to encodings to use them in the linear model. We have 2 columns, ‘edema’ and ‘stage’ which are categorical in nature and thus we transform them.</p><pre>columns=[&#39;edema&#39;,&#39;stage&#39;]<br>one_hot_train=pd.get_dummies(df_train, columns=columns, drop_first=True)<br>one_hot_test=pd.get_dummies(df_test, columns=columns, drop_first=True)<br>one_hot_val=pd.get_dummies(df_val, columns=columns, drop_first=True)</pre><p>Now, after these transformations and preprocessing steps, our data looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_jxkriheQT0k0wnkzyvcQ.png" /></figure><h4>Training our Cox Proportional Hazard Model</h4><p>Now, we are all set to fit our data to the Cox Proportional hazard model and we’ll start by constructing a CoxPHFitter object from the lifelines library.</p><pre>cph = CoxPHFitter()<br>cph.fit(one_hot_train, duration_col = &#39;time&#39;, event_col = &#39;status&#39;, step_size=0.1)</pre><pre>cph.print_summary()</pre><p>The Trained CoxPH model would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXUPLQNTTRCw47pBzbzqig.png" /></figure><p>Let us start analysing the table above which describes our trained model, providing all the coefficients which were optimised according to the training data.</p><p>Here, we can see that features with negative coefficients are beneficial i.e. they contribute towards lowering the risk factor/output value and the ones with positive coefficients contribute towards increasing the risk factor/output value. We can infer from the above table that <strong>‘trt’</strong>, ‘<strong>ascites’</strong>, <strong>‘spiders’</strong>, <strong>‘albumin’</strong> and <strong>‘alk.phos’</strong> have negative coefficients and therefore, a high values of these features will reduce the risk factor proportionally.</p><p>We can compare the predicted survival curves for treatment variable</p><ul><li>The y-axis is the survival rate</li><li>The x-axis is time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*GXznZJxiFzlxCr6uDf3z3Q.jpeg" /><figcaption>Predicted Survival curves for treatment variable</figcaption></figure><p>We can clearly see that the survival curve for ‘trt’=0 is lower as compared to that for ‘trt’=1. This is due to the fact that ‘trt’ variable or treatment feature is a negative covariate i.e. it has a negative coefficient in the fitted model and therefore a higher value of the variable will yield to lower risk score.</p><p>Next, We compare the predicted survival curves for ‘edema_1.0’ variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*7KyTzFwRtkYV5sZuxOXTOg.jpeg" /><figcaption>Predicted Survival curves for edema_1.0 variable</figcaption></figure><p>Here, it is clearly noticeable that the two curves are separated by a large value and curve for ‘edema_1.0’=1 is lower as compared to that for ‘edema_1.0’=0. This is due to the fact that ‘edema_1’ variable is a positive covariate i.e. it has a positive coefficient in the fitted model and therefore a higher value of the variable will yield to a higher risk score. The large gap between the two curves is due to the relatively high value of the coefficient corresponding to ‘edema_1.0’.</p><h4>Hazard Ratio</h4><p>Hazard Ratio between two patients is the likelihood of one patient being more at risk than the other. It can be mathematically formulated as:</p><p><strong>𝜆₁(𝑡)/𝜆₂(𝑡)=𝑒xp(𝜃(𝑋₁−𝑋₂)ᵀ</strong></p><p>where, 𝜆₁(𝑡)=𝜆₀(𝑡)𝑒xp(𝜃𝑋₁ᵀ)</p><p>and, 𝜆₂(𝑡)=𝜆₀(𝑡)𝑒xp(𝜃𝑋₂ᵀ)</p><p>Now, we’ll calculate hazard ratio using any 2 patients from our dataset.</p><pre>i = 1<br>patient_1 = one_hot_train.iloc[i, :].drop([&#39;time&#39;, &#39;status&#39;]).values<br>j = 5<br>patient_5 = one_hot_train.iloc[j, :].drop([&#39;time&#39;, &#39;status&#39;]).values<br>cox_params=cph.params_.values<br>hr = np.exp(np.dot(cox_params,(patient_1-patient_5)))<br>print(hr)</pre><p>After running the above piece of code, we get the hazard ratio between patient 1 and patient 5 as <strong>15.029017732492221 </strong>. This means that patient 1 is at a higher risk as compared to patient 5 as the hazard ratio between the two is greater than 1. Similarly, we can calculate hazard ratio between any two patients and compare their risk scores.</p><h4>Measuring the performance of our model</h4><p>Measuring the performance of a trained model is an integral part of a machine learning pipeline and here we’ll be using the <strong>Harrell’s C-index</strong> as a measure of performance of our model. C-index or Concordant index in the survival context is the probability that, given a randomly selected pair of individuals, the one who died sooner has a higher risk score. Here we’ll be writing our own version of C-index in the next few lines of code. But before stepping into code, let me introduce an important concept which is essential to understand prognostic models i.e.<strong> Censoring</strong>. Censoring is a condition when the event or, death in our case, does not occur during the course of study which can be due to any of the following 2 reasons:</p><ol><li>Patient opts out from the study before witnessing an event/death</li><li>The study ends before the patient witnesses an event/death</li></ol><p>So, if a patient’s profile is censored, then it is represented in the ‘Event’ column of the dataset with value ‘0’. If it is uncensored, then it is represented with a value of ‘1’.</p><p>Harrell’s C-index is mathematically formulated as:</p><p>Harrell’s C-index =</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*2o5N8pslLriaAwqx7lWf7w.png" /></figure><p>where,</p><p><strong>PermissiblePairs</strong> = Total number of patient pairs for which any one of the following conditions holds true: for (patient_i,patient_j) pair,</p><ol><li>Both the patients have uncensored data</li><li>If any one patient’s data in censored and Time[censored]&gt;Time[uncensored]</li></ol><p><strong>ConcordantPairs</strong>= Total number of patient pairs for which both the following conditions hold true: for(patient_i,patient_j) pair,</p><ol><li>Patient Pair is permissible</li><li>if RiskScore[patient_i]&gt;RiskScore[patient_j] then,</li></ol><p>Time[patient_i]&lt;Time[patient_j] or vice-versa</p><p><strong>RiskTies</strong>=Total number of patient pairs for which the following conditions hold true: for (patient_i,patient_j) pair,</p><ol><li>Patient Pair is permissible</li><li>RiskScore[patient_i]=RiskScore[patient_j]</li></ol><pre>event=one_hot_train[&#39;status&#39;].values<br>y_true=one_hot_train[&#39;time&#39;].values<br>scores=scores.values</pre><pre>n = len(y_true)<br>assert (len(scores) == n and len(event) == n)<br>concordant = 0.0<br>permissible = 0.0<br>ties = 0.0<br>result = 0.0<br>   <br>for i in range(n):<br>    for j in range(i+1, n):<br>       if event[i]==1 or event[j]==1:<br>                pass<br>          if event[i]==1 and event[j]==1:<br>              permissible+=1<br>                    <br>              if scores[i]==scores[j]:<br>                   ties+=1<br>                    <br>              elif (y_true[i]&gt;y_true[j] and scores[i]&lt;scores[j]):<br>                        concordant+=1<br>              elif (y_true[i]&lt;y_true[j] and scores[i]&gt;scores[j]):<br>                        concordant+=1</pre><pre>           elif (event[i]!=event[j]):<br>                   <br>                    if event[j] == 0:<br>                        censored = j<br>                        uncensored = i<br>                    <br>                    if event[i] == 0:<br>                        censored = i<br>                        uncensored = j<br>                <br>                    if y_true[censored]&gt;=y_true[uncensored]:<br>                        permissible+=1<br>                        <br>                        if scores[i]==scores[j]:<br>                            ties+=1<br>                            <br>                        if scores[censored]&lt;scores[uncensored]:<br>                            concordant+=1<br>    <br>c-index = (concordant+ties*0.5)/permissible</pre><pre>print(c-index)</pre><p>In the above piece of code, we have computed the Harrell’s C-index on the training data after calculating the number of permissible, concordant and risk ties pairs. Harrell’s C-index corresponding to our training data is <strong>0.8265139116202946</strong></p><p>Similarly, we can compute Harrell’s C-index for Validation and Testing data.</p><pre><strong>Val: 0.8544776119402985<br>Test: 0.8478543563068921</strong></pre><p>We get an appreciable C-index which tells us that our model is performing reasonably good but we can improve the performance of our prognostic model by using a tree based approach which I’ll be discussing in the next section.</p><h3>Building the Random Survival Forest model</h3><p>Random Survival Forest model is a tree based machine learning approach which constructs a number of estimators/trees and takes the decision on the basis of vote. This tree based approach has an advantage over the linear models like the Cox proportional hazard model which we have already discussed. The Cox proportional hazard model assumes a linear hazard function which makes it impossible to represent non-linear hazard functions which is quite prevalent in the dataset in question. So, let us start building our model from scratch.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSXy6TlzGRqWfTGsLxf%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSXy6TlzGRqWfTGsLxf%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3898f196e6f743390544f539811e8d0/href">https://medium.com/media/a3898f196e6f743390544f539811e8d0/href</a></iframe><p>In a population, different patients may have different Hazard functions. So, to optimise our prediction, The Random Survival Forest model first predicts the hazard function for that patient by running through the tree and then calculates the Risk Score using that hazard function.</p><h4>Importing the necessary libraries</h4><p>We’ll be using a pre-installed library which is in R for building our Random Survival Forest model. You can find this library <a href="https://github.com/Ravsehajsinghpuri/Medical_prognostic_models">here</a> and download it on your local machine to use it in your project. To call R function from Python, we’ll use the ‘r2py’ package. Let’s start importing them step by step before building our actual model.</p><pre>%load_ext rpy2.ipython<br>%R require(ggplot2)</pre><pre>from rpy2.robjects.packages import importr<br>base = importr(&#39;base&#39;)<br>utils = importr(&#39;utils&#39;)<br>import rpy2.robjects.packages as rpackages </pre><pre>forest = rpackages.importr(&#39;randomForestSRC&#39;, lib_loc=&#39;R&#39;)</pre><pre>from rpy2 import robjects as ro<br>R = ro.r</pre><pre>from rpy2.robjects import pandas2ri<br>pandas2ri.activate()</pre><p>In a tree based model, encoding of variables is not required as trees work well with raw categorical data. So we straightaway start training our model.</p><h4>Training and evaluating model</h4><pre>model = forest.rfsrc(ro.Formula(&#39;Surv(time, status) ~ .&#39;), data=df_train, ntree=300, nodedepth=5, seed=-1)</pre><p>Let us look at our trained model and its parameters after fitting our data.</p><pre>print(model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*jdxFGnQsD4Ebd4dwgxyFXg.png" /><figcaption>Model description</figcaption></figure><p>Let us now evaluate the performance of our Random Survival Forest model by calculating Harrell’s C-index. The same code mentioned previously in this post can be used to calculate Harrell’s C-index from the scores predicted by RSF model, which are calculated using the code mentioned below.</p><pre>result = R.predict(model, newdata=df_train)<br>scores = np.array(result.rx(&#39;predicted&#39;)[0])</pre><p>Harrell’s C-index corresponding to training data comes out to be <strong>0.8769230769230769 </strong>which is a great score and our prognostic model’s performance has improved. Let us check how it is performing on the validation and testing data.</p><pre>result = R.predict(model, newdata=df_val)<br>scores_val = np.array(result.rx(&#39;predicted&#39;)[0])<br>result = R.predict(model, newdata=df_test)<br>scores_test = np.array(result.rx(&#39;predicted&#39;)[0])</pre><p>For calculating C-index for test and validation data, use ‘scores_val’ and scores_test’ to compute Harrell’s C-index. After running the above-mentioned steps, we get the following scores/c-index:</p><pre><strong>Survival Forest Validation Score: 0.8769230769230769<br>Survival Forest Testing Score: 0.8621586475942783</strong></pre><p>So, our model performs great on both validation and testing data and it outperforms the Cox Proportional Hazard model.</p><h4>Digging deeper</h4><p>Let us dig deeper into our RSF model we just trained and evaluated so that we can get some insights about the features our model is giving priority, in its prediction of Risk Score. For this, we’ll be using the in-built function which comes with Random Survival models called ‘Variable Importance” or VIMP.</p><pre>VIMPS = np.array(forest.vimp(model).rx(&#39;importance&#39;)[0])</pre><pre>y = np.arange(len(VIMPS))<br>plt.barh(y, np.abs(VIMPS))<br>plt.yticks(y, df_train.drop([&#39;time&#39;, &#39;status&#39;], axis=1).columns)<br>plt.title(&quot;Variable Importance (absolute value)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*OJ-dyYttHxlB5sST-4JbyQ.jpeg" /><figcaption>VIMP Bar Chart</figcaption></figure><p>Seeing the chart above, we can infer that ‘bili’ variable has the most importance in predicting the risk score and it is followed by ‘edema’ and ‘protime’. If we compare the values in the chart above with the coefficients in the Cox model, we will note that ‘edema’ is an important feature in both the models but ‘bili’ seems to be important only in Random Survival Forest.</p><h3>Conclusion</h3><p>In this post, We witnessed an overview of medical prognostic models followed by a detailed illustration of two machine learning approaches to build a Risk Model. Finally, we evaluated both the models using visual illustrations and figures and compared their performance using Harrell’s C-index.</p><p>To end this post, I’ll share my thoughts on this field of study by starting with a famous quote by an eminent personality, Andrew Ng</p><blockquote>It is difficult to think of a major industry that AI will not transform. This includes healthcare, education, transportation, retail, communications, and agriculture. There are surprisingly clear paths for AI to make a big difference in all of these industries.</blockquote><p>The scope of Artificial Intelligence in the field of medicine and healthcare is immense. With the help of Prognostic models, Health Practitioners can plan future treatment of a patient by analysing the Risk Scores calculated over time and thus improve a patient’s health by a large amount. The research in this field is moving at a very fast pace and if we plan to implement these approaches in real life, we will soon witness leading hospitals and medical clinics efficiently using such models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71bd4ceb7db1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-medical-prognostic-models-for-patients-with-primary-biliary-cirrhosis-71bd4ceb7db1">Building Medical Prognostic Models For Patients With Primary Biliary Cirrhosis</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>