<?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 Shashi Gharti on Medium]]></title>
        <description><![CDATA[Stories by Shashi Gharti on Medium]]></description>
        <link>https://medium.com/@shashi.gharti?source=rss-388b02fe73dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*orMQVh-JHeK24Bdwvti4jw.jpeg</url>
            <title>Stories by Shashi Gharti on Medium</title>
            <link>https://medium.com/@shashi.gharti?source=rss-388b02fe73dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:50:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashi.gharti/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 Loss Function and Error in Neural Network]]></title>
            <link>https://medium.com/udacity-pytorch-challengers/understanding-loss-function-and-error-in-neural-network-676a81cc776c?source=rss-388b02fe73dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/676a81cc776c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Shashi Gharti]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 15:51:15 GMT</pubDate>
            <atom:updated>2019-01-07T16:07:04.188Z</atom:updated>
            <content:encoded><![CDATA[<p>Loss function helps us to quantify how good/bad our current model is in predicting some value which it is trained to predict. This article aims you to explain the role of loss function in neural network.</p><p>I assume that you have basic understanding of Neural Networks and Pytorch library. Throughout this tutorial, I will use google <a href="https://colab.research.google.com/">colab</a> to write and test the code. I will be using Dog vs Cat dataset from kaggle. You can download it from <a href="https://www.kaggle.com/c/dogs-vs-cats">here</a>.</p><h3>Cat Images from kaggle dataset</h3><p>The dataset that I downloaded looks like this. I will be using cat images only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*7BZikVANdBxF7-npBxA-qw.png" /></figure><h3><strong>Let’s Get Started!</strong></h3><p>I will start my explanation with an example of a simple neural network as shown in Figure 1 where x1 and x2 are inputs to the function f(x). The output y_hat is the weighted sum of inputs passed through the activation function. I have omitted bias for the sake of simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*VU4cY78JrRTaoz-NTTYlSA.jpeg" /><figcaption>Single Layer Neural Network</figcaption></figure><p><strong>What is a loss function?</strong></p><p>Let’s prepare a training dataset of cats along with true labels for each input image and pass it to our model.</p><pre>train_transforms =transforms.Compose([<br>                         transforms.RandomResizedCrop(224),<br>                         transforms.ToTensor(),<br>                         transforms.Normalize([0.485, 0.456, .406],<br>                                              [0.229, 0.224,.225])])<br>train_data = datasets.ImageFolder(data_dir + &#39;/train&#39;, transform=train_transforms)<br>train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)</pre><p>Following is Densenet, a pretrained model that we will use for this tutorial.</p><pre>model = models.densenet121(pretrained=True)<br>classifier = nn.Sequential(nn.Linear(2048, 512),   <br>                           nn.ReLU(),<br>                           nn.Dropout(p=0.2),<br>                           nn.Linear(512,2),<br>                           nn.LogSoftmax(dim=1)<br>)</pre><p>All the training images will be passed to this model in batches:</p><pre>for epoch in range(epochs):<br>  for inputs, labels in train_loader:<br>    logps = model.forward(inputs)</pre><p>For each batch, we compare the output from the model (predicted values) with the actual labels. To explain in simple words, we check if the image predicted as cat by the model is actually a cat or not. If all the predictions are correct, then our model is good. But if model identifies dog as a cat, then we have an error. This is what the loss function calculates.</p><p>Loss function takes in the predicted score coming out from our model together with true target or labels, compares it and gives us some quantitative value of how good or bad those predictions are for the training images.</p><pre>criterion = nn.NLLLoss()</pre><pre>logps = model.forward(inputs)<br>batch_loss = criterion(logps, labels)</pre><p>There are different types of <a href="https://isaacchanghau.github.io/post/loss_functions/">loss functions</a> that we can use. Choosing the optimal loss function depends on various factors and the type of problem we are trying to solve such as regression or classification. In this tutorial, we are using <a href="https://pytorch.org/docs/stable/nn.html#nllloss">NLLLoss</a> function.</p><h4>How do we minimize this error?</h4><p>Once we calculate the loss, our next step is to decide whether to continue training or not . The decision is based on the loss value. If the loss value is very high, then we need to update the weight parameters of the model and repeat the same process. If the loss is low and satisfies our need then we stop the training process.</p><p>Based on the calculated error, the optimization functions are used to optimize the weights using <a href="https://en.wikipedia.org/wiki/Gradient_descent">gradient descent</a> and <a href="https://en.wikipedia.org/wiki/Backpropagation">back propagation</a>.</p><pre>#compute the  gradients<br>loss.backward()</pre><pre>#update the parameters<br>optimizer.step()</pre><p>In this way, we modify the weight parameters of the model and repeat the same process until the loss is reduced and it is minimal.</p><h3>Output</h3><p>Yay! We have completed the training part for our model. The calculated loss per batch looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*6ouYVyCoNQ9y1d8DTpDs3A.png" /><figcaption>Loss calculation per batch</figcaption></figure><p>The working code for this tutorial can be downloaded from <a href="https://colab.research.google.com/drive/1I1J0Uti2Xo1ubDXg1nldvkB_BWol1hRh#scrollTo=nvd3WI4s6n3a">here</a>.</p><h3>Summary</h3><p>The main objective of this tutorial is to give detailed explanation on error calculation and loss function rather than how to train a model. So we examined and observed the error calculation and optimization step in detail, while training our model. However, this tutorial doesn’t explain all the <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html">steps</a> involved in training process of neural network. I hope this tutorial adds some value to help you understand the importance and role of loss function in neural network.</p><p><strong>References</strong></p><p><a href="https://isaacchanghau.github.io/post/loss_functions/">https://isaacchanghau.github.io/post/loss_functions/</a><br><a href="https://seba-1511.github.io/tutorials/beginner/blitz/neural_networks_tutorial.html">https://seba-1511.github.io/tutorials/beginner/blitz/neural_networks_tutorial.html</a><br><a href="https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0</a><br><a href="https://www.youtube.com/watch?v=h7iBpEHGVNc">https://www.youtube.com/watch?v=h7iBpEHGVNc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=676a81cc776c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/udacity-pytorch-challengers/understanding-loss-function-and-error-in-neural-network-676a81cc776c">Understanding Loss Function and Error in Neural Network</a> was originally published in <a href="https://medium.com/udacity-pytorch-challengers">Udacity PyTorch Challengers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Neural Network using TensorFlow]]></title>
            <link>https://medium.com/ub-women-data-scholars/easy-steps-to-build-a-simple-neural-network-using-tensorflow-55db89197761?source=rss-388b02fe73dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/55db89197761</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[women-who-code]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shashi Gharti]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 17:30:53 GMT</pubDate>
            <atom:updated>2018-07-17T18:41:05.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*yfUivnPIm4HV-qnyHYehzg.png" /></figure><p>TensorFlow is an open source, deep learning library initially developed by Google Brain Team. It was made publicly available on November 9, 2015, and is actively maintained by Google. TensorFlow has various applications and it is widely being used for deep learning. Real-world usage of TensorFlow is in image recognition, sentiment analysis, speech recognition, e-commerce application and many more.</p><p>I will show you how to develop a simple machine learning model to detect malignant and benign breast cancer using freely available data from <a href="https://www.kaggle.com/">Kaggle</a>.</p><p><strong>Prerequisites to get started:</strong></p><ol><li>Download the <a href="https://www.kaggle.com/uciml/breast-cancer-wisconsin-data/version/2#">data</a> from Kaggle.</li><li><a href="https://colab.research.google.com/">Google Collab cloud platform</a> : It a cloud service provided by google. We can use it to develop and test our AI models using GPU accelerators for free. We don’t have to set up our local machine to get started, easy !!.</li><li>Python 3 , Numpy, Tensorflow and Keras</li></ol><p>In Google Collab, create a new python notebook. <strong>Go to File-&gt;New Python 3 notebook</strong> as shown in the image below. A new notebook will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*tWE_n2-qQq-sgUQDgl7f4w.png" /></figure><p>Change runtime to use GPU accelerator in order to speed up the processing time. To set GPU go to <strong>Runtime-&gt;Change Run Time -&gt; Hardware Acceleration -&gt; GPU</strong>. Now you are ready to code!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*s4qtc3QvZFE2ZJ8B8JXDBw.png" /></figure><p>To use TensorFlow with GPU run the following code:</p><pre>import tensorflow as tf</pre><pre>device_name = tf.test.gpu_device_name()<br>if device_name != ‘/device:GPU:0’:<br>raise SystemError(‘GPU device not found’)<br>print(‘Found GPU at: {}’.format(device_name))</pre><p><a href="https://colab.research.google.com/"><em>https://colab.research.google.com</em></a></p><p>Upload the data using following code:</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>import io</pre><pre>from google.colab import files<br>file_uploaded = files.upload()</pre><p>Upload the file that you downloaded from Kaggle as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8uhZR6VQp5LOzvGVJ9UA0Q.png" /></figure><p>Read the data from CSV file and split it to X and Y variables:</p><pre>import pandas as pd<br>import io<br>import keras<br>from sklearn.model_selection import train_test_split</pre><pre>dataset = pd.read_csv(io.StringIO(file_uploaded[&#39;data.csv&#39;].decode(&#39;utf-8&#39;)))</pre><pre># split into input (X) and output (Y) variables<br>dataset[&#39;diagnosis&#39;] = dataset[&#39;diagnosis&#39;].map({&#39;B&#39;: 1, &#39;M&#39;: 0})<br>X = dataset.iloc[:, 2:32].values<br>y = dataset.iloc[:, 1].values<br>y = keras.utils.to_categorical(y, num_classes = 2)</pre><p>Now let’s split the data into train and test data. We will use sklearn library to split the data.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y,test_size = 0.2)</pre><pre>#test the shape of the train and test <br>print(‘x_train shape:’, X_test.shape)<br>print(X_train.shape[0], ‘train samples’)<br>print(X_test.shape[0], ‘test samples’)</pre><p>Next setup is to build a 2 layered CNN model. In sequential model, we can stack up the hidden layers as shown in the code below. Both layers have 32 neurons each. LeakyReLU is an activation function and is very popular in CNN among other activation functions as it avoids vanishing gradient problem. We use sigmoid activation for the output layer.</p><pre>model = Sequential()<br>dim = X_train.shape[1]</pre><pre>#Layer 1<br>model.add(Dense(32, input_dim = dim))<br>model.add(LeakyReLU())<br>model.add(Dropout(0.25))</pre><pre>#Layer 2<br>model.add(Dense(32))<br>model.add(LeakyReLU())<br>model.add(Dropout(0.25))</pre><pre>#output layer<br>model.add(Dense(2))<br>model.add(Activation(‘sigmoid’))</pre><pre>model.compile(optimizer = ’rmsprop’,loss = ’binary_crossentropy’,<br>metrics = [‘accuracy’])</pre><p>Let’s train our model. We have set batch size to 32 which means 32 rows will be processed at once. The whole training process will have 5 iterations as we have set epochs to 5.</p><pre>#Fit/Train the model<br>bsize = 32  <br>model.fit(X_train, y_train, batch_size = bsize, epochs = 5, verbose = 1,validation_data = (X_test, y_test))</pre><h4>Output</h4><p>Finally!! we trained a model and you can see the results. In each epoch, the accuracy is increased and the final accuracy is 63% which is not bad :). This means our trained model can now detect a malignant or benign breast cancer with 63% accuracy. You can download the running version of the code from <a href="https://colab.research.google.com/drive/1TiCQRC1MpHoGynGAvj-3-sNmYE7Fsv_q">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whvPDoOyoLMq_j_NrudeuA.png" /></figure><h3>Summary</h3><p>In this article, we learned how to quickly develop our own Neural Network model using open source data from Kaggle, TensorFlow, Keras and Google Collab cloud service. This tutorial is a simple example of how quickly we can develop a Neural Network model. I hope this tutorial will be helpful for starters who want to learn machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55db89197761" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ub-women-data-scholars/easy-steps-to-build-a-simple-neural-network-using-tensorflow-55db89197761">Building a Simple Neural Network using TensorFlow</a> was originally published in <a href="https://medium.com/ub-women-data-scholars">Women Data Greenhorns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>