<?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 Shreya Goyal on Medium]]></title>
        <description><![CDATA[Stories by Shreya Goyal on Medium]]></description>
        <link>https://medium.com/@shreya-goyal?source=rss-bb949d75e9ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ev0PBc6_ZMgxMvVf_4rOcQ.jpeg</url>
            <title>Stories by Shreya Goyal on Medium</title>
            <link>https://medium.com/@shreya-goyal?source=rss-bb949d75e9ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:20:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shreya-goyal/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[Finding Optimal epochs using K-Fold for Transformer Models.]]></title>
            <link>https://medium.com/geekculture/finding-optimal-epochs-using-k-fold-for-transformer-models-615a002195cb?source=rss-bb949d75e9ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/615a002195cb</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[k-fold-cross-validation]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Shreya Goyal]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 12:07:20 GMT</pubDate>
            <atom:updated>2023-02-10T14:49:01.715Z</atom:updated>
            <content:encoded><![CDATA[<h4>Usually fine-tuning a pre-trained Transformer model on some downstream task such as Text Classification may result in overfitting if the dataset is small, and thus we could leverage the K-fold technique in such scenarios to prevent the overtraining and better generalization of the model.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2IiOy2-CH0bOxM7w" /><figcaption>Photo by <a href="https://unsplash.com/@eklektikum?utm_source=medium&amp;utm_medium=referral">Iva Rajović</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Understanding K-Fold:</strong></p><p>As the name suggests, we are simply splitting our data into equal K partitions, and using a new partition each time as a Validation/Test set while Training the data on the rest of the K-1 partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*Cr6pRMlmUrbjFoyh33MldA.png" /><figcaption>Figure1: K-Folds for Training, Image by author</figcaption></figure><p>I am using the TensorFlow framework to illustrate it in code but the same concept could be extended to PyTorch as well.</p><p>We will be using the <a href="https://huggingface.co/docs/transformers/training"><em>Huggingface</em></a> library for the pre-trained Transformer model.</p><p><strong>Step 1:</strong> Splitting the data into required K-folds, eg., 5–7 folds. Don’t use a large number for K as it will increase the Training time.</p><pre>from sklearn.model_selection import StratifiedKFold<br><br>kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=20)<br><br>for train_indices, valid_indices in kfold.split(df, df[&#39;label&#39;]):<br>    train_df = df.iloc[train_indices]<br>    valid_df = df.iloc[valid_indices]</pre><blockquote>Using a Stratified fold makes sure the labels are in the same ratio in the K-folds as in the original data and there is equal distribution of all classes in the folds.</blockquote><p><strong>Step 2</strong>: Tokenize the Training data and train the model on each Split.</p><pre>from transformers import AutoTokenizer, DataCollatorWithPadding, <br>                         TFAutoModelForSequenceClassification<br>from tensorflow.keras import optimizers<br>from tensorflow.keras import metrics<br>from tensorflow.keras import losses<br>from datasets import Dataset<br><br><br>def tokenize(x, tokenizer):<br>    return tokenizer(x[&#39;inputs&#39;], padding=True, truncation=True)<br><br>def create_dataset(df):<br>    x, y  = df[&#39;text&#39;], df[&#39;label&#39;]<br>    data_dict = {&quot;inputs&quot;: x, &quot;labels&quot;: y}<br>    <br>    tokenizer = AutoTokenizer.from_pretrained(&#39;bert-base-uncased&#39;) <br>    #you can use any pretrained model as needed<br>    <br>    data_ds = Dataset.from_dict(data_dict)<br>    tokenized_data = data_ds.map(lambda x:tokenize(x, tokenizer),batched=True)<br>    data_collator = DataCollatorWithPadding(tokenizer=tokenizer, \<br>                                            return_tensors=&quot;tf&quot;)<br>    tf_dataset = tokenized_data.to_tf_dataset(<br>                columns=[&#39;input_ids&#39;, &#39;attention_mask&#39;],<br>                label_cols=[&quot;labels&quot;],<br>                shuffle=True,<br>                batch_size=8,<br>                collate_fn=data_collator<br>            )<br>    return tf_dataset<br><br>def build_model(num_labels):<br>    model = TFAutoModelForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;,<br>                                                                 num_labels=num_labels)<br>    model.compile(<br>        optimizer=optimizers.Adam(learning_rate=5e-5),<br>        loss=losses.SparseCategoricalCrossentropy(from_logits=True),<br>        metrics=metrics.SparseCategoricalAccuracy()<br>    )<br>    return model</pre><p>Instead of training each split on <strong>n </strong>number of epochs, we could use the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping"><em>EarlyStopping</em></a> callback. For details, you could refer to the link.</p><pre>import tensorflow as tf<br><br>def train_model(train_data, num_labels, valid_data=None, batch_size=8,<br>                 epochs_num=20):<br>    model = build_model(num_labels=num_labels)<br>    model_callback = None<br>    <br>    if valid_data is not None:<br>        early_callback = [tf.keras.callbacks.EarlyStopping(<br>            monitor=&#39;val_sparse_categorical_accuracy&#39;, patience=7, <br>            restore_best_weights=True, mode=&#39;max&#39;, min_delta=0.001)]<br>        model_callback = [early_callback]<br><br>    history = model.fit(train_data,<br>                        validation_data=valid_data,<br>                        epochs=epochs_num, verbose=2, <br>                        batch_size=batch_size, callbacks=model_callback)<br>    return history, model</pre><p>Iterating over each split, and training till the validation data reaches its maximum accuracy.</p><pre><br>all_val_accuracies = []<br><br>for train_indices, valid_indices in kfold.split(df, df[&#39;label&#39;]):<br>    train_df = df.iloc[train_indices]<br>    valid_df = df.iloc[valid_indices]<br>    <br>    train_tf_data = create_dataset(train_df)<br>    valid_tf_data = create_dataset(valid_df)<br>  <br>    history, model = train_model(train_tf_data, num_labels, valid_tf_data)<br>    <br>    val_accuracy = history.history[&#39;val_sparse_categorical_accuracy&#39;]<br>    #its a list of accuracy of each epoch on validation data<br>    <br>    all_val_accuracies.append(val_accuracy)</pre><p><strong>Step 3</strong>: Calculating average Accuracy for each epoch on all K-Validation splits and finding the epoch with maximum accuracy.</p><p>Let’s assume that first model trained till 15 epochs, second till 12 epochs and so on. So, we will first trim the list till the least epochs and then convert it into a 2d numpy array.</p><pre>epochs_len = [len(each_hist) for each_hist in all_val_accuracies]<br>min_epoch = min(epochs_len)<br><br>trimmed_val_accuracies = np.array([each_hist[:min_epoch] for each_hist \<br>                          in all_val_accuracies])</pre><p>Now, we need to calcuate the average accuracy on each epoch. For this, we have to first sum over the array along the axis=0, and then divide each by K. Since K is constant , we can just take the epoch with maximum sum.</p><pre>sum_val_acc = np.sum(trimmed_val_accuracies, axis=0)<br><br>optimal_epoch = np.argmax(sum_val_acc) + 1</pre><p><strong>Step 4:</strong> Retrain the Model on complete data till optimal epochs <strong>n</strong>.</p><pre>tf_data = create_dataset(df)<br><br>history, model = train_model(train_tf_data, num_labels, <br>                  epochs_num=optimal_epoch)<br><br>model.save_pretrained(&quot;optimal-epoch-model&quot;, saved_model=True)</pre><p>Using this method, does increase a considerable amount of time on Training and one could get away by simply splitting the data into 1 Training and Validation set and using Early Callback, as it works for most of the time, if validation data is enough.</p><p>But in case of very small datasets, and you need all the data for training and can’t keep some data points aside, k-fold technique could be used for tuning the hyperparameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615a002195cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/finding-optimal-epochs-using-k-fold-for-transformer-models-615a002195cb">Finding Optimal epochs using K-Fold for Transformer Models.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimization Techniques for better and faster Model Training.]]></title>
            <link>https://medium.com/geekculture/optimization-techniques-for-better-and-faster-model-training-44b41ef7bd31?source=rss-bb949d75e9ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b41ef7bd31</guid>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Shreya Goyal]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 10:38:09 GMT</pubDate>
            <atom:updated>2022-05-04T06:36:19.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Model Training basically involves learning an equation that minimizes the loss between the actual and predicted value. By learning an equation, means to adjust the various parameters/weights in the equation. Here’s where optimization comes in play.</p><blockquote>An optimizer is a method or algorithm to update the various parameters that can reduce the loss in much less effort.</blockquote><p><em>Let’s dive straight into different Optimization Techniques:</em></p><p><strong>Gradient Descent </strong><em>(proposed by Cauchy in 1874 )</em></p><p>It’s the very first optimization algorithm that came into picture. The weights are updated using the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*Sv3pxas-eSwG020zAxuHYg.png" /><figcaption>Figure 1: Gradient Descent algorithm , <em>Image by author</em></figcaption></figure><p>GD updates the weights θ by directly subtracting the gradient(derivative) of the cost function <em>J(θ) w.r.t </em>θ multiplied by the learning rate, α . But why gradient of cost function? Cost function is the function that we aim to minimize, and it’s derivative is basically the direction of slope. So, GD steps down the slope by rate, α until it converges and reaches the minima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*W-Ry-D1V_-8gCP-zMWvAdg.png" /><figcaption>Figure 2: Gradient Descent Illustration, <em>Image by author</em></figcaption></figure><p>α, is the hyperparameter here, and is called learning rate. It determines how big/small the steps would be.</p><ol><li>If α is very large, it may fail to converge and overshoot the minimum.</li><li>If α is very small, it would take long time to converge and become computationally expensive.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*GoFOHGVnX9mVrSLjXqXVNQ.png" /><figcaption>Figure 3: When, α is very large and the steps keep on oscillating instead of reaching the minima and diverge. <em>Image by author</em></figcaption></figure><p>Let’s look at the loss w.r.t to epochs in case of different learning rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*_pv3fU5efDmNaJMe.jpeg" /><figcaption>Figure 4: Gradient descent with different learning rates. <a href="http://cs231n.github.io/neural-networks-3/">Source</a></figcaption></figure><p><strong>Gradient Descent with Momentum </strong><em>(proposed by Boris Polyak in 1964)</em></p><p>Problem with traditional Gradient Descent algorithm is, it doesn’t take into account what the previous gradients are and if the gradients are tiny, it goes down very slowly.</p><p>This create issues when there are multiple local minima, or saddle points with approximately zero gradient, which in turn leads to no or very less update in weights and the learning stops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*6bnX4AjWm5VtzvS5F-ORrA.png" /><figcaption>Figure 5: Gradient Descent stuck at local minima instead of going down to global minima. <em>Image by author</em></figcaption></figure><p>Momentum Optimization, on the other hand cares a lot about the previous gradients. It takes into account the change in step at previous iteration (momentum gained) and use that to update the next step. We can imagine a rolling ball, which starts slowly but pick up momentum quickly until it reaches the bottom (global minima). The weights are updated using the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*FELAX0zRKQc5Eq96KQIaXA.png" /><figcaption>Figure 6: Momentum Optimization algorithm. <em>Image by author</em></figcaption></figure><p>β, called the momentum is to adjust the previous change, and is set between <em>0(high friction)</em> to <em>1(low friction)</em>. Recommended value is 0.9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*VP2bzoO_xDppAeZclfWMCw.png" /><figcaption>Figure 7: Gradient Descent with Momentum Illustration, doesn’t get stuck at local minima and reach the global minima using the momentum gained from previous iterations. <em>Image by author</em></figcaption></figure><p><strong>Nesterov Accelerated Gradient </strong><em>(proposed by Yurii Nesterov in 1983)</em></p><p>It’s a small update to Momentum optimization, instead of calculating the gradient at the local position, it calculates the gradient slightly ahead in the direction of momentum. This tweak works, because even the momentum optimization will be pointing towards the right direction, so it makes sense to measure gradient at a slightly far point, and in turn it will converge a bit more faster.</p><p>The weights are updated using the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*gNAH_q3hQWDNqR9ln971rw.png" /><figcaption>Figure 8: Nesterov Accelerated Gradient algorithm. <em>Image by author</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*ksBU3WtAbsQxoQXLypicQw.png" /><figcaption>Figure 9: Nesterov Accelerated Gradient, converges much faster than Momentum optimization. <em>Image by author</em></figcaption></figure><p><strong>AdaGrad </strong><em>(proposed by John Duchi in 2011)</em></p><p>When we have multiple parameters/weights and the function is non-convex instead of convex, we might need different learning rate at different points.</p><p>In AdaGrad optimization, the learning rate adapts according to the gradient. The weights are updated using the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*iV-xTSBZ_8kcj8Qq1HLgZQ.png" /><figcaption>Figure 10: AdaGrad algorithm. <em>Image by author</em></figcaption></figure><p>Here, the learning rate α is divided by parameter s, which accumulates the square of the gradients. This means, that when the slope is small , α will be large and in turn large steps will be there in contrast to when we are near the minima and the slope is steep.</p><p>Let’s consider a case first with Gradient Descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*V5Gqp3flQW_xmBYilcsgPw.png" /><figcaption>Figure 11: GD oscillating around global minima, until it reaches there after a lot of iterations, with a constant learning rate, α. <em>Image by author</em></figcaption></figure><p>However, if use a very small learning rate to prevent it from oscillations, it will still take a lot more iterations and will be computationally expensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*m_8k3DdllTJu15Rvy5b2Yg.png" /><figcaption>Figure 12: AdaGrad Illustration. Global Minima is reached much faster with the slower learning rate near the minima than at beginning. <em>Image by author</em></figcaption></figure><p><strong>RMSProp </strong><em>(proposed by Geoffrey Hinton &amp; Tijmen Tieleman in 2012)</em></p><p>Due to slow convergence near the minima, AdaGrad might run into the risk of slowing down a bit too fast and never converging to the global optimum. RMSProp fixes this issue, by using a exponential decay in the first step and reduces the effect of slope on learning rate.</p><p>Weights are updated using the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*-K1jng7WABS6kzdRCWhvzg.png" /><figcaption>Figure 13: RMSProp algorithm. <em>Image by author</em></figcaption></figure><p>The decay rate, β is typically set to 0.9 and works well for most of the problems.</p><p><strong>Adam </strong><em>(proposed by Diederik and Jimmy in 2014)</em></p><p>It stands for adaptive momentum estimation and combines the idea of <em>momentum optimization</em> and <em>RMSProp</em>.</p><p>Weights are updated using the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*VBYU_CHWU8XPhJBvugSnZQ.png" /><figcaption>Figure 14: Adam algorithm. <em>Image by author</em></figcaption></figure><p>Step 1,2 and 5 , are very similar to Momentum optimization and RMSProp.</p><p>The momentum decay parameter <em>β1</em> is typically initialized to <em>0.9</em>, while the scaling decay parameter<strong> </strong><em>β2 </em>is initialized to <em>0.999</em>.</p><blockquote>In practice Adam, works well for almost all problems and often works slightly better than RMSProp. So, we can use Adam as a default optimizer in all our deep learning models. But, in some datasets we can try using Nesterov Accelerated Gradient as an alternative.</blockquote><p>There are 2 variants of Adam, namely <strong>AdaMax </strong>and <strong>Nadam.</strong></p><p><strong>AdaMax</strong> :<strong> </strong>It replaces the step 2 of the equation with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*Onf7toERfYm4t5MYyQ3mkw.png" /><figcaption>Figure 15: change in Step 2 in AdaMax algorithm. <em>Image by author</em></figcaption></figure><p>Moreover, it drops out the step 4 and directly scale down the learning rate by factor of <strong><em>s</em></strong>. In some cases AdaMax is more stable than Adam, but it depends on the dataset.</p><p><strong>Nadam </strong>: It is Adam + Nesterov Accelerated Gradient, which helps it to converge slightly faster than Adam. Again, it depends on the dataset in hand.</p><p>Let’s check how to implement each of the Optimizer in Keras, tensorflow. We can take fashion_mnist as a sample dataset. There are 10 classes in the dataset :<em> </em><em>[‘top’, ‘trouser’, ‘pullover’, ‘dress’, ‘coat’, ‘sandal’, ‘shirt’, ‘sneaker’, ‘bag’, ‘ankle boot’]</em></p><pre>import tensorflow as tf<br>from tensorflow import keras<br>fashion_mnist = keras.datasets.fashion_mnist<br>(X_train, Y_train), (X_test, Y_test) = fashion_mnist.load_data()<br>X_valid, X_train = X_train[:5000]/255.0, X_train[5000:]/255.0<br>Y_valid, Y_train = Y_train[:5000] , Y_train[5000:]</pre><p>We will create a simple Sequential Model.</p><pre>model = keras.models.Sequential()<br>model.add(keras.layers.Flatten(input_shape=[28,28]))<br>model.add(keras.layers.Dense(300, activation=&quot;relu&quot;))<br>model.add(keras.layers.Dense(100, activation=&quot;relu&quot;))<br>model.add(keras.layers.Dense(10, activation=&quot;softmax&quot;))</pre><p>Defining SGD (Gradient Descent) Optimizer</p><pre>optimizer = keras.optimizers.SGD(learning_rate=0.001)<br>model.compile(loss=&quot;sparse_categorical_crossentropy&quot;, optimizer = optimizer, metrics=[&quot;accuracy&quot;])<br>history = model.fit(X_train, Y_train, epochs=20, validation_data=(X_valid, Y_valid))</pre><p>Similarly, we can define various other optimizers and pass them in <em>model.compile</em></p><pre># Momentum Optimization<br>optimizer = keras.optimizers.SGD(learning_rate=0.001, momentum=0.9)</pre><pre># Nesterov Accelerated Gradient<br>optimizer = keras.optimizers.SGD(learning_rate=0.001, momentum=0.9,nesterov=True)</pre><pre># AdaGrad<br>optimizer = keras.optimizers.Adagrad(learning_rate=0.001)</pre><pre>#RMSProp<br>optimizer = keras.optimizers.RMSprop(learning_rate=0.001, rho=0.9)</pre><pre>#Adam<br>optimizer = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999)</pre><pre>#AdaMax<br>optimizer = keras.optimizers.Adamax(lr=0.001, beta_1=0.9, beta_2=0.999)</pre><pre>#Nadam<br>optimizer = keras.optimizers.Nadam(lr=0.001, beta_1=0.9, beta_2=0.999)</pre><p>Complete code can be found <a href="https://github.com/GoyalShreya/keras-tf2-notebooks/blob/main/comparing%20_optimizers8.ipynb"><strong>here</strong></a>.</p><p>The performance of various optimizers on the given model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*0y18ptKMTiQ4wchCaWKpPQ.png" /><figcaption>Figure 16: Comparison of different Optimizers on Fashion Mnist Data classification Model. <em>Image by author</em></figcaption></figure><p>Following conclusions can be drawn from the Graph:</p><ol><li>As we can see the later optimization techniques converges much faster than <strong>SGD</strong>, and even attains global minima in very few epochs.</li><li><strong>Adam variants</strong> outperform all and reaches to minima in much less epochs.</li><li>Also, in this situation , <strong>Nesterov </strong>outperforms <strong>RMSProp</strong>.</li><li><strong>AdaGrad </strong>gets to minimum at the beginning, but there is not much update after that.</li><li>So, we can easily use <strong>Adam </strong>as a default optimizer in most of the cases.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b41ef7bd31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/optimization-techniques-for-better-and-faster-model-training-44b41ef7bd31">Optimization Techniques for better and faster Model Training.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Better Code in Python]]></title>
            <link>https://python.plainenglish.io/python-writing-better-codes-175fe422a5a0?source=rss-bb949d75e9ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/175fe422a5a0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shreya Goyal]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 10:07:48 GMT</pubDate>
            <atom:updated>2022-04-26T04:30:17.352Z</atom:updated>
            <content:encoded><![CDATA[<h4>Code conventions, and libraries to use while writing codes in Python which will make your code consistent, efficient, and easy to debug/read.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-AdHb39VHOpnu3g3" /><figcaption>Photo by <a href="https://unsplash.com/@alvarordesign?utm_source=medium&amp;utm_medium=referral">Alvaro Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A better programmer is not the one who can write codes that a computer can understand but it’s the one, whose code is easily understood by its colleagues, and further modifications can be added without much affecting the previous code.</p><p>In this article, I am listing down some of the code conventions, and libraries to use while writing codes in Python which will make your code, consistent, efficient, and easy to debug/read.</p><h4>1. Ternary Expressions</h4><p>If we’re only dealing with just the assignment of one variable, we should use the ternary expression, which checks the condition and completes the assignment with just one line of code.</p><pre># The typical way<br>if score &gt; 90:<br>    grade = “A”<br>else:<br>    grade = “B”</pre><pre># Do this instead<br>grade = “A” if score &gt; 90 else “B”</pre><h4>2. Evaluating Multiple If Conditions</h4><p>We should try to make multiple conditional statements in ‘if’ as compact as possible. Let’s look at some of the examples.</p><pre># Multiple Comparisons<br># The typical way<br>if a &lt; 4 and a &gt; 1:<br>    # do something here</pre><pre># Do this instead<br>if 1 &lt; a &lt; 4:<br>    # do something here</pre><pre># The typical way<br>if b == &quot;A&quot; or b == &quot;B&quot; or b == &quot;C&quot; or b == &quot;D&quot;:<br>    # do something here</pre><pre># Do this instead<br>if b in &quot;A B C D&quot;.split():<br>    # do something here</pre><p>Another technique is the use of the built-in all() and any() functions for evaluating multiple conditions.</p><pre># The typical ways<br>if a &lt; 10 and b &gt; 5 and c == 4:<br>    # do something</pre><pre>if a &lt; 10 or b &gt; 5 or c == 4:<br>    # do something</pre><pre># Do these instead<br>if all([a &lt; 10, b &gt; 5, c == 4]):<br>    # do something</pre><pre>if any([a &lt; 10, b &gt; 5, c == 4]):<br>    # do something</pre><h4>3. List and Dict Comprehensions</h4><p>Comprehensions are used to replace multiple lines in a <strong>for </strong>loop with a single statement. They increase both the performance and readability of the program. List and Dict comprehensions are used according to the final data type that&#39;s needed.</p><p>Let’s look at list comprehensions first:</p><pre># typical way<br>square_num = []<br>for x in range(5):<br>    if x%2==0:<br>        square_num.append(x**2)<br>    else:<br>        square_num.append(x)</pre><pre># do this instead<br>square_num = [x**2 if x%2==0 else x for x in range(5)]</pre><p>It can be easily applied to nested loops as well. The easy way to create comprehensions is first taking the final expressions and then writing the loops from top to bottom. What does that mean?</p><p>Well, let’s understand by one example.</p><pre># typical nested loops<br>num=[]<br>for x in range(10):<br>    for y in range(0,x):<br>        if y%2 == 0:<br>            num.append(y)<br>        else:<br>            num.append(0)</pre><p>Let’s create a comprehension of the above example now. The final expression is: num.append(y) if y%2 ==0 else num.append(0), and the loops are for x in range(10) and for y in range (0,x).</p><p>The final list comprehension will look like this:</p><pre>num = [y if y%2==0 else 0 for x in range(10) for y in range(0,x)]</pre><p>In a similar fashion, Dict comprehensions can be created.</p><pre># typical way<br>some_dict= {}<br>for x,y in zip(range(4),(&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;)):<br>    some_dict[y] = x</pre><pre># do this instead<br>some_dict = {y:x for x,y in zip(range(4),(&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;))}</pre><p>In the above example, I have used <strong>zip, </strong>which should be used frequently too in code wherever needed, to make the code compact.</p><h4>4. Accessing Elements from Dict</h4><p>This is a mistake we all do, accessing a key from Dict that doesn’t exist and could send the program with an exception. Instead of applying checks for the key, we should use the<em> get() </em>method.</p><pre># typical way<br>if &#39;key&#39; in some_dict:<br>    value = some_dict[&#39;key&#39;]</pre><pre># do this instead<br>value = some_dict.get(&#39;key&#39;, &#39;default_value&#39;) </pre><p>The<em> ‘default_value’</em> is defined in case the key doesn’t exist in the Dict, then that value will get returned.</p><h4>5. Default Values in Function Declarations</h4><p>Optional parameters or the parameters whose values will not be changed much on call should be defined with a default value in their function declaration.</p><pre># typical way<br>def do_some_work(task, hours, db_flag):<br>    # do something here</pre><pre>total_sum = do_some_work(&#39;get_sum&#39;, 10, None)<br>all_data = do_some_work(&#39;get_data&#39;, 10, 1)</pre><pre># do this instead<br>def do_some_work(task, hours=10, db_flag=None):<br>    # do something here</pre><pre>total_sum = do_some_work(&#39;get_sum&#39;)<br>all_data = do_some_work(&#39;get_data&#39;, db_flag=1)</pre><p>This will be useful when the function parameters increase on adding some new code and by using default values, we don’t need to change the arguments in any previous calls made.</p><p>Here’s a catch though, there are two types of arguments — <strong>Mutable </strong>(e.g., list and dict) and <strong>Immutable </strong>(e.g., int, str, booleans, etc.) objects. Now, in Python, every default argument is evaluated just once and not on every function call made. In that case, if it&#39;s a mutable object, it will be evaluated only once and all the operations will be done on the existing list which might get modified with every function call. <strong><em>So, we should avoid using mutable objects in default values.</em></strong></p><pre>#default_arguments.py<br>def add_a(a_list=[]):<br>    a_list.append(2)<br>    print(a_list)</pre><pre>add_a()<br>add_a()<br>add_a()</pre><pre># output will be, which is not expected<br>[2]<br>[2,2]<br>[2,2,2]</pre><pre><br># do this instead<br>def add_a(a_list=None):<br>    a_list = []<br>    a_list.append(2)<br>    print(a_list)</pre><pre>add_a()<br>add_a()<br>add_a()</pre><pre># here, output will be<br>[2]<br>[2]<br>[2]</pre><h4>6. With Operators, Context Managers</h4><p>Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with statement. This is widely used when we want to open a file, do some operations on it and then close it.</p><pre># typical way<br>file_obj = open(&#39;some_file&#39;, &#39;w&#39;)<br>try:<br>    file_obj.write(&#39;Hey!&#39;)<br>    file_obj.write(&#39;What are you upto?&#39;)<br>finally:<br>   file_obj.close()</pre><p>But, in this scenario, if we forgot to close the file, none of the data will get written, to avoid such mistakes we should always use with statement.</p><pre># do this instead<br>with open(&#39;some_file&#39;, &#39;w&#39;) as file_obj:<br>    file_obj.write(&#39;Hey!&#39;)<br>    file_obj.write(&#39;What are you upto?&#39;)</pre><p>There is no need for any close statement, that will be handled by <strong>with </strong>operator.</p><h4>7. * and **, the Unpacking Operators</h4><p>* and ** are basically the unpacking operators. * can unpack any iterable object like <em>list</em>, while ** works on <em>dict </em>only. Let’s understand by looking at some examples.</p><pre># typical way<br>a,b,c,d,e,f = some_func_call(data)<br>print(a,e)</pre><pre># In this case, we could unpack multiple value by using *<br>a,*b,e,f = some_func_call(data)<br>print(a,e)</pre><p>In function declarations and calls too.</p><pre># typical way<br>def get_sum(a,b,c,d):<br>    total_sum = a+b+c+d</pre><pre># do this instead<br>def get_sum(*args):<br>    total_sum = 0 <br>    for each_arg in args:<br>        toatl_sum += each_arg</pre><pre>get_sum(1,2,3)<br>get_sum(1,2,4,5)<br># this will work on any number of args</pre><p>Let’s look at some usage of ** as well. It’s used when we have the key-value pairs to unpack.</p><pre># typical way<br>def print_values(name, age, gender, grade):<br>    print(&quot;name:&quot;, name)<br>    print(&quot;age:&quot;, age)<br>    print(&quot;gender:&quot;, gender)<br>    print(&quot;grade:&quot;, grade)</pre><pre># do this instead<br>def print_values(**kwargs):<br>    for key, value in kwargs.items():<br>        print(&quot;{}:{}\n&quot;.format(key, value))</pre><pre># we can give any number of key value pairs then<br>print_values(name=&#39;X&#39;, age=&#39;20&#39;, gender=&#39;Male&#39;)</pre><h4>8. Collections Library: Default Dict and Counter</h4><p>Collections is a standard library module and have a number of useful utilities, particularly, <strong><em>defaultdict </em></strong>and <strong><em>Counter. </em></strong>Let’s look at them one by one.</p><p><strong><em>Defaultdict:</em></strong><em> </em>It allows you to add values to dictionaries concisely and reduce boilerplate code.</p><pre># typical way<br>all_data = [(&#39;emp1&#39;, &#39;detp1&#39;), (&#39;emp2&#39;, &#39;dept2&#39;), (&#39;emp3&#39;, &#39;dept2&#39;)]</pre><pre># need to create a dict with dept as keys<br>dept_data = {}<br>for emp, dept in all_data:<br>    if dept not in dept_data:<br>        dept_data[dept] = []<br>    dept_data[dept].append(emp)</pre><pre><br># do this instead<br>from collections import defaultdict</pre><pre>dept_data = defaultdict(list)<br>for emp, dept in all_data:<br>    dept_data[dept].append(emp)</pre><pre><br># defaultdict can be used with other data types also, e.g.,<br>int_defaultdict = defaultdict(int)<br>int_defaultdict[&#39;value&#39;] += 1<br>int_defaultdict[&#39;value&#39;] += 1</pre><p><strong><em>Counter:</em></strong> It can be used to maintain tallies. Suppose we want to create a vocab dict with unique words and their number of occurrences.</p><pre># typical way<br>words = [&#39;fox&#39;, &#39;wolf&#39;, &#39;fox&#39;, &#39;sit&#39;, &#39;tree&#39;, &#39;eat&#39;, &#39;sheep&#39;, &#39;eat&#39;, ...]<br>vocab = {}<br>for each_word in words:<br>   if word not in vocab:<br>       vocab[word] = 0<br>   vocab[word] += 1</pre><pre># same could be done by deafultdict too, but we have more easy way.<br>from collections import Counter<br>vocab = Counter(words)</pre><pre># and its done ! more words can be added too<br>vocab.update(more_words)</pre><pre># we can fetch the most common words easily<br>vocab.most_common()</pre><pre># output<br>[(&#39;fox&#39;, 2), (&#39;eat&#39;, 2), ...]</pre><h4>9. Type Hinting</h4><p>In Python, we can directly assign values to variables without defining their data types. Although, it’s flexible in Python, defining data types increases the readability of code and avoid the chances of mistakes.</p><pre>def greet(name: str) -&gt; str:<br>    return &quot;Hello&quot;+name</pre><pre># varaibles assignment<br>age: int = 20<br>name: str =  &#39;ABC&#39;<br>some_list: list = [1,2,3]</pre><p>Python’s typing module can make data type annotations even more verbose.</p><pre>from typing import Optional, List, Tuple</pre><pre>def some_work(names: List[str], age_data: List[int],<br>              work_done: Optional[int]=0) -&gt; None:<br>    # do something here</pre><h4>10. Deepcopy</h4><p>Let’s understand this, directly by an example.</p><pre>a = [1,2,3,4,5]<br>b = a<br>b.remove(3)<br>print(&quot;b :&quot;, b)<br>print(&quot;a :&quot;, a)</pre><p>What do you expect the output will be. 3 gets removed from list b and remains as it is. Well, it&#39;s not the case.</p><pre># output<br>b :[1,2,4,5]<br>a :[1,2,4,5]</pre><p>By using the assignment operator(=), the same pointer is pointing to both a and b . Any change in b will get reflected in a, if that’s not intended, then we should use deep copy to create duplicate copies of the variable.</p><pre># do this instead<br>from copy import deepcopy</pre><pre>b = deepcopy(a)<br>b.remove(3)<br>print(&quot;b :&quot;, b)<br>print(&quot;a :&quot;, a)</pre><pre># output<br>b :[1,2,4,5]<br>a :[1,2,3,4,5]</pre><p>By using all the techniques mentioned, we can have a much more clean, effective, and readable code.</p><p>That’s it for this topic. Thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175fe422a5a0" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-writing-better-codes-175fe422a5a0">How to Write Better Code in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Last-Minute Touchups for Better Code Quality in Python]]></title>
            <link>https://python.plainenglish.io/python-last-minute-touchups-for-better-code-quality-efddfae93463?source=rss-bb949d75e9ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/efddfae93463</guid>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[flake8]]></category>
            <category><![CDATA[code-readability]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Shreya Goyal]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 14:50:49 GMT</pubDate>
            <atom:updated>2022-04-28T06:14:53.750Z</atom:updated>
            <content:encoded><![CDATA[<h4>Improve code readability with these simple tools.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*di8lpKL1fRRq6BO9" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We often forget to follow basic <strong>Code Conventions</strong> when writing Python code, since we know it’s not very restricted and will still run the code. However, it decreases the <strong>Code Readability</strong> and can also cause unexpected behavior in its logic, which becomes hard to trace as the project grows.</p><p>Here, I am listing some very simple tools to identify such pitfalls in the code and at the same time increase code readability.</p><ol><li><strong><em>black: </em></strong>It formats the Python code in a way that is pleasant, consistent, and most importantly readable. It’s <strong><em>“</em></strong><em>the uncompromising Python code formatter</em><strong><em>”, </em></strong>that cannot be configured or changed. <em>So, you can write code lazily and quickly, knowing black is there to automatically format it.</em></li></ol><p>You can easily install black using pip: pip install black and running it is even simple, just call it on the complete project and it will format all the code files within. Run black &lt;project_dir&gt; and you are done!</p><pre># before black<br>session.query(DB()).filter(DB().emp_id == arg_id, DB().emp_type == 6, or_(DB().lang == ‘english’, DB().lang == ‘’, DB().lang == None)).update({“lang”: language}, synchronize_session=False)</pre><pre># after black<br>session.query(DB()).filter(<br>    DB().emp_id == arg_id,<br>    DB().emp_type == 6,<br>    or_(DB().lang == &quot;english&quot;, DB().lang == &quot;&quot;, DB().lang == None),<br>).update({&quot;lang&quot;: language}, synchronize_session=False)</pre><p>2. <strong>Flake8</strong>: It detects a lot of errors in your code and will list them down for you, with each code assigned a type and reports then can be generated too.</p><p>It will detect a number of issues, which might not cause an error at run time but should be avoided. For example, it will flag the unused imports as well as wildcard imports.</p><p><em>Wildcard imports might feel harmless but can impart a lot of harm without raising any issues. They should be avoided at every cost!</em></p><p>Let’s look at an example of the same. Suppose we have 2 files having a function with the same name, let&#39;s call it get_data(). Now, the function will be called from whichever file is imported at last.</p><pre>#wildcard_import.py<br>from file_a import *<br>from file_b import *</pre><pre>def get_data_a():<br>    get_data()</pre><pre>#flake8 will identify the error<br>wildcard_import.py:2:1: F403 &#39;from file_a import *&#39; used; unable to detect​ undefined get_data()</pre><p>It will also detect variables that are accessed without being defined.</p><pre>#undefined_variable.py<br>total_sum = 0<br>total_sum += a</pre><pre># after running flake8<br>undefined_variable.py:3:5: F821 undefined name &#39;a&#39;</pre><p>There is a large list of what Flake8 can detect and it&#39;s easy to install and run as well. Just run #pip install flake8and #pip install flake8-bugbear</p><p>The flake8-bugbear has some additional add-ons like detecting mutable default arguments.</p><pre>#default_arguments.py<br>def add_a(a_list=[]):<br>    a_list.append(2)<br>    print(a_list)</pre><pre>add_a()<br>add_a()<br>add_a()</pre><p>You will see output like this when you run the code:</p><pre>[2]<br>[2,2]<br>[2,2,2]</pre><p>This was not expected but instead, it should have created a new a_list on every call and added 2 in it. However, this is not a bug. Python evaluates default arguments just once. So, if a mutable object (e.g., list, dict, etc.) is present, the same will be used for every function call and can cause unexpected behaviour in our code. Not much of a problem in the case of immutable objects (e.g., int, str, booleans, etc).</p><p>Flake8 will detect such issues and will flag them before causing any untraceable bugs in our code.</p><p>For a list of issues that flake8 detects, you can go over the documentation of it: <a href="https://buildmedia.readthedocs.org/media/pdf/flake8/stable/flake8.pdf">https://buildmedia.readthedocs.org/media/pdf/flake8/stable/flake8.pdf</a></p><p>You can run Flake8 on the entire project at once: flake8 &lt;project_dir&gt; . Also, various other arguments can be passed like --ignore to ignore some of the Issue IDs when running Flake8.</p><p>More options can be found by running : flake8 --help</p><p>The easiest way, which I prefer is creating a <strong><em>.flake8</em></strong> file and defining all the configs there. This way, when flake8 runs, it will by default pick those arguments and run. For example, I use the following config:</p><pre>#.flake8<br>[flake8]<br>ignore = E501,F841,E266,E265,E302,E401,F401,E203,W605,W503,B009<br>show_source = True<br>statistics = True<br>format = pylint<br><br># usage: flake8 \dir_name\ --output-file=issues.txt</pre><p>You can add more config parameters, as suited.</p><p>So, just by calling these 2 modules before pushing our code in any remote repo, we were successful in increasing our code quality , easy right?</p><p>Thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efddfae93463" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-last-minute-touchups-for-better-code-quality-efddfae93463">Last-Minute Touchups for Better Code Quality in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Loss Functions: An Overview]]></title>
            <link>https://medium.com/geekculture/ml-loss-functions-an-overview-14dcca261504?source=rss-bb949d75e9ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/14dcca261504</guid>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shreya Goyal]]></dc:creator>
            <pubDate>Thu, 28 Oct 2021 05:59:01 GMT</pubDate>
            <atom:updated>2023-02-10T20:02:20.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4UpcX6nZZXQ7kNDB" /><figcaption>Photo by <a href="https://unsplash.com/@franki?utm_source=medium&amp;utm_medium=referral">Franki Chamaki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What’s a Loss Function? It’s how we can find out that our Algorithm is performing well or not, the main aim of algorithm is to reduce this loss so as to get our predictions close to Actual values.</strong></p><p><em>Before choosing a Loss function that will be appropriate for your model, you should understand the problem statement, the data you are dealing with and the different type of loss functions that are there! You can obviously customize your own loss function.</em></p><p>Let’s go through some of the predefined Loss Functions. Broadly there are 2 categories: Regression Loss and Classification Loss. I think what’s important is to understand the <em>What? Why? </em>and <em>How?</em> of each loss.</p><h3><strong>Regression Losses</strong></h3><h3><strong>Mean Squared Error (MSE)/ Root Mean Squared Error (RMSE)</strong></h3><h4>What?</h4><ol><li>In Statistics, Mean Square Error (MSE) is defined as Mean or Average of the square of the difference between actual and estimated values.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*TCE9Kui4fbyZl5u3ARRBJw.png" /></figure><p>2. MSE unit order is higher than the error unit as the error is squared. To get the same unit order, many times the square root of MSE is taken. It is called the Root Mean Squared Error (RMSE).<br>RMSE = SQRT(MSE)</p><h4>Why?</h4><ol><li>The result is always positive. So, you will always aim to minimize it irrespective of the signs in the Predicted and Actual value.</li><li>The squaring means that larger mistakes result in more error than smaller mistakes, meaning that the model is punished for making larger mistakes.</li><li>Why Squared? Its because otherwise sometimes the predicted value will be less and sometimes more than actual value which can result in negative and positive difference between them, which can then lead to incorrect summation and sometimes 0, in worst case! which can make us believe our model is prefect!</li></ol><h4>How?</h4><ol><li>Can be used in Keras by specifying ‘mse‘ or ‘mean_squared_error‘ as the loss function when compiling the model.</li></ol><pre><em>model.compile(loss=’mean_squared_error’) model.compile(loss=’root_mean_squared_error’)</em></pre><p>2. From Sklearn Module of python</p><pre><em>from sklearn.metrics import mean_squared_error<br>mean_squared_error(y_true, y_pred)</em><br><em>mean_squared_error(y_true, y_pred, squared=False) ; </em>if squared=False it returns RMSE instead of MSE</pre><p>3. Using Numpy Module</p><pre><em>mse = np.square(y_true — y_pred).mean(axis=0)<br>rmse = np.sqrt(mse)</em></pre><h3><strong>Mean Absolute Error (MAE)</strong></h3><h4>What?</h4><ol><li>Mean Absolute Error (MAE) is defined as Mean or Average of the absolute difference between actual and estimated values.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*yxvpJsR_us5nQ6IF.gif" /></figure><h4>Why?</h4><ol><li>It treat larger and small errors equally. Not very sensitive to outliers unlike MSE loss.</li></ol><h4>How?</h4><ol><li>Can be used in Keras by specifying ‘mean_absolute_error’ as the loss function when compiling the model.</li></ol><pre><em>model.compile(loss=’mean_absolute_error’)</em></pre><p>2. From Sklearn Module of python</p><pre><em>from sklearn.metrics import mean_absolute_error<br>mean_absolute_error(y_true, y_pred)</em></pre><p>3. Using Numpy Module</p><pre><em>mae = np.absolute(y_true — y_pred).mean(axis=0)</em></pre><h3><strong>Mean Squared Logarithmic Error (MSLE)/ RMSLE</strong></h3><h4>What?</h4><ol><li>First calculate the natural logarithm of each of the predicted values and actual values, then calculate the mean squared error. This is called the Mean Squared Logarithmic Error loss, or MSLE.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*MTzY0ZYdf-GTzFz2DYNY0A.png" /></figure><h4>Why?</h4><ol><li>It only cares about the relative difference between the actual and the predicted value, or in other words, percental difference between them.</li><li>This means that it will treat small differences between small actual and predicted values approximately the same as big differences between large actual and predicted values. So, for eg., if <br><em>Actual = 30, Predicted = 20 ; then MSLE = 0.02861 and <br>Actual = 30000 , Predicted = 20000; then MSLE = 0.03100 but here MSE= 100000000</em></li><li>It’s useful when the range of target values is large i.e., can vary from 10 to 10000 or even more.</li></ol><h4>How?</h4><ol><li>Can be used in Keras by specifying ‘mean_squared_logarithmic_error’ as the loss function when compiling the model.</li></ol><pre><em>model.compile(loss=’mean_squared_logarithmic_error’)</em></pre><p>2. Using Numpy Module</p><pre><em>msle = np.sum(np.square(np.log(y_true+1) -np.log(y_pred+1))).mean(axis=0)</em><br>and simliarly we can have,<em> rmsle = np.sqrt(msle)</em></pre><h3><strong>Huber Loss</strong></h3><h4>What?</h4><ol><li>Huber Loss = Combination of both MSE and MAE</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*Rrcn2OVN1sxnERE2XaU2WQ.png" /></figure><h4>Why?</h4><ol><li>It offers the best of both worlds by balancing the MSE and MAE together. It is quadratic(MSE) when the error is small else MAE.</li><li>Using the MAE for larger loss values mitigates the weight that we put on outliers so that we still get a well-rounded model. At the same time we use the MSE for the smaller loss values to maintain a quadratic function near the center.</li><li>Use the Huber loss any time you feel that you need a balance between giving outliers some weight, but not too much. For cases where outliers are very important to you, use the MSE! For cases where you don’t care at all about the outliers, use the MAE!</li></ol><h4>How?</h4><ol><li>Can be used in Keras by specifying ‘huber_loss’ as the loss function when compiling the model.</li></ol><pre><em>model.compile(loss=’huber_loss’) </em>or <em>model.compile(loss=tf.keras.losses.Huber())</em></pre><p>2. Using Sklearn</p><pre><em>from sklearn.linear_model import HuberRegressor<br>huber = HuberRegressor().fit(X, y)</em></pre><p>3. Using Tensorflow</p><pre>def huber_loss_fn(y_true, y_pred, delta=1):<br> error = y_true — y_pred<br> is_small_error = tf.abs(error) &lt; delta<br> squared_loss = tf.square(error) / 2<br> linear_loss = delta * (tf.abs(error) — delta/2)<br> return tf.where(is_small_error, squared_loss, linear_loss)</pre><h3>Classification Losses</h3><h3>Binary Cross Entropy Loss</h3><h4>What?</h4><p>In Binary Classification we predict the probability of X being in class 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*PDtIfRHpMfbbXbhj26I-OA.png" /></figure><p>When the observation belongs to class 1 the first part of the formula becomes active and the second part vanishes and vice versa in the case observation’s actual class is 0.</p><h4>Why?</h4><ol><li>It is used with Binary classification where the target values are in the set {0, 1}. It then calculates the score that penalizes the probabilities based on the distance from the expected value. That means how close or far from the actual value.</li></ol><h4>How?</h4><ol><li>In Keras</li></ol><pre>model.compile(loss=&#39;binary_crossentropy&#39;)<br>model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True))</pre><p>2. In Sklearn</p><pre><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> log_loss<br>log_loss(<em>y_true</em>, <em>y_pred)</em></pre><p>3. In Numpy</p><pre>loss = -(y_true*np.log(y_pred)+(1-y_true)*np.log(1-y_pred)).mean()</pre><h3>Hinge Loss</h3><h4>What?</h4><p>Hinge Loss is used particularly for SVM models or where the target values are in the set {-1, 1}</p><pre>hinge_loss = max(0, 1-y_true*y_pred)</pre><h4>Why?</h4><ol><li>In SVM, we have 2 classes -1 and 1 and we try to model the decision boundary. So, the predicted values show the distance from the decision boundary.</li><li>In such case if a class is predicted as -1.6 and actual was -1. It means it is far away from decision boundary and hence will have 0 loss. The more its near to the boundary, more will be its Hinge Loss and will keep on increasing if it goes on wrong side of the boundary.</li></ol><h4>How?</h4><ol><li>In Keras</li></ol><pre>model.compile(loss=&#39;hinge&#39;)</pre><p>2. In Sklearn</p><pre>from sklearn.metrics import hinge_loss<br>hinge_loss(y_true, y_pred)</pre><p>3. In Numpy</p><pre>loss = np.max([0.0, 1 - y_true*y_pred])</pre><h3>Multi-Class Cross-Entropy Loss/Categorical Cross-Entropy</h3><h4>What?</h4><p>It is the default loss function used from the Multi Class Classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*rSn1W9CXWW5C0szSTYwwhg.png" /></figure><h4>Why?</h4><ol><li>It is used when we have multiple classes instead of just 2 and instead of calculating Binary Loss for each label, we calculate the categorical loss for all the classes.</li></ol><h4>How?</h4><ol><li>In Keras</li></ol><pre>model.compile(loss=&#39;categorical_crossentropy&#39;)</pre><p>2. In Sklearn</p><pre>sklearn.metrics.log_loss(y_true, y_pred, labels=[all_labels])</pre><h3>Sparse Multiclass Cross-Entropy Loss</h3><h4>What?</h4><p>Both categorical cross entropy and sparse categorical cross-entropy have the same loss function as defined in above Equation. The only difference between the two is on how truth labels are defined. … In sparse categorical cross-entropy , truth labels are <strong>integer encoded</strong>, for example, [1] , [2] and [3] etc., while in categorical cross entropy they are one-hot encoded.</p><h4>Why?</h4><ol><li>It is used in cases where there are large number of labels and doing them one-hot encoding will only cause problems.</li></ol><h4>How?</h4><ol><li>In Keras</li></ol><pre>model.compile(loss=&#39;sparse_categorical_crossentropy&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14dcca261504" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/ml-loss-functions-an-overview-14dcca261504">ML Loss Functions: An Overview</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticating Jira Rest API in Python and Creating Issues: OAuth]]></title>
            <link>https://python.plainenglish.io/authenticating-jira-rest-api-in-python-and-creating-issues-oauth-4780c58fd478?source=rss-bb949d75e9ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/4780c58fd478</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jira-rest-api]]></category>
            <category><![CDATA[oauth-jira]]></category>
            <category><![CDATA[jira]]></category>
            <dc:creator><![CDATA[Shreya Goyal]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 10:54:10 GMT</pubDate>
            <atom:updated>2022-05-05T05:12:06.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ChDYjwSinbcpXzxR" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>OAuth(Open Authentication) is basically a secure gateway for 2 unrelated services to authenticate an asset. For instance, when we log in to any custom app through our Facebook/Gmail account, we are not providing the login information (user name and password) and thus any breach in that app will not affect the security of your Facebook/Gmail account.</p><p>A few days before, I got into a problem to do the same for Jira from an application written in Python. Here I needed to authenticate a Jira user to create issues from a Python app without using the Single Sign on.</p><p>The steps are fairly simple. Before diving into the code, let’s first look at how OAuth works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*RU3D5yYN0AYxrd1YWjHJ9g.png" /><figcaption>Handshake between Application and Jira server.</figcaption></figure><p>Now let’s implement the same in code stepwise. One more thing we need to do is create Application link on Jira Server. Configure your client application on Jira as provided on:</p><p><a href="https://developer.atlassian.com/cloud/jira/platform/jira-rest-api-oauth-authentication/">OAuth 1.0a for REST APIs (Legacy)</a></p><p>From this step you will have consumer_key , private_rsa_key and the server_url (Jira Server URL).</p><ol><li><strong>Requests OAuth token:</strong></li></ol><pre><strong>import </strong>requests<br><strong>from </strong>oauthlib.oauth1 <strong>import </strong>SIGNATURE_RSA<br><strong>from </strong>requests_oauthlib <strong>import </strong>OAuth1<br>verify = False<br>oauth = OAuth1(consumer_key, signature_method=SIGNATURE_RSA, rsa_key=private_rsa_key)<br>r = requests.post(<br>    server_url + <strong>&quot;/plugins/servlet/oauth/request-token&quot;</strong>, verify=verify, auth=oauth<br>)<br>request = dict(parse_qsl(r.text))<br>request_token = request[<strong>&quot;oauth_token&quot;</strong>]<br>request_token_secret = request[<strong>&quot;oauth_token_secret&quot;</strong>]</pre><p>3. <strong>Redirect User to Authorize:</strong></p><pre><strong>import </strong>webbrowser<br>auth_url = <strong>&quot;{}/plugins/servlet/oauth/authorize?oauth_token={}&quot;</strong>.format(<br>    server_url, request_token<br>)<br>webbrowser.open_new(auth_url)<br>print(<strong>&quot;Your browser is opening the OAuth authorization for this client session.&quot;</strong>)<br>approved = input(<strong>&quot;Have you authorized this program to connect on your behalf to {}? (y/n)&quot;</strong>.format(server))<br><strong>if </strong>approved.lower() != <strong>&quot;y&quot;</strong>:<br>    exit(<strong>&quot;Exiting OAuth dance.&quot;</strong>)</pre><p>5. <strong>Requests Access Tokens:</strong></p><pre>oauth = OAuth1(<br>    consumer_key,<br>    signature_method=SIGNATURE_RSA,<br>    rsa_key=key_cert_data,<br>    resource_owner_key=request_token,<br>    resource_owner_secret=request_token_secret,<br>)<br>r = requests.post(<br>    server + <strong>&quot;/plugins/servlet/oauth/access-token&quot;</strong>, verify=verify, auth=oauth<br>)<br>access = dict(parse_qsl(r.text))<br><strong>return </strong>{<br>    <strong>&quot;access_token&quot;</strong>: access[<strong>&quot;oauth_token&quot;</strong>],<br>    <strong>&quot;access_token_secret&quot;</strong>: access[<strong>&quot;oauth_token_secret&quot;</strong>],<br>    <strong>&quot;consumer_key&quot;</strong>: consumer_key,<br>    <strong>&quot;key_cert&quot;</strong>: private_rsa_key,<br>}</pre><p>Now we have the access tokens, they are valid till 5 years and can be used to create, fetch update issues in Jira.</p><p>Code Snippet to create issue in Jira:</p><pre><strong>from </strong>jira.client <strong>import </strong>JIRA<br>jira = JIRA(options={<strong>&#39;server&#39;</strong>: server_url}, oauth={<br>    <strong>&#39;access_token&#39;</strong>: access_token,<br>    <strong>&#39;access_token_secret&#39;</strong>: access_token_secret,<br>    <strong>&#39;consumer_key&#39;</strong>: consumer_key,<br>    <strong>&#39;key_cert&#39;</strong>: private_rsa_key<br>})</pre><pre>payload_temp = {<br>    <strong>&quot;project&quot;</strong>: {<strong>&#39;id&#39;</strong>: &lt;project_id&gt;},<br>    <strong>&quot;summary&quot;</strong>: &lt;summary&gt;,<br>    <strong>&quot;description&quot;</strong>: &lt;desc&gt;,<br>    <strong>&quot;issuetype&quot;</strong>: {<br>        <strong>&quot;name&quot;</strong>: &lt;issue_type&gt;<strong><br>    </strong>}<br>}<br>issue = jira.create_issue(fields=payload_temp)</pre><p>For further Jira operations, explore the Jira library:</p><p><a href="https://jira.readthedocs.io/en/master/">https://jira.readthedocs.io/en/master/</a></p><p>That’s it for this topic. Thank you for reading.</p><p><em>More content at</em><strong><em> </em></strong><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4780c58fd478" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/authenticating-jira-rest-api-in-python-and-creating-issues-oauth-4780c58fd478">Authenticating Jira Rest API in Python and Creating Issues: OAuth</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>