<?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 Alifia Ghantiwala on Medium]]></title>
        <description><![CDATA[Stories by Alifia Ghantiwala on Medium]]></description>
        <link>https://medium.com/@gghantiwala?source=rss-b519474fb94c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MTwBe1V0-Jp6nrYAdXVMeA.jpeg</url>
            <title>Stories by Alifia Ghantiwala on Medium</title>
            <link>https://medium.com/@gghantiwala?source=rss-b519474fb94c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:41:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gghantiwala/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[Building an audio classifier (Part 3)]]></title>
            <link>https://gghantiwala.medium.com/building-an-audio-classifier-part-3-ddf80a833ace?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf80a833ace</guid>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[classifier]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 05:30:12 GMT</pubDate>
            <atom:updated>2023-08-31T05:29:11.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z0IfVxBeD-ARARhY" /><figcaption>Photo by <a href="https://unsplash.com/@schluditsch?utm_source=medium&amp;utm_medium=referral">Daniel Schludi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have not had a chance to go through the previous articles of this series, I am working on building an end-to-end audio classifier, in the preceding articles I have covered, an introduction of the data we would be working with and feature extraction. As part of this article, we will be working on building a baseline model that would work on the features we have generated.</p><ul><li><a href="https://blog.jovian.com/building-an-audio-classifier-813a1d6cde46">Building an audio classifier</a></li><li><a href="https://blog.jovian.com/building-an-audio-classifier-part-2-a2cf3cca8508">Building an audio classifier (Part 2)</a></li></ul><p>Ready to roll?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBpGWitbFZflfSUYuZ9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FBpGWitbFZflfSUYuZ9%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMXo0bTV5a285Znp6Zjg1OGJwanAwMTF0dDdtYnoyOGUxbGpyY2d4ciZlcD12MV9naWZzX2dpZklkJmN0PWc%2FBpGWitbFZflfSUYuZ9%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="363" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3adc02048a2e7c8a20f23b21df942f/href">https://medium.com/media/3f3adc02048a2e7c8a20f23b21df942f/href</a></iframe><p>In the last article, we created MFCC features for some audio samples, we will now do it for all samples in our data frame. As we saw MFCC features are of the shape (n_mfcc, number of time frames divided by hop length). Since our data has 7442 samples our feature set would have a shape of (7442,216)</p><pre>#Create a new datafrane for MFCC features.<br>df = pd.DataFrame(columns=[&#39;fea&#39;])<br>#iterate over the entire dataset to calculate mean of MFCC features.<br>counter = 0<br>for index,path in enumerate(data.path):<br>    audio , sampling_rate = librosa.load(path<br>                                  ,duration=2.5<br>                                  ,sr=44100<br>                                  ,offset=0.5)<br>    sampling_rate = np.array(sampling_rate)<br>    mfcc = np.mean(librosa.feature.mfcc(y=audio, sr=sampling_rate, n_mfcc = 13),axis=0)<br>    df.loc[counter] = [mfcc]<br>    counter = counter + 1<br>print(len(df))<br>df.head()<br>df = pd.concat([data,pd.DataFrame(df[&#39;fea&#39;].values.tolist())],axis=1)<br>#Fill empty values with 0<br>df = df.fillna(0)<br>print(df.shape)<br></pre><p>Next, as per standard model training practices, we would split the dataset into train and test sets and normalize the data to avoid some features from overpowering the others.</p><pre>#Splitting data to train &amp; test, normalising the data<br>X_train, X_test, y_train, y_test = train_test_split(df.drop([&#39;path&#39;,&#39;labels&#39;],axis=1)<br> , df.labels<br> , test_size=0.25<br> , shuffle=True<br> , random_state=42<br> )<br>X_train.shape<br>mean = np.mean(X_train,axis=0)<br>std = np.std(X_train,axis=0)<br>X_train = (X_train - mean)/std<br>X_test = (X_test - mean)/std</pre><p>Next, we convert the labels into integers and initialize an LGBM classifier.</p><pre>le = LabelEncoder()<br>y_train = le.fit_transform(y_train)<br>y_test = le.transform(y_test)<br>clf = LGBMClassifier(<br>    n_estimators=50,<br>    random_state=72,<br>    extra_trees=True,<br>    min_gain_to_split = 0.2,<br>    min_data_in_leaf = 10<br>)<br>%%time<br>clf.fit(<br>    X_train, y_train, <br>    eval_set=[(X_test,y_test)],<br>    callbacks=[early_stopping(100)]<br>)<br>predictions = clf.predict(X_test)<br>from sklearn.metrics import accuracy_score<br>acc = accuracy_score(y_test,predictions)<br>print(acc)</pre><p>The model has an accuracy of 36% on test data, so certainly there is room for a lot of improvement, which I would work on. The intention behind this series of articles was to get my hands dirty with working on audio data and build a baseline model, which I think I have fairly achieved.</p><p>You can refer to my notebook here:</p><p><a href="https://www.kaggle.com/code/aliphya/building-an-audio-classifier/notebook">Building an audio classifier</a></p><p>If you have enjoyed reading this series, and have suggestions of other case studies you would want me to cover, do let me know. Thanks for reading along, have a great day! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf80a833ace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an audio classifier (Part 2)]]></title>
            <link>https://gghantiwala.medium.com/building-an-audio-classifier-part-2-a2cf3cca8508?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2cf3cca8508</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[mfcc]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 15:04:27 GMT</pubDate>
            <atom:updated>2023-08-18T05:42:31.657Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science</h4><h3>Building an Audio Classifier (Part 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iY22T8fvzdSbIUTx" /><figcaption>Photo by <a href="https://unsplash.com/@cdx2?utm_source=medium&amp;utm_medium=referral">C D-X</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have been sharing my journey of building an audio classifier through Medium posts, so far I have covered how to read audio data, the link to the article is below. Going through it, before you read this article would give you useful context on the data we would be working with as part of this case study.</p><p><a href="https://gghantiwala.medium.com/building-an-audio-classifier-813a1d6cde46">Building an audio classifier</a></p><p>With that introduction, let’s get going with today’s article.</p><p>An audio file can be represented as amplitude on the y-axis and time on the x-axis. The sampling rate is the information/number of samples per second. The default sampling rate, librosa uses is 22050 Hz i.e. 20KHz because that’s the highest frequency humans can hear. Let’s see how different sampling rates can affect the audio.</p><p>Firstly, we will use a sampling rate of 4000 Hz</p><pre>#A happy sample at a SR = 4000<br>SAMPLE_RATE = 4000<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_HAP_HI.wav&#39;<br>audio , sampling_rate = librosa.load(v_path,sr=SAMPLE_RATE)<br>plt.figure(figsize=(15,5))<br>librosa.display.waveshow(audio , sr = sampling_rate)<br>ipd.Audio(v_path,rate=4000)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*lshxfy411LMSpU6nivdryQ.png" /><figcaption>Image by Author</figcaption></figure><p>Next, let’s try a sampling rate of 1000 Hz</p><pre>#A happy sample at a SR = 1000<br>SAMPLE_RATE = 1000<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_HAP_HI.wav&#39;<br>audio , sampling_rate = librosa.load(v_path,sr=SAMPLE_RATE)<br>plt.figure(figsize=(15,5))<br>librosa.display.waveshow(audio , sr = sampling_rate)<br>ipd.Audio(v_path,rate=1000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*3TyiStAxaXBYFa8wabJOtw.png" /><figcaption>Image by Author</figcaption></figure><p>Lastly, let’s take an extreme example of a sampling rate of 10 Hz</p><pre>SAMPLE_RATE = 10<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_HAP_HI.wav&#39;<br>audio , sampling_rate = librosa.load(v_path,sr=SAMPLE_RATE)<br>plt.figure(figsize=(15,5))<br>librosa.display.waveshow(audio , sr = sampling_rate)<br>ipd.Audio(v_path,rate=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*_CRnoCFvqqYZK2gr8b2ASQ.png" /><figcaption>Image by Author</figcaption></figure><blockquote><em>Observations from this exercise:</em></blockquote><p><strong>As we reduce the sampling rate, we notice that the audio becomes blurry, hence we can consider the sampling rate in audio to be like the pixels in an image, or the video quality on Youtube, naturally 1080 px would stream higher quality video than 720 px.</strong></p><p>The feature we would be extracting is <strong>MFCC</strong>.</p><blockquote>The full form of MFCC is Mel-frequency cepstral coefficients. It is a frequency domain feature, and you can consider it as an x-ray of your mouth, as in the sound that comes out of your tract. (this analogy is courtesy: <a href="https://www.kaggle.com/code/ejlok1/part-2-extracting-audio-features/notebook">https://www.kaggle.com/code/ejlok1/part-2-extracting-audio-features/notebook</a>)</blockquote><p>In case you want a detailed explanation of the mathematics behind MFCC, you can refer to this excellent blog: <a href="https://medium.com/prathena/the-dummys-guide-to-mfcc-aceab2450fd">https://medium.com/prathena/the-dummys-guide-to-mfcc-aceab2450fd</a></p><p>We will use the librosa library which provides us a method to generate the MFCC feature in a single line. The below code would generate MFCC for happy audio.</p><pre>SAMPLE_RATE = 22050<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_HAP_HI.wav&#39;<br>audio , sampling_rate = librosa.load(v_path,sr=SAMPLE_RATE)<br>mfcc = librosa.feature.mfcc(y=audio, sr=SAMPLE_RATE, n_mfcc = 5)<br>plt.figure(figsize=(12, 6))<br>plt.subplot(3,1,1)<br>librosa.display.specshow(mfcc)<br>plt.ylabel(&#39;MFCC&#39;)<br>plt.colorbar()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*fG6UsSdM0DBcLEC6aCwKfw.png" /><figcaption>Image by Author</figcaption></figure><p>Similarly, in the next snippet, we change the audio sample.</p><pre>SAMPLE_RATE = 22050<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_DIS_LO.wav&#39;<br>audio , sampling_rate = librosa.load(v_path,sr=SAMPLE_RATE)<br>mfcc = librosa.feature.mfcc(y=audio, sr=SAMPLE_RATE, n_mfcc = 5)<br>plt.figure(figsize=(12, 6))<br>plt.subplot(3,1,1)<br>librosa.display.specshow(mfcc)<br>plt.ylabel(&#39;MFCC&#39;)<br>plt.colorbar()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*u-TxzaBciK3V--qAA9KE2Q.png" /><figcaption>Image by Author</figcaption></figure><p>We can see a difference between the two MFCC features the first one being a Happy audio and the second one being a disgust emulating audio. Though, I cannot pinpoint what exactly is the difference, as long as we have a difference it can help our classifier to work with them.</p><p>Like MFCC, there are many features we can work with, but I want to first build a baseline model with MFCC before I deep dive into the n number of features available for audio data. In the next article, I would work on building the classifier. Stay Tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2cf3cca8508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an audio classifier]]></title>
            <link>https://gghantiwala.medium.com/building-an-audio-classifier-813a1d6cde46?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/813a1d6cde46</guid>
            <category><![CDATA[program]]></category>
            <category><![CDATA[classifier]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 03:04:24 GMT</pubDate>
            <atom:updated>2023-08-18T05:40:26.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science</h4><h3>Building an Audio Classifier (Part 1)</h3><h4>Get started from scratch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LHm7RtlM7hhzzGJ-" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As part of this article, we would try to build an audio classifier. The steps for the same would be:</p><p>1) <em>Data exploration</em></p><p>2) <em>Feature Extraction</em></p><p>3) <em>Model building.</em></p><p>Each of these steps would be covered in separate articles, since this is part 1 we would work on data exploration in this article.</p><p>This is my early attempt at working with audio data and this work is heavily inspired by: <a href="https://www.kaggle.com/code/ejlok1/audio-emotion-part-1-explore-data">https://www.kaggle.com/code/ejlok1/audio-emotion-part-1-explore-data</a></p><p>I will try to note down my learnings along with the code, if you like the article please do upvote! :)</p><p>With the introduction aside, let’s get to work.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLSRBzSMN4JCFG1AkFd%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLSRBzSMN4JCFG1AkFd%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLSRBzSMN4JCFG1AkFd%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/24919749fb807963b0272b60b654666e/href">https://medium.com/media/24919749fb807963b0272b60b654666e/href</a></iframe><p>We’ll start by loading the Python libraries we would need as part of the notebook. I’ll provide info about the libraries as we use them in code.</p><pre>import numpy as np # linear algebra<br>import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)<br>import os<br>import seaborn as sns<br>import librosa<br>import librosa.display<br>import matplotlib.pyplot as plt<br>import IPython.display as ipd</pre><p>Information about the data (from their official GitHub page: <a href="https://github.com/CheyneyComputerScience/CREMA-D">https://github.com/CheyneyComputerScience/CREMA-D</a>)</p><p>CREMA-D (Crowd-sourced Emotional Multimodal Actors Dataset) Summary CREMA-D is a data set of 7,442 original clips from 91 actors. These clips were from 48 male and 43 female actors between the ages of 20 and 74 coming from a variety of races and ethnicities (African American, Asian, Caucasian, Hispanic, and Unspecified).</p><p>Actors spoke from a selection of 12 sentences. The sentences were presented using one of six different emotions (Anger, Disgust, Fear, Happy, Neutral, and Sad) and four different emotion levels (Low, Medium, High, and Unspecified).</p><p>Participants rated the emotion and emotion levels based on the combined audiovisual presentation, the video alone, and the audio alone. Due to the large number of ratings needed, this effort was crowd-sourced and a total of 2443 participants each rated 90 unique clips, 30 audio, 30 visual, and 30 audio-visual. 95% of the clips have more than 7 ratings.</p><pre>#Looking at the file paths.<br>PATH = &quot;/kaggle/input/cremad/AudioWAV&quot;<br>dir_list = os.listdir(PATH) #lists the files within a directory/folder<br>dir_list.sort()<br>print(dir_list[0:10])</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlO26H42BxIRGUVydgi7Bw.png" /><figcaption>Image by Author</figcaption></figure><p>The data is not explicitly labeled, but if you look at the file paths you’d see they mention the emotion, for example in the file: ‘1001_DFA_ANG_XX.wav’ we see that it has ANG within the file path, which means it represents the emotion of anger. We’ll leverage this information to generate the labels below.</p><pre>#Let&#39;s generate labels<br>emot_labels = []<br>path = []<br>for i in dir_list:<br>    part = i.split(&#39;_&#39;)<br>    path.append(PATH + i)<br>    if part[2] == &#39;ANG&#39;:<br>        emot_labels.append(&#39;angry&#39;)<br>    elif part[2] == &#39;DIS&#39;:<br>        emot_labels.append(&#39;disgust&#39;)<br>    elif part[2] == &#39;FEA&#39;:<br>        emot_labels.append(&#39;fear&#39;)<br>    elif part[2] == &#39;HAP&#39;:<br>        emot_labels.append(&#39;happy&#39;)<br>    elif part[2] == &#39;NEU&#39;:<br>        emot_labels.append(&#39;neutral&#39;)<br>    elif part[2] == &#39;SAD&#39;:<br>        emot_labels.append(&#39;sad&#39;)<br>    else:<br>        emot_labels.append(&#39;unknown&#39;)</pre><p>Next, we create a data frame that has one column of the file path and the other of the corresponding label.</p><pre>data = pd.DataFrame(emot_labels,columns=[&#39;labels&#39;])<br>data = pd.concat([data,pd.DataFrame(path,columns=[&#39;path&#39;])],axis=1)<br>data.labels.value_counts()</pre><p>Let’s listen to some samples now using the librosa library. Librosa package in Python is widely used for audio analysis. We would also display the waveform of the audio using the IPython display library and the librosa.display package.</p><pre># An angry sample<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_ANG_HI.wav&#39;<br>audio , sampling_rate = librosa.load(v_path)<br>plt.figure(figsize=(15,5))<br>librosa.display.waveshow(audio , sr = sampling_rate)<br>ipd.Audio(v_path)</pre><p>I was not able to link the audio output here, but you could clone my notebook and run it to see the results.</p><p>The output would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4Jf0mjFEHE-teAkQd2XWQ.png" /><figcaption>Image by Author</figcaption></figure><p>Let’s load another sample, this time in a different emotion.</p><pre>#A happy sample<br>v_path = &#39;/kaggle/input/cremad/AudioWAV/1001_IEO_HAP_HI.wav&#39;<br>audio , sampling_rate = librosa.load(v_path)<br>plt.figure(figsize=(15,5))<br>librosa.display.waveshow(audio , sr = sampling_rate)<br>ipd.Audio(v_path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpcgzECyYmC3SExeWe04yw.png" /><figcaption>Image by Author</figcaption></figure><p>Observations from the data:</p><p>Listening to the above two samples of the same sentence in two different emotions we can clearly hear the difference, also the waveforms are different. It would be interesting to see what features we can extract from this data.</p><p>The audio is only for 2 seconds, at has some silence at the start and end of the audio.</p><p>Link to my notebook which you can run to replicate the results.</p><p><a href="https://www.kaggle.com/code/aliphya/building-an-audio-classifier-pt-1">https://www.kaggle.com/code/aliphya/building-an-audio-classifier-pt-1</a></p><p>I will continue working on the next parts of the article and link them here.</p><p>Happy coding! Toodaloo!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYjBucRKAAXqKMiAVMJ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYjBucRKAAXqKMiAVMJ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FYjBucRKAAXqKMiAVMJ%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/a35fa92e5937c2a74624089ba16aa702/href">https://medium.com/media/a35fa92e5937c2a74624089ba16aa702/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=813a1d6cde46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resources that would help you get the AWS Cloud Practitioner certificate.]]></title>
            <link>https://gghantiwala.medium.com/resources-that-would-help-you-get-the-aws-cloud-practitioner-certificate-364aba414842?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/364aba414842</guid>
            <category><![CDATA[ccp]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 07:50:40 GMT</pubDate>
            <atom:updated>2023-07-13T07:50:40.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-TfkTDrTXRu--zyM" /><figcaption>Photo by <a href="https://unsplash.com/de/@burntime?utm_source=medium&amp;utm_medium=referral">Alex Kulikov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>If you have been wondering how to begin your cloud journey, getting a certification could be a really good start. Certifications give you the right mix of theory and practical exposure to get your hands dirty and come with a respectable market value. Out of all the major cloud providers, AWS has the largest market share, which means there are in general more companies using AWS than Azure or GCP, that gives us even more reason to get a good grip on AWS, doesn’t it? As promised in the title, let me give you the resources that helped me get the certification and later on in the blog I’ll give you some pointers regarding the exam as well.</p><h3>Resources:</h3><p>AWS runs a <strong><em>skill builder program</em></strong> which I used to gain introductory information about the system and the certification. The program is sponsored by AWS.</p><p>Link: <a href="https://skillbuilder.aws/">https://skillbuilder.aws/</a></p><p>Once I went through the above-mentioned program, I tried to <strong><em>practice as many real exam questions</em></strong>, as the Internet provided me for free :P Linking them below</p><ol><li><a href="https://www.youtube.com/watch?v=IvvD13aNO68&amp;list=PL_0RK_1F4sTDNZOzu4aQ0h7RBA6tPwuUj">https://www.youtube.com/watch?v=IvvD13aNO68&amp;list=PL_0RK_1F4sTDNZOzu4aQ0h7RBA6tPwuUj</a></li><li><a href="https://www.w3schools.com/aws/aws_quiz.php">https://www.w3schools.com/aws/aws_quiz.php</a></li><li><a href="https://www.examtopics.com/exams/amazon/aws-certified-cloud-practitioner/">https://www.examtopics.com/exams/amazon/aws-certified-cloud-practitioner/</a></li></ol><p>AWS also has really good <strong>documentation</strong> of its own, for every incorrect answer on the test questions, I just went through their documentation to gain further insight into why my answer was incorrect.</p><p>Link: <a href="https://aws.amazon.com/certification/certified-cloud-practitioner/">https://aws.amazon.com/certification/certified-cloud-practitioner/</a></p><p><strong><em>Course on Udemy by Stephane Maarek.</em></strong></p><p>I personally have taken other courses from this instructor and can vouch for his teaching ability and technical skills, you could take this course if you wanted a further deep dive.</p><p>Link: <a href="https://www.udemy.com/course/aws-certified-cloud-practitioner-new/">https://www.udemy.com/course/aws-certified-cloud-practitioner-new/</a></p><h3>About the exam:</h3><p>The exam can be taken online through Pearson Vue or from offline centers near you, you’ll get the list of offline centers when you are booking the exam.</p><p>The exam duration is of 90 minutes and you’ll have to answer 65 multiple-choice questions(these include questions that can have single or multiple answers)</p><p>To pass the certificate you’d have to have at least 70% of your answers correct.</p><p>If you are taking an online proctored exam by Pearson Vue for the first time, I suggest you go through the below video before the exam.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhV_DpwpzNZI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhV_DpwpzNZI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhV_DpwpzNZI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c633eb35c6312b20677b270a59f3cbfa/href">https://medium.com/media/c633eb35c6312b20677b270a59f3cbfa/href</a></iframe><p>Thanks for reading along, until next time!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fm9eG1qVjvN56H0MXt8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fm9eG1qVjvN56H0MXt8%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMjV5eGQ5Mnh4NDI2dm9iY2lvdzJmaWQ2a2s1dHUwMnJyZHhkNHgyZyZlcD12MV9naWZzX2dpZklkJmN0PWc%2Fm9eG1qVjvN56H0MXt8%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/c95ee00fac26bb89f08cbdb0a138c8ae/href">https://medium.com/media/c95ee00fac26bb89f08cbdb0a138c8ae/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364aba414842" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Basics Part I]]></title>
            <link>https://gghantiwala.medium.com/python-basics-part-i-62a9ff22a417?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/62a9ff22a417</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Mon, 01 May 2023 13:12:27 GMT</pubDate>
            <atom:updated>2023-05-08T04:44:24.790Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why do we write if __name__ == ‘__main__’</h4><p>Ever wondered why you see the below code in Python programs?</p><pre>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>If you have the above question in your mind, you have clicked on the right article.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQuTOdlwvMl5lHKbpRC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQuTOdlwvMl5lHKbpRC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQuTOdlwvMl5lHKbpRC%2Fgiphy-downsized-large.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/3c6b8f6421da5e30b0b59b6d236c24bc/href">https://medium.com/media/3c6b8f6421da5e30b0b59b6d236c24bc/href</a></iframe><p>Now, let’s first get our basics correct: before any Python program runs, python assigns some values to certain variables. The variable ‘__name__’ specifies the name of the script that is currently being executed.</p><p>When the script/module running is the current script, the variable would be assigned the value of ‘__main__’.</p><p>So what, the below piece of code would do when the script(basics.py) is executed is run everything written in the main function.</p><pre>#basics.py<br>def main():<br>    pass<br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>The variable ‘__name__’ allows us to model the execution of a program based on where it is being called from. To drive my message home, consider the below two scripts, our original basics.py, and second.py</p><pre>#basics.py<br>def main():<br>    print(&#39;Script basics.py is calling me&#39;)<br>if __name__ == &#39;__main__&#39;:<br>    main()<br>else:<br>    print(&#39;Script second.py is calling me&#39;)</pre><pre>#second.py<br>import basics</pre><p>Note that in the second.py we have just written a single statement to import basics which is equivalent to saying that we want to run the code present in basics.py through second.py</p><p>Now let’s see the output when we run basics.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*WJVNnnz3r1FE8dxg_au1dw.png" /></figure><p>And we get the following output when we run second.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*l1aNPTrmCJrYTXyr91tC8g.png" /></figure><p>In conclusion, ‘__name__’ is a variable that is assigned a value of ‘__main__’ by Python when the current script is being executed.</p><p>The code below should clear any doubts you might still have about the variable.</p><pre>#second.py<br>import basics<br>print(__name__)<br>print(basics.__name__)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*e6Y8Ts7FM-eUuDwljwRNQg.png" /></figure><p>I hope you found the article useful, have a great day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62a9ff22a417" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django: Restricting Pages and creating a registration form]]></title>
            <link>https://gghantiwala.medium.com/django-restricting-pages-and-creating-a-registration-form-cfb124d1fe0a?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfb124d1fe0a</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 06:57:35 GMT</pubDate>
            <atom:updated>2023-05-06T06:31:00.499Z</atom:updated>
            <content:encoded><![CDATA[<p>Django is simpler than it seems!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMiH0Llr_MSpfG_H" /><figcaption>Photo by <a href="https://unsplash.com/@writecodenow?utm_source=medium&amp;utm_medium=referral">Boitumelo Phetla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Introduction:</em></p><p>In continuation to my last blog where I created a login and logout mechanism using Django, in this article I would be creating the registration form for signing up a new user and exploring how we can restrict access to certain web pages.</p><p>Linking my last article, in case you would want to have a look.</p><p><a href="https://gghantiwala.medium.com/django-sign-in-and-logout-tutorial-for-beginners-1a5612933434">Django: Sign-in and Logout Tutorial for Beginners</a></p><p><em>Restricting user access to web applications:</em></p><p>You would want to control the access a user has on your application, say you would want to allow only the admin of a group to add or remove members, or you would only want people who are logged in to your application to be able to create, edit or delete groups.</p><p>You could do this simply, by using a built-in decorator in Django. A decorator is simply a way you can add functionality to a function without changing it. For example, say you have a function to create a room in your code, you would use Django’s built-in decorator: <strong><em>login_required </em></strong>to restrict the user from creating a room without logging in.</p><p><em>Code in Action</em>:</p><pre><br>from django.contrib.auth.decorators import login_required<br>@login_required(redirect_field_name=&quot;{% url &#39;login&#39; %}&quot;)<br># The decorator login_required would check if the user is logged in and if not<br># redirect the user to the login page.<br>def create_room(request):<br>    &#39;&#39;&#39;Function to create a room/group&#39;&#39;&#39;</pre><p><em>Creating a registration page for a user to sign up for your web app:</em></p><p>We would use Django’s <strong><em>UserCreationForm</em></strong> module which inherits from the ModelForm class. The module allows us to create a new user. If the user is sending data to the form i.e the method is POST, we check if the form is valid and then save the user details, i.e username(after lowercasing) and the user’s entered password. We have written this function in our <strong>views.py</strong> file. I have explained the entire file structure of a typical Django project in my previous post <a href="https://medium.com/jovianml/django-sign-in-and-logout-tutorial-for-beginners-1a5612933434">here</a>.</p><p>Next, we create a <strong>register.html</strong> file where we would define how we would want to render the registration page. First, we are extending, the template from main.html and creating a form within the {%block content%}, (this again has been explained in my previous post). In the form, we are setting the action parameter to our register url[see urls.py linked below where we have added the reference to the link with the name ‘register’]. We are then passing a csrf token, [used to prevent Cross-Site Request Forgery] and rendering the UserCreationForm, next, we have a <strong>submit</strong> button and we are redirecting the user to the login page if they have already signed up to our web app.</p><p><em>Below is the code in action:</em></p><pre># views.py: Function to register user <br>def registerPage(request):<br>    form = UserCreationForm()<br>    if request.method == &quot;POST&quot;:<br>        form = UserCreationForm(request.POST)<br>        if form.is_valid():<br>            user = form.save(commit=False)<br>            user.username = user.username.lower()<br>            user.save()<br>            login(request, user)<br>            return redirect(&quot;home&quot;)<br>        else:<br>            messages.error(request, &quot;An error occour  during registration&quot;)</pre><pre># register.html<br><br>{% extends &#39;main.html&#39; %}<br><br>{% block content %}<br>&lt;div&gt;<br>  &lt;form action=&quot;{% url &#39;register&#39; %}&quot; method=&quot;POST&quot;&gt;<br>    {% csrf_token %}<br><br>    {{ form.as_p }}<br><br>    &lt;input type=&quot;submit&quot; value=&quot;Register&quot; /&gt;<br>  &lt;/form&gt;<br><br>  &lt;p&gt;Already signed up yet?&lt;/p&gt;<br>  &lt;a href=&quot;{% url &#39;login&#39; %}&quot;&gt;Login&lt;/a&gt;<br>&lt;/div&gt;<br>{% endblock content %}</pre><pre># urls.py <br>from django.urls import path, include<br>from . import views<br><br>urlpatterns = [<br>    path(&quot;accounts/&quot;, include(&quot;django.contrib.auth.urls&quot;)),<br>    path(&#39;register/&#39;,views.registerPage,name=&#39;register&#39;),<br>    path(&#39;&#39;,views.home,name=&#39;home&#39;),<br>    path(&#39;room/&lt;str:pk&gt;/&#39;,views.room,name=&#39;room&#39;),<br>    path(&#39;create-room/&#39;,views.create_room,name=&#39;create-room&#39;),<br>    path(&#39;update-room/&lt;str:pk&gt;/&#39;,views.update_room,name=&#39;update-room&#39;),<br>    path(&#39;delete-room/&lt;str:pk&gt;/&#39;,views.delete_room,name=&#39;delete-room&#39;)<br>]</pre><p>You can also extend the UserCreationForms and create a custom form that allows you to include any fields like the email address of a user. The standard user creation form takes in only the username and password of a user as input to register a person to your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-fWbiWz2V0mAsReiU6uwA.png" /><figcaption>Image by Author.</figcaption></figure><p><em>Conclusion:</em></p><p>In conclusion, all in all, Django provides a good layer of encapsulation making a beginner like me feel at home. We used a decorator today ‘login_required’ which forces a user to log in before he can access certain functionalities on your webpage and used the UserCreationForms to create a basic user registration form.</p><p><em>Shameless Self-Promotion:</em></p><p>I have written some articles on automation using Python, linking them here, in case you would want to have a look :P</p><ul><li><a href="https://blog.jovian.com/job-suggesting-python-script-b4e9e39bca1">Job suggesting python script</a></li><li><a href="https://blog.jovian.com/automating-memory-cleanup-using-python-1ada92fb2399">Automating Memory Cleanup Using Python</a></li><li><a href="https://blog.jovian.com/how-to-make-python-read-you-a-book-458dcd877ec">How to make Python read you a book!</a></li><li><a href="https://gghantiwala.medium.com/let-the-quotes-motivate-you-a59f4a3b59ff">Let the quotes motivate you</a></li></ul><p><em>Thanks for reading along, have fun Pythoning :)</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FykWYTFReBKN8zGqkXZ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FykWYTFReBKN8zGqkXZ%2Fgiphy-downsized-large.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FykWYTFReBKN8zGqkXZ%2Fgiphy-downsized-large.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/30e90f028ae62223bd168a45c605d8c2/href">https://medium.com/media/30e90f028ae62223bd168a45c605d8c2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfb124d1fe0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django: Sign-in and Logout Tutorial for Beginners]]></title>
            <link>https://gghantiwala.medium.com/django-sign-in-and-logout-tutorial-for-beginners-1a5612933434?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5612933434</guid>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 11:57:10 GMT</pubDate>
            <atom:updated>2023-05-08T04:44:42.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuCX1mr1q_3gQt4jFhW9-Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@faisaldada?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Faisal</a> on <a href="https://unsplash.com/photos/BI465ksrlWs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>Table of Contents:</blockquote><blockquote><a href="#1538"><em>Introduction</em></a></blockquote><blockquote><a href="#4719"><em>Installations</em></a></blockquote><blockquote><a href="#3b54"><em>Setting up the main code</em></a></blockquote><blockquote><a href="#cd12"><em>Final Result</em></a></blockquote><blockquote><a href="#f81b"><em>Conclusion</em></a></blockquote><blockquote><a href="#9ba8"><em>Shameless Self-Promotion</em></a></blockquote><p><strong>Introduction:</strong></p><p>In my pursuit to master the Python language, I have already dabbled my hands with writing scripts for automating manual tasks, and to do something different for this weekend I decided to build a web application using Python. After some research, I found that Django is a framework that would allow me to do the same. Though I was not able to build an entire application, I managed to create a simple sign-in and logout functionality using the auth package in Django, which I thought I should share with you as it is really simple, and anybody can do it. I would be adding other functionalities as well to my application and writing about them, so if you like this article, do stay tuned for more.</p><p>Without further ado, let’s get the ball rolling, shall we?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTHuL9YrTFvJYAKGVmX%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTHuL9YrTFvJYAKGVmX%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FTHuL9YrTFvJYAKGVmX%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/924330ccb2b26b1e747f45aa550b016c/href">https://medium.com/media/924330ccb2b26b1e747f45aa550b016c/href</a></iframe><p><strong>Installations:</strong></p><p>We will first install a virtual env in which we would install Django.</p><pre>pip3 install virtualenv #Installing <br>virtualenv env # Creating a virtual env named &#39;env&#39;<br>env/scripts/activate #Activating the virtual env.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*nwwL-KtCGTrgWT16Pa52mw.png" /><figcaption>Image by Author</figcaption></figure><p>Once you activate the virtual environment, you would see the name of the environment in round brackets before your command line, as above.</p><p>Next, install Django and start the server.</p><pre>pip3 install django<br>django-admin startproject project_name #Creates a folder with your project name and all boiler plate files.<br>#In my case project_name is GroupStudy<br>python manage.py runserver #Start the server</pre><p>On starting the server, you would be able to see the below on your command prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_uhwWeZpHUZX9mFXQirQA.png" /><figcaption>Image by Author</figcaption></figure><p>On viewing the localhost(<a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>), in your browser, you should be able to see the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*jic2iz6XizIIN2w7h5j0tA.png" /><figcaption>Image by Author.</figcaption></figure><p>If you see the above page on your browser, it means you have successfully installed Django.</p><p>I am using VisualStudioCode as my code editor, you can use anything that suits you like Notepad++, or Atom. The project structure you would see would be as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*8YT4HxNQJTdHqJx7WmxelA.png" /><figcaption>Image by Author.</figcaption></figure><p><strong>Setting up the main code:</strong></p><p>Create a folder named ‘templates’ and the below HTML files within the folder. I have added comments within the code blocks to make it easy to understand.</p><pre>#main.html: Boiler plate html code<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&#39;utf-8&#39;&gt;<br>    &lt;meta http-equiv=&#39;X-UA-Compatible&#39; content=&#39;IE=edge&#39;&gt;<br>    &lt;title&gt; Group Study&lt;/title&gt;<br>    &lt;meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1&#39;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    {% include &#39;navbar.html&#39; %} <br>    # we would be including login and logout buttons in the navbar, so that a user can login from any page of the application.<br>    {% block content %}<br>    <br>    {% endblock%}<br>&lt;/body&gt;<br>&lt;/html&gt;<br>#Using the include keyword we can reference one html template in another, aswe have done here.</pre><pre>#navbar.html <br>#In the navbar we have a link to take us to the homepage.<br>#Next, we first check if the user is authenticated, <br># if not we provide them an option to login.<br>&lt;a href=&quot;/&quot;&gt;<br>    &lt;h1&gt;LOGO&lt;/h1&gt;<br>&lt;/a&gt;<br>{% if user.is_authenticated%}<br>    &lt;p&gt;Hi, {{user.username}} :)&lt;/p&gt;<br>    &lt;p&gt;&lt;a href=&quot;{% url &#39;logout&#39; %}&quot;&gt;Log Out&lt;/a&gt;&lt;/p&gt;<br>{%else%}<br>    &lt;p&gt;You are not logged in&lt;/p&gt;<br>    &lt;a href=&quot;{% url &#39;login&#39; %}&quot;&gt;Login&lt;/a&gt;<br>{%endif%}<br>&lt;hr&gt;</pre><p>Within your project folder structure, within the folder project_name/base, you would find a file urls.py, add the following to it.</p><pre>from django.urls import path, include<br>from . import views<br><br>urlpatterns = [<br>    path(&quot;accounts/&quot;, include(&quot;django.contrib.auth.urls&quot;)),<br>    ]</pre><p>In the file ‘project_name/setting.py’ make the following changes:</p><p>If you see the installed apps in settings.py you should find that <strong>django.contrib.auth </strong>is added already by default, as below, we would be using the same auth package for our signing-in setup.</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;base.apps.BaseConfig&#39;,<br>]</pre><ol><li>Add <em>BASE_DIR / ‘templates’</em> which is the folder name where we have stored our HTML files so that our app knows where it has to look to render the HTML pages.</li></ol><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [<br>            BASE_DIR / &#39;templates&#39;<br>        ],</pre><p>2. We want that login as well as log out to our app redirects to the home page, for the same we would have to specify the below in the settings.py file at the end of the existing code present there.</p><pre>LOGIN_REDIRECT_URL = &quot;/&quot;<br>LOGOUT_REDIRECT_URL = &quot;/&quot; </pre><p><strong>Final Result:</strong></p><p>On completion of the above steps, you should be able to see the below on the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*TIUq_-vwdUwDok7dIlOm7g.png" /><figcaption>Image by Author</figcaption></figure><p>On clicking the login button, you would see the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*9cew7v-4tRSAMdKUYSSlYw.png" /><figcaption>Image by Author.</figcaption></figure><p>Do make a note of the changing URLs in every screenshot, we have defined in the Python script ‘urls.py’ that on calling path accounts/ auth package by Django should be invoked.</p><p>Now for logging in we would need a username and password. For the same, run the below command.</p><pre>python manage.py createsuperuser</pre><p>Now follow the prompts and add a username and password of your choosing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*OqLvzufKmgasHa3gCgQbtg.png" /><figcaption>Image by Author.</figcaption></figure><p>Using the username and password you just created try to log in to your application. You should be redirected to the home page of your application with the below message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*ugjuUAUid9tboNT6LhNWGw.png" /><figcaption>Image by Author.</figcaption></figure><p>And now you can see a logout option to sign out as well.</p><p><strong>Conclusion:</strong></p><p>In conclusion, we have used the ‘django.contrib.auth’ package to create a simple sign-in and sign-out functionality for our application.</p><p>Next, I would be covering how we can register a user directly from our application.</p><p><strong>Shameless Self-Promotion:</strong></p><p>As I mentioned at the start of this blog, I have written some articles on automation using Python, linking them here, in case you would want to have a look :P</p><ul><li><a href="https://blog.jovian.com/job-suggesting-python-script-b4e9e39bca1">Job suggesting python script</a></li><li><a href="https://blog.jovian.com/automating-memory-cleanup-using-python-1ada92fb2399">Automating Memory Cleanup Using Python</a></li><li><a href="https://blog.jovian.com/how-to-make-python-read-you-a-book-458dcd877ec">How to make Python read you a book!</a></li><li><a href="https://gghantiwala.medium.com/let-the-quotes-motivate-you-a59f4a3b59ff">Let the quotes motivate you</a></li></ul><p><strong>Thanks for reading along, have fun Pythoning :)</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVzjC1xn7ZY0Qo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FVzjC1xn7ZY0Qo%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FVzjC1xn7ZY0Qo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/d35d29771ca4b9214210cb7c054f802c/href">https://medium.com/media/d35d29771ca4b9214210cb7c054f802c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a5612933434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should read “Before the coffee gets cold”]]></title>
            <link>https://gghantiwala.medium.com/why-you-should-read-before-the-coffee-gets-cold-d5f73e803679?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f73e803679</guid>
            <category><![CDATA[time-travel]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[fiction]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 15:01:54 GMT</pubDate>
            <atom:updated>2023-02-19T15:01:54.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5R0wX45zVe8YjDvyCg-pA.jpeg" /></figure><p>Before the coffee gets cold is a novel written by Toshikazu Kawaguchi. I was first introduced to this book by the youtube channel ChalChitra Talks, and I am so glad I took up the recommendation. It took me around 2 days and some tissues to complete the book.</p><p>The book asks us what we would do if we could go to the past. Honestly, I think we have all spent some days thinking about how our life would be better, had we done something differently, how we could have saved our relationships simply by speaking our minds (and dropping our egos), how often times we completely miscalculate our priorities in life? These are mistakes we all make which is why I think everyone can resonate with the main idea of the book, what do you want to change in your past if you had the chance to go back? The book introduces a cafe Funiculi Funicula which allows you to go back to your past.</p><p>Obviously, as you would have seen in countless time travel movies, as per the principles of time if you go back to your past and change something, it would cause an almost apocalypse in the present. Basically, you cannot change your past and not expect things to go bonkers in your present, right? This is why one of the rules of traveling to the past at Funiculi Funicula is anything you do would going back to the past would in no way change the future.</p><p>I don&#39;t want to give out all the rules you would need to follow to go back in time at Funiculi Funicula because I don&#39;t want to be a spoilsport. But if you want like reading a good paced fiction novel with a dash of time travel, this book would definitely be a good read for you.</p><p>Lastly, I mentioned in the intro that I was able to finish the book with the help of some tissues, to give you a bit of context I am an emotional person but in a long time I haven’t been moved to tears by a book. This book was able to do it. Naturally, if you think about it, when people go back to their past they&#39;re bound to come back to the present with a different perspective of the situation, and sometimes what you need to do in life is just that, to look at it with a lens of hope and possibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f73e803679" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Using a Different Way to Split Your Time Series Data Improve Model Performance?]]></title>
            <link>https://gghantiwala.medium.com/can-using-a-different-way-to-split-your-time-series-data-improve-model-performance-3f5042f13dff?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5042f13dff</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[model-performance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 16:31:43 GMT</pubDate>
            <atom:updated>2022-12-22T02:57:31.628Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h4>TimeSeriesSplit by scikit-learn could save your day.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HjX07SHof-PV_uJr" /><figcaption>Photo by <a href="https://unsplash.com/@jakehills?utm_source=medium&amp;utm_medium=referral">Jake Hills</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is in continuation of my last post on the <a href="https://medium.com/jovianml/predictions-on-time-series-data-a9e32f0797a8">Predictions on Time series data</a>. As part of this, I have tried to deepen my understanding further into the subject and look at ways to improve the efficiency of a tree-based model on time series data.</p><p>When the data is not temporal/ordered you could use a random split to split your data into train and validation sets, however, this is not a good approach when working with time series data, as the ordering of data has to be considered while making a split.</p><p>There are multiple ways to split time series data, and you can try them based on your use case.</p><h4><strong>Manual Split Based on Cutoff Date:</strong></h4><p>In this split, you would simply take a small subset of the entire data as a validation set. The usual practice is to take the latest data as a validation subset and the prior data as a training subset. For example, if you have data from 1st Jan 2000 to 30 Apr 2021, you would want to take the first 4 months of 2021 as the validation set, so you would split your data at the cutoff date of 01 Jan 2021.</p><p>The reasoning behind this is that we usually want to predict the future which is not included in the train set, and how the model performs on the latest data in the train set can usually provide a fair estimate of how it would perform in the future.</p><p>Let’s look at how we can achieve this using code.</p><pre>cutoff_date = &#39;2020-06-01&#39;<br>train = tatasteel.loc[tatasteel.Date&lt;cutoff_date]<br>test = tatasteel.loc[tatasteel.Date&gt;=cutoff_date]</pre><p>We have simply mentioned the cutoff date and used the <strong><em>dataframe.loc</em></strong> method we are simply splitting the data.</p><p>Now let’s check the model performance of an unturned XGB Regressor on this split of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k72ojes8WAY1_Ef5cJjkzg.png" /><figcaption>Image by Author</figcaption></figure><p>As you can see from the graph above our model does not perform very well, and has a mean squared error of 202 on the validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*E5D7Z2VlRATTSaI2eu1c-A.png" /><figcaption>Image by Author</figcaption></figure><h4><strong>Using TimeSeriesSplit from the scikit-learn library:</strong></h4><p>[Reference: <a href="https://www.kaggle.com/code/robikscube/pt2-time-series-forecasting-with-xgboost/notebook">https://www.kaggle.com/code/robikscube/pt2-time-series-forecasting-with-xgboost/notebook</a> ]</p><p>We would use the TimeSeriesSplit function to split our data, this is similar to k-folds but as the data is temporal there is no random split, i.e test indices are higher than the train indices.</p><p>In the code below we create 5 folds of the data, since we have daily data and want to keep 6 months of data in the validation set, I have set test_size to 180. A gap of 2 signifies that the train and test sets would have a gap of 2 days between them.</p><pre>#Reference: https://www.kaggle.com/code/robikscube/pt2-time-series-forecasting-with-xgboost/notebook<br>from sklearn.model_selection import TimeSeriesSplit<br>tss = TimeSeriesSplit(n_splits=5,test_size=180,gap=2)<br>tatasteel = tatasteel.sort_index()</pre><p>Next, let’s visualize the folds.</p><pre>fig, axs = plt.subplots(5, 1, figsize=(15, 15), sharex=True)<br>fold = 0<br>for train_idx , val_idx in tss.split(tatasteel):<br>    train = tatasteel.iloc[train_idx]<br>    test = tatasteel.iloc[val_idx]<br>    train[&#39;Open&#39;].plot(ax=axs[fold],<br>                          label=&#39;Training Set&#39;,<br>                          title=f&#39;Data Train/Test Split Fold {fold}&#39;)<br>    test[&#39;Open&#39;].plot(ax=axs[fold],<br>                         label=&#39;Test Set&#39;)<br>    axs[fold].axvline(test.index.min(), color=&#39;black&#39;, ls=&#39;--&#39;)<br>    fold += 1<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*5ELZBEuZaOgkyanY2B1G3A.png" /></figure><p>In each fold, the test set of the previous fold is included in the training set of the next fold.</p><p>Let’s train the same model on the data we split using TimeSeriesSplit and view the mean squared error.</p><pre>fold = 0<br>preds = []<br>scores = []<br>for train_idx , val_idx in tss.split(tatasteel):<br>    train = tatasteel.iloc[train_idx]<br>    test = tatasteel.iloc[val_idx]<br>    <br>    train = create_datetime_features(train,&#39;Date&#39;)<br>    test = create_datetime_features(test,&#39;Date&#39;)<br>    <br>    FEATURES = [&#39;Volume&#39;, &#39;Turnover&#39;, &#39;Trades&#39;, &#39;Deliverable Volume&#39;,<br>       &#39;%Deliverble&#39;, &#39;month&#39;, &#39;year&#39;, &#39;weekday&#39;,&#39;quarter&#39;]<br>    TARGET = [&#39;Open&#39;]<br>    <br>    X_train = train[FEATURES]<br>    y_train = train[TARGET]<br>    <br>    X_test = test[FEATURES]<br>    y_test = test[TARGET]<br>    <br>    reg = XGBRegressor(base_score=0.5, booster=&#39;gbtree&#39;,    <br>                           n_estimators=1000,<br>                           early_stopping_rounds=50,<br>                           objective=&#39;reg:linear&#39;,<br>                           max_depth=3,<br>                           learning_rate=0.01)<br>    reg.fit(X_train, y_train,<br>            eval_set=[(X_train, y_train), (X_test, y_test)],<br>            verbose=100)<br>    y_pred = reg.predict(X_test)<br>    preds.append(y_pred)<br>    score = np.sqrt(mean_squared_error(y_test, y_pred))<br>    scores.append(score)</pre><pre>print(f&#39;Score across folds {np.mean(scores):0.4f}&#39;)<br>print(f&#39;Fold scores:{scores}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYEWVlTZoGwSQRPN9A6U_g.png" /><figcaption>Image by Author</figcaption></figure><p>For the different folds as you can see from the above results we managed to get the average mean squared error across the folds down to 98.9</p><h4><strong>Conclusion:</strong></h4><p>For the dataset, I was working with (<a href="https://www.kaggle.com/datasets/rohanrao/nifty50-stock-market-data">Nifty 50 Data on Kaggle</a>), splitting data using TimeSeriesSplit did help in lowering the mean squared error than splitting the data using a cutoff date.</p><p>Maybe we can further better the performance of our predictions by fine-tuning the model or using better features. Will try to include this in my next article.</p><p>Lastly. <a href="https://www.kaggle.com/code/aliphya/visualizing-the-nifty-50-and-predicting-the-prices/notebook?scriptVersionId=114283104">a link to my notebook, for your reference</a>.</p><p>Thanks for reading along :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ffxe8v45NNXFd4jdaNI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ffxe8v45NNXFd4jdaNI%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Ffxe8v45NNXFd4jdaNI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="289" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f747ce88e719be28552d375fdee25fd/href">https://medium.com/media/6f747ce88e719be28552d375fdee25fd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5042f13dff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predictions on time series data.]]></title>
            <link>https://gghantiwala.medium.com/predictions-on-time-series-data-a9e32f0797a8?source=rss-b519474fb94c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e32f0797a8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[catboost]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Alifia Ghantiwala]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 05:47:27 GMT</pubDate>
            <atom:updated>2022-11-25T13:40:20.365Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h3>Predictions On Time Series Data</h3><h4>Using the “Kaggle” March 2022 playground series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7KvvSYH4VUBe2Ke-" /><figcaption>Photo by <a href="https://unsplash.com/@aronvisuals?utm_source=medium&amp;utm_medium=referral">Aron Visuals</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Table of contents<br>☞ <a href="#97d3">Introduction</a><br>☞ <a href="#033e">A little about the data</a><br>☞ <a href="#75a3">Feature Generation</a><br>☞ <a href="#82fc">Plotting Visualizations to get a better grasp of the data</a><br>☞ <a href="#c801">Preprocessing the data</a><br>☞ <a href="#ff41">Modeling the predictions using CatBoost</a><br>☞ <a href="#12b2">Concluding Thoughts</a></p><h4>Introduction:</h4><p>Have you ever wondered how stores stock up their items? Why do the sales of firecrackers splurge during November in India? When should you plan a vacation to Hawaii? All the above questions can easily be answered by analyzing past trends.</p><p>Looking at time series data, and finding insights is the most exciting and important use case of machine learning, in my opinion. All data in the real world has time as a component. Knowing how to effectively tackle a time series helps you to uncover interesting things which are lying right in front of you.</p><p>In this article, we would work with time series data(No surprises here :P) and model predictions using the CatBoost Regressor. Get ready with python up in your arsenal and let’s go.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FzaezT79s3Ng7C%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FzaezT79s3Ng7C%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FzaezT79s3Ng7C%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e94576a8d0e9434b5f02af43c8b3d02/href">https://medium.com/media/4e94576a8d0e9434b5f02af43c8b3d02/href</a></iframe><h4>A little about the data:</h4><p>The data we would be using is from Kaggle’s March 2022 playground series. We have to predict the traffic flow in a busy US metropolitan area, columns in the dataset have information about the directions, time, and space.</p><p>Columns in the training dataset: (<a href="https://www.kaggle.com/competitions/tabular-playground-series-mar-2022/data">Reference Link</a>)</p><ul><li>row_id - a unique identifier for this instance</li><li>time - the 20-minute period in which each measurement was taken</li><li>x - the east-west midpoint coordinate of the roadway</li><li>y - the north-south midpoint coordinate of the roadway</li><li>direction - the direction of travel of the roadway. EB indicates &quot;eastbound&quot; travel, for example, while SW indicates a &quot;southwest&quot; direction of travel.</li><li>congestion - congestion levels for the roadway during each hour; the target. The congestion measurements have been normalized to the range of 0 to 100.</li></ul><p>The training data ranges from 1st April 1991 to 30 Sept 1991, and there are no missing records in the data.</p><pre>train.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Xam3ZkOTnlJHvQWWq7SgDA.png" /><figcaption>Source: Author</figcaption></figure><pre>train.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*s33zhJuuFpnA5oJn7o31DA.png" /><figcaption>Source: Author</figcaption></figure><h4>Feature Generation:</h4><p>We would next create some features from the date column we have in our data.</p><pre>def create_features(df, label=None):<br>    &quot;&quot;&quot;<br>    Creates time series features from datetime index<br>    &quot;&quot;&quot;<br>    df[&#39;date&#39;] = df.index<br>    df[&#39;hour&#39;] = df[&#39;date&#39;].dt.hour<br>    df[&#39;dayofweek&#39;] = df[&#39;date&#39;].dt.dayofweek<br>    df[&#39;quarter&#39;] = df[&#39;date&#39;].dt.quarter<br>    df[&#39;month&#39;] = df[&#39;date&#39;].dt.month<br>    df[&#39;year&#39;] = df[&#39;date&#39;].dt.year<br>    df[&#39;dayofyear&#39;] = df[&#39;date&#39;].dt.dayofyear<br>    df[&#39;dayofmonth&#39;] = df[&#39;date&#39;].dt.day<br>    df[&#39;weekofyear&#39;] = df[&#39;date&#39;].dt.weekofyear<br>    <br>    X = df[[&#39;hour&#39;,&#39;dayofweek&#39;,&#39;quarter&#39;,&#39;month&#39;,&#39;year&#39;,<br>           &#39;dayofyear&#39;,&#39;dayofmonth&#39;,&#39;weekofyear&#39;]]<br>    if label:<br>        y = df[label]<br>        return X, y<br>    return X</pre><p>In the above function, we use python’s DateTime library to extract features like the month, year, day of the week, and so on from the date column.</p><p>After feature generation, we have the following columns in our dataset.</p><pre>train.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Q1Mc5rH_m6sPBbEu5pSTVA.png" /><figcaption>Source: Author</figcaption></figure><h4>Plotting Visualizations to get a better grasp of the data:</h4><pre>month_train = train.groupby(by = [&#39;month&#39;]).sum()<br>sns.lineplot(data=month_train,x=&#39;month&#39;,y=&#39;congestion&#39;)<br>plt.title(&#39;Monthly changes in target&#39;)<br>plt.show()</pre><p>If we look at the feature “month” we generated, we see a sharp dip in traffic congestion(our target variable) in the month of June. Why would that be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*nXbnOKA70evtAw61fcdGiQ.png" /><figcaption>Source: Author</figcaption></figure><pre>hour_train = train.groupby(by = &#39;hour&#39;).sum()<br>sns.lineplot(data=hour_train,x=&#39;hour&#39;,y=&#39;congestion&#39;)<br>plt.title(&#39;Hourly changes in target&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*zObUfFlyqVQFr5X4Lu1wCQ.png" /><figcaption>Source: Author</figcaption></figure><p>A quick look at the feature “hour” tells us that traffic seems to be at its peak at around 15:00 which is afternoon 3 pm.</p><h4>Preprocessing the data:</h4><p>Just like marinating chicken is an important pre-requisite for enjoying delicious Chicken biryani, similarly preprocessing your data is an absolute must for your model to generate amazing results.</p><p>The target column is a numeric column and its values range from 0 to 100, we would Standard Scaler from sklearn to range the data between -1 and 1. We would then encode the categorical column direction using Label Encoder.</p><pre>from sklearn.preprocessing import StandardScaler<br>scaler = StandardScaler()<br>train[&#39;congestion&#39;] = scaler.fit_transform(train[[&#39;congestion&#39;]])</pre><pre>from sklearn.preprocessing import LabelEncoder<br>le = LabelEncoder()<br>train[&#39;direction&#39;] = le.fit_transform(train[&#39;direction&#39;])<br>test[&#39;direction&#39;] = le.fit_transform(test[&#39;direction&#39;])</pre><p>We will then split the data into train and validation/test sets. In time series datasets we use temporal splits, i.e we consider the most recent data as the validation set. Random splitting would not help in the case of time series data as we need the sequence of data(according to their time) to be maintained. Also by keeping the most recent data as a validation set we ensure any recent changes are captured and factored in for the model’s consideration.</p><pre>split_date = &#39;01-Aug-1991&#39;<br>data_train = train.loc[train.index &lt;= split_date].copy()<br>data_test = train.loc[train.index &gt; split_date].copy()</pre><p>In the code above, we use data from 01-April to 31-July as the training set and data from 01-Aug to 30-Sep as the validation set.</p><h4>Modeling the predictions using CatBoost:</h4><p>We would use the Catboost Regressor and optimize it using Optuna, the code for the below cells has been referenced from this <a href="https://www.kaggle.com/code/hamzaghanmi/xgboost-catboost-using-optuna">notebook by Hamza</a></p><pre>import optuna<br>from sklearn.metrics import mean_squared_error<br>def objective(trial,train_x=X_tr,train_y=y_tr,test_x=X_te,test_y=y_te):<br>    param = {<br>        &#39;loss_function&#39;: &#39;RMSE&#39;,<br>        &#39;l2_leaf_reg&#39;: trial.suggest_loguniform(&#39;l2_leaf_reg&#39;, 1e-3, 10.0),<br>        &#39;max_bin&#39;: trial.suggest_int(&#39;max_bin&#39;, 200, 400),<br>        &#39;subsample&#39;: trial.suggest_uniform(&#39;bagging_fraction&#39;, 0.4, 1.0),<br>        &#39;learning_rate&#39;: trial.suggest_uniform(&#39;learning_rate&#39;, 0.006, 0.018),<br>        &#39;n_estimators&#39;:  25000,<br>        &#39;max_depth&#39;: trial.suggest_categorical(&#39;max_depth&#39;, [5,7,9,11,13,15]),<br>        &#39;random_state&#39;: trial.suggest_categorical(&#39;random_state&#39;, [2020]),<br>        &#39;min_data_in_leaf&#39;: trial.suggest_int(&#39;min_data_in_leaf&#39;, 1, 300),<br>    }<br>    model = CatBoostRegressor(**param)  <br>    <br>    model.fit(train_x,train_y,eval_set=[(test_x,test_y)],early_stopping_rounds=200,verbose=False)<br>    <br>    preds = model.predict(test_x)<br>    <br>    rmse = mean_squared_error(test_y, preds,squared=False)<br>    <br>    return rmse<br>study = optuna.create_study(direction=&#39;minimize&#39;)<br>study.optimize(objective, n_trials=30)<br>print(&#39;Number of finished trials:&#39;, len(study.trials))<br>print(&#39;Best trial:&#39;, study.best_trial.params)</pre><p>The model was able to generate predictions with a mean average percent error of 6 which is not bad but can definitely be better. I would try to optimize the results further and add them to the blog later on.</p><h4>Concluding Thoughts:</h4><p>As part of this article,</p><p>1. We extracted features from the date column using python’s DateTime library.</p><p>2. We preprocessed the data using StandardScaler and LabelEncoder from sklearn.</p><p>3. A basic Catboost regressor with hyperparameter optimization helped to yield results with a MAPE of 6%.</p><p>If you think any of the article’s content is incorrect, please flag the same in the comment section. Thanks for reading along! <strong>May you always succeed in timing your predictions :) (pun intended!)</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FL3WZFMFFqgtxnXe4bf%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FL3WZFMFFqgtxnXe4bf%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FL3WZFMFFqgtxnXe4bf%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/cb4241f230221d3d3bcb57404120f610/href">https://medium.com/media/cb4241f230221d3d3bcb57404120f610/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e32f0797a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>