<?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 Basil K Jose on Medium]]></title>
        <description><![CDATA[Stories by Basil K Jose on Medium]]></description>
        <link>https://medium.com/@basilkjose?source=rss-a571119d1ba3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9E6NMisGYkO88cyzS6sklA.png</url>
            <title>Stories by Basil K Jose on Medium</title>
            <link>https://medium.com/@basilkjose?source=rss-a571119d1ba3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:29:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@basilkjose/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[Data Preprocessing | Natural Language Processing]]></title>
            <link>https://basilkjose.medium.com/data-preprocessing-natural-language-competition-processing-dcbbf9d014e8?source=rss-a571119d1ba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcbbf9d014e8</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[text-preprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Basil K Jose]]></dc:creator>
            <pubDate>Tue, 04 May 2021 17:23:37 GMT</pubDate>
            <atom:updated>2021-05-05T16:06:17.952Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A hands on data preprocessing steps to follow while dealing with text data for NLP modeling.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*VzhvZVKGVGynlsU0AZZQww.jpeg" /></figure><h3>Overview</h3><p>Text preprocessing is traditionally an important step for natural language processing (NLP) tasks. It transforms text into a more digestible form so that machine learning algorithms can perform better.</p><p>Data preprocessing is an important step to prepare the data to form a machine learning model can understand. There are many important steps in data preprocessing, such as data cleaning, data transformation, and feature selection. Data cleaning and transformation are methods used to remove outliers and standardize the data so that they take a form that can be easily used to create a model.</p><h3>Why You Need Data Preprocessing?</h3><p>By now, you’ve surely realized why your data preprocessing is so important. Since mistakes, redundancies, missing values, and inconsistencies all compromise the integrity of the set, you need to fix all those issues for a more accurate outcome. Imagine you are training a Machine Learning algorithm to deal with your customers’ purchases with a faulty dataset. Chances are that the system will develop biases and deviations that will produce a poor user experience.</p><p>Thus, before using that data for the purpose you want, you need it to be as organized and “clean” as possible. There are several ways to do so, depending on what kind of problem you’re tackling. Ideally, you’d use all of the following techniques to get a better data set.</p><h3>Steps For Data Preprocessing</h3><p><em>In this section, we will code common steps involved in text preprocessing.</em></p><h4>1) Lower Case</h4><p>Converting the text into lower case letters.</p><pre>sent_0 =sent_0.lower()</pre><p><strong>2) Removing all URLs from data</strong></p><p>we are removing URLs(‘http\’) from text using python regular expression.</p><pre>sent_0 = re.sub(r&quot;http\S+&quot;, &quot;&quot;, sent_1000)</pre><p><strong>3) Removing all tags from data</strong></p><p>For removing tags we use the <a href="https://pypi.org/project/beautifulsoup4/">Beautiful Soup</a> python package.</p><pre>soup = BeautifulSoup(sent_0, &#39;lxml&#39;)<br>text = soup.get_text()</pre><p><strong>4) Removing words with numbers from data</strong></p><p>we are removing words containing numbers from text using python regular expression.</p><pre>sent_0 = re.sub(&quot;\S*\d\S*&quot;, &quot;&quot;, sent_0).strip()</pre><p><strong>5)Removing special character from data</strong></p><p>we are removing all the special character(‘*,&amp;,#,@…’) from the text.</p><pre>sent_0 = re.sub(&#39;[^A-Za-z0-9]+&#39;, &#39; &#39;, sent_0)</pre><p><strong>6) Decontracting the words</strong></p><p>In this step, we are expanding English language contractions using python.</p><pre><strong>def</strong> decontracted(phrase):<br>    phrase = re.sub(r&quot;won&#39;t&quot;, &quot;will not&quot;, phrase)<br>    phrase = re.sub(r&quot;can\&#39;t&quot;, &quot;can not&quot;, phrase)<br>    phrase = re.sub(r&quot;n\&#39;t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;re&quot;, &quot; are&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;s&quot;, &quot; is&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;d&quot;, &quot; would&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;ll&quot;, &quot; will&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;ve&quot;, &quot; have&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;m&quot;, &quot; am&quot;, phrase)<br>    <strong>return</strong> phrase</pre><p><strong>7) Removing stop words</strong></p><p>stop words are words which are filtered out before or after processing of natural language data Though “stop words” usually refers to the most common words in a language, there is no single universal list of stop words used by all natural language processing tools.</p><pre>nltk.download(&#39;stopwords&#39;)<br>eng_stopwords = set(stopwords.words(&#39;english&#39;))</pre><p><strong>8) Stemming</strong></p><p>Stemming is the process of reducing a word to its word stem that affixes to suffixes and prefixes or to the roots of words known as a lemma. Stemming is important in natural language understanding (NLU) and natural language processing (NLP).</p><pre><strong>def</strong> stemmer(data):<br>  review_clean_ps = []<br>  ps = PorterStemmer()<br>  <strong>for</strong> sentance <strong>in</strong> tqdm(data[&#39;review&#39;].values):<br>    ps_stems = []<br>    <strong>for</strong> w <strong>in</strong> sentance.split():<br>      <strong>if</strong> w == &#39;oed&#39;:<br>        <strong>continue</strong><br>      ps_stems.append(ps.stem(w))  <br>     <br>    review_clean_ps.append(&#39; &#39;.join(ps_stems))   <br>  data[&#39;review&#39;]=review_clean_ps<br>  <strong>return</strong> data</pre><p><strong>9) Lemmatization</strong></p><p>Lemmatization is the process of grouping together the different inflected forms of a word so they can be analysed as a single item. Lemmatization is similar to stemming but it brings context to the words. So it links words with similar meaning to one word.</p><pre><strong>def</strong> get_wordnet_pos(treebank_tag):<br><br>    <strong>if</strong> treebank_tag.startswith(&#39;J&#39;):<br>        <strong>return</strong> wordnet.ADJ<br>    <strong>elif</strong> treebank_tag.startswith(&#39;V&#39;):<br>        <strong>return</strong> wordnet.VERB<br>    <strong>elif</strong> treebank_tag.startswith(&#39;N&#39;):<br>        <strong>return</strong> wordnet.NOUN<br>    <strong>elif</strong> treebank_tag.startswith(&#39;R&#39;):<br>        <strong>return</strong> wordnet.ADV<br>    <strong>else</strong>:<br>        <strong>return</strong> &#39;n&#39;</pre><pre>nltk.download(&#39;averaged_perceptron_tagger&#39;)<br>nltk.download(&#39;wordnet&#39;)</pre><pre><strong>def</strong> lemmatization(data):<br>  review_clean_wnl = []<br>  wnl = WordNetLemmatizer()<br>  <strong>for</strong> sentance <strong>in</strong> tqdm(data[&#39;review&#39;].values):<br>     wnl_stems = []<br>     token_tag = pos_tag(sentance.split())<br>     <strong>for</strong> pair <strong>in</strong> token_tag:<br>       res = wnl.lemmatize(pair[0],pos=get_wordnet_pos(pair[1]))<br>       wnl_stems.append(res)<br>     review_clean_wnl.append(&#39; &#39;.join(wnl_stems))<br>  data[&#39;review&#39;]=review_clean_wnl<br>  <strong>return</strong> data</pre><p><strong>10) Vectorization</strong></p><p>Word Embeddings or Word vectorization is a methodology in NLP to map words or phrases from vocabulary to a corresponding vector of real numbers which used to find word predictions, word similarities/semantics.</p><p>There are different types of vectorization techniques ,we mainly speaks about <strong>bag of words </strong>and <strong>tfidf </strong>vectorizer .</p><pre><em>#</em><strong><em>bag of words</em></strong><br>vectorizer_bow = CountVectorizer(min_df=10,ngram_range=(1,4), max_features=5000)<br>vectorizer_bow.fit(X_train.values)  <em>#fitting</em><br>x_train_bow= vectorizer_bow.transform(X_train.values) <br>x_test_bow= vectorizer_bow.transform(X_test.values)</pre><pre><em><br></em><strong><em>#tfidf</em></strong><br>tfidfvectorizer = TfidfVectorizer(min_df=10,max_features=5000)<br>text_tfidf = tfidfvectorizer.fit(X_train.values) <em>#fitting</em><br><br>X_train_tfidf =tfidfvectorizer.transform(X_train.values) <br>X_test_tfidf =tfidfvectorizer.transform(X_test.values)</pre><blockquote><em>You can find my complete solution in my </em><a href="https://github.com/basilkjose/Sentiment-Analysis-Web-Application-for-Movie-Reviews/blob/main/nlp_movie_dep.ipynb"><strong><em>Github Repository</em></strong></a><em> ,and if you have any suggestions, please contact me via </em><a href="https://www.linkedin.com/in/basil-k-jose-58b579166/"><strong><em>Linkedin</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcbbf9d014e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twint: Twitter Scraping Without Twitter’s API]]></title>
            <link>https://basilkjose.medium.com/twint-twitter-scraping-without-twitters-api-aca8ba1b210e?source=rss-a571119d1ba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca8ba1b210e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[twint]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[twitter-scraping]]></category>
            <dc:creator><![CDATA[Basil K Jose]]></dc:creator>
            <pubDate>Wed, 24 Feb 2021 14:14:42 GMT</pubDate>
            <atom:updated>2021-05-04T15:27:41.708Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hands-on guide to scraping anybody’s tweet without Twitter’s API using Twitter Intelligence Tool called TWINT</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgvP56c62vrNvb7bvIi8ew.jpeg" /></figure><h3>What is Twint ?</h3><p><a href="https://pypi.org/project/twint/">Twint</a> is an advanced tool for Twitter scrapping. We can use this tool to scrape any user’s tweets without having to use Twitter API.Twitter scraping tool written in Python that allows for scraping Tweets from Twitter profiles .</p><p>Twint utilizes Twitter’s search operators to let you scrape Tweets from specific users, scrape Tweets relating to certain topics, hashtags &amp; trends, or sort out sensitive information from Tweets like e-mail and phone numbers. I find this very useful, and you can get creative with it too.</p><p>Above all ,Twint has these<strong> major benefits:</strong></p><ul><li>Twitter API has restrictions to scrape only the last 3200 Tweets. But Twint can fetch almost all Tweets.</li><li>Set up is really quick as there is no hassle of setting up Twitter API.</li><li>Can be used anonymously without Twitter sign-up.</li><li>It’s free!! No pricing limitations.</li><li>Provides easy to use options to store scraped tweets into different formats — CSV, JSON, SQLite, and Elasticsearch</li></ul><h3>Installation</h3><p>You can install Twint using the pip command or directly from git.</p><h4>Using pip</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Ae8W1CF_E0NViNWwOyaE9w.png" /></figure><h4>Directly from Git</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*apQq0aPZAe72Hn6GO17COA.png" /></figure><h3><strong>Code Walkthrough</strong></h3><p>If you trying the following code on the notebook you may get into the error <em>“RuntimeError: This event loop is already running”</em>. To resolve this error, just run the below code in the cell.(used once to enable concurrent actions within a notebook.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*M2G7bZLFyyE1wuwfvl3_7A.png" /></figure><h4>1. Scrape the tweets of user</h4><p>If we have a Twitter username of the profile we can directly scrape the tweets of a specific user.</p><pre><em># Configure</em><br>c = twint.Config()<br>c.Limit = 1<br>c.Username = &quot;narendramodi&quot;<br><br><em># Run</em><br>twint.run.Search(c)</pre><p>First of all, we want to configure Twint. After defining all the parameters we can run and search Twint.</p><p><strong>Limit :</strong> Number of tweets to pull.</p><h4>2. Scrape the tweets between specific dates</h4><pre>c = twint.Config()<br>c.Lang = &quot;en&quot;<br>c.Username = &quot;narendramodi&quot;<br>c.Hide_output = <strong>True</strong><br>c.Since = &#39;2020-10-12&#39;<br>c.until= &#39;2021-01-20&#39;<br><em># Run</em><br>twint.run.Search(c)</pre><p><strong>since :</strong> Filter tweets from this date.</p><p><strong>until : </strong>Filter tweets upto this date.</p><h4>3. Scrape tweets for specific search strings</h4><p>We can specify different search terms to filter over tweets.</p><pre><em># Configure</em><br>c = twint.Config()<br>c.Lang = &quot;en&quot;<br>c.Hide_output = <strong>True</strong><br>c.Username = &quot;narendramodi&quot;<br>c.Search = [&#39;India&#39;,&#39;bjp&#39;]<br>c.Limit = 1<br><em># Run</em><br>twint.run.Search(c)</pre><h4>4. Scrape tweets contain Media (images or videos or both)</h4><pre><em># Configure</em><br>c = twint.Config()<br>c.Username = &quot;narendramodi&quot;<br>c.Limit = 1<br><em>#c.Images= True</em><br><em>#c.Vidoes = True</em><br>c.Media = <strong>True</strong><br><br><em># Run</em><br>twint.run.Search(c)</pre><p><strong>Images :</strong> Display only tweets with images .</p><p><strong>Videos :</strong> Display only tweets with videos.</p><p><strong>Media :</strong> Display tweets with only images or videos.</p><h4>5. Scrape popular tweets of user</h4><pre><em># Configure</em><br>c = twint.Config()<br>c.Username = &quot;narendramodi&quot;<br>c.Limit = 1<br>c.Popular_tweets = <strong>True</strong><br><br><em># Run</em><br>twint.run.Search(c)</pre><p><strong>Popular_tweets :</strong> Scrape popular tweets ,most recent(default=False)</p><h4>6. Filter tweets based on min likes, min retweets, and min replies</h4><pre>c = twint.Config()<br>c.Username = &quot;narendramodi&quot;<br>c.Limit = 1<br>c.Min_likes = 5000<br>c.Min_replies = 1000<br>c.Min_retweets = 100<br><br>twint.run.Search(c)</pre><p><strong>Min_likes : </strong>Filter tweets by minimum number of likes.</p><p><strong>Min_retweets :</strong> Filter tweets by minimum number of retweets.</p><p><strong>Min_replies :</strong> Filter tweets by minimum number of replies.</p><h4>7. Scrape tweets contain specific hashtags</h4><p>In search terms we can search over hashtags.</p><pre>c = twint.Config()<br>c.Search = &#39;#blacklivesmatter&#39;<br>c.Limit = 20<br>twint.run.Search(c)</pre><h4>8. Store as Pandas DataFrame</h4><p>We can store entire scrapped data into dataframe.</p><pre>c = twint.Config()<br>c.Limit = 1<br>c.Username = &#39;narendramodi&#39;<br>c.Pandas = <strong>True</strong><br><br>twint.run.Search(c)<br><br>Tweets_df = twint.storage.panda.Tweets_df</pre><h4>9. Display the tweet</h4><p>We can display tweets using HTML and requests.</p><pre><strong>from</strong> <strong>IPython.display</strong> <strong>import</strong> HTML<br><strong>import</strong> <strong>requests</strong><br><br><strong>def</strong> show_tweet(link):<br>    <em>&#39;&#39;&#39;Display the contents of a tweet. &#39;&#39;&#39;</em><br>    url = &#39;https://publish.twitter.com/oembed?url=<strong>%s</strong>&#39; % link<br>    response = requests.get(url)<br>    html = response.json()[&quot;html&quot;]<br>    display(HTML(html))</pre><pre>sample_tweet_link = Tweets_df.sample(1)[&#39;link&#39;].values[0]<br>display(sample_tweet_link)<br>show_tweet(sample_tweet_link)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xa3SqW77K1alLB2PSavHzg.png" /></figure><h3>Conclusion</h3><p>Twint is a great package to build social media monitoring applications without being blocked by the Twitter API and its rate limits.</p><p>After scrapping the tweets we can done a effective NLP analysis because dataframe contains lots of features and also we can derive new features.</p><blockquote>You can find my complete solution in my <a href="https://github.com/basilkjose/web-scrapping/tree/main/Twitter%20web%20scrapping%20using%20Twint"><strong>Github Repositor</strong>y </a>,and if you have any suggestions, please contact me via <a href="https://www.linkedin.com/in/basil-k-jose-58b579166/"><strong>Linkedin</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca8ba1b210e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting using LSTM | Code Walkthrough]]></title>
            <link>https://medium.com/apes-ai/time-series-forecasting-using-lstm-code-walkthrough-3aae01645491?source=rss-a571119d1ba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aae01645491</guid>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <dc:creator><![CDATA[Basil K Jose]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 16:56:47 GMT</pubDate>
            <atom:updated>2021-05-19T05:09:20.818Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Time Series Forecasting using LSTM | Code walkthrough</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtFMnFgcwn2gZfs0nqg5GA.jpeg" /></figure><h3>Table of Contents</h3><ol><li>Introduction</li><li>Why lstm?</li><li>Prerequisites</li><li>Dataset</li><li>Univariate forecasting</li><li>Multivariate forecasting</li><li>References</li></ol><h3>Introduction</h3><p>Time series analysis can be useful to see how a given asset, sensor value,security, or economic variable changes over time. It can also be used to examine how the changes associated with the chosen data point compare to shifts in other variables over the same time period.Today most companies use time series forecasting for business growth so they can plan accordingly in the future.It also used in many other fields ,we can use time series forecasting where we have timely recorded data is available. So it is used almost everywhere we need to predict future outcomes from timely recorded historical data.</p><p>Here are a few examples of how different industries use time series forecasting:</p><ul><li><strong>Energy</strong> — Prices,demand, production schedules,temperature prediction</li><li><strong>Retail </strong>— Sales,consumer demand for certain products</li><li><strong>State government</strong> — Sales tax receipts</li><li><strong>Transportation</strong> — Demand for future travel</li><li><strong>Finance </strong>— Stocks, market potential</li></ul><p>Today time series forecasting is one of the hot fields in data science. Different modeling strategies are used for forecasting we can use statistical, machine learning and deep learning models.In this blog, we focused on deep learning LSTM models. Most of the code snippets used for this blog is taken from the <a href="https://www.tensorflow.org/tutorials/structured_data/time_series">TensorFlow 2.0 documentation</a>. The main aim of this writing step by step code walkthrough from data preprocessing to modeling.</p><h3>Why lstm ?</h3><p>Long Short-Term Memory (<strong>LSTM</strong>) is a type of recurrent neural network that can learn the order dependence between items in a sequence.LSTM are pretty good at extracting patterns in input feature space, where the input data spans over long sequences. Given the gated architecture of LSTM that has this ability to manipulate its memory state(memorizing historical data), they are ideal for time series problems.</p><h3>Prerequisites</h3><ul><li>Basic knowledge of LSTMs and RNNs.</li><li>Should familiar with Tensorflow 2.0,matplotlib,numpy and pandas.</li><li>complete code is written on python and run on the google colab platform.</li></ul><h3>Dataset</h3><p>This tutorial uses a <a href="https://www.bgc-jena.mpg.de/wetter/">weather time series dataset</a> recorded by the <a href="https://www.bgc-jena.mpg.de/">Max Planck Institute for Biogeochemistry</a>.</p><p>This dataset contains 14 different features such as air temperature, atmospheric pressure, and humidity. These were collected every 10 minutes, beginning in 2003. For efficiency, you will use only the data collected between 2009 and 2016. <strong>Our aim in this code walkthrough is to forecast air temperature for future timestamps.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvXpUT2F8lo60f5E_XCZCA.png" /><figcaption>Data reading using tensorflow</figcaption></figure><p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/get_file"><strong>tf.keras.utils.get_file</strong></a><strong>() </strong>method in tensorflow is used to download a file from a URL if it is not already in the cache. File is downloaded as a zip file since extract is equal to true, the file is extracted and saved as a csv file.</p><p><a href="https://www.geeksforgeeks.org/python-os-path-splitext-method/"><strong>os.path.splitext()</strong></a> method in Python is used to split the path name into a pair root and ext. Here, <em>ext</em> stands for extension and has the extension portion of the specified path while root is everything except ext part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ITzbefsOXxbVHJVNC0Ung.png" /><figcaption>DataFrame head</figcaption></figure><blockquote><strong>Forecasting task:</strong><em> Predict temperature (in deg C) in the future.</em></blockquote><h3>Univariate Forecasting</h3><p>Only one variable is varying over time. For example, data collected from a sensor measuring the temperature of a room every second. Therefore, each second, you will only have a one-dimensional value, which is the temperature.</p><pre><em># univariate dataframe: Temp vs Time</em><br>uni_data_df = df[&#39;T (degC)&#39;]<em># variable</em><br>uni_data_df.index = df[&#39;Date Time&#39;]<em>#index</em><br>uni_data_df.head()</pre><p>For univariate time series forecasting we want to consider only one variable ,since the problem statement is to forecast temperature.We want the dataframe to consist of temperature as variable and date(timestamp) as index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*4cfdwc7zV0DFaNtiQRUt5g.png" /><figcaption>plot for univarite data</figcaption></figure><p>Before reaching forecasting, we must understand how important preprocessing is for time series. It can make or break your forecasting. So let us go through some of the crucial preprocessing steps for time series.The main challenge to forecasting is preprocessing data into the relevant form.</p><pre>TRAIN_SPLIT = 300000 # First 300000 obs will be used as train data and rest as test data.<br>tf.random.set_seed(13) # random seed</pre><pre>uni_train_mean = uni_data[:TRAIN_SPLIT].mean()<br>uni_train_std = uni_data[:TRAIN_SPLIT].std()</pre><pre>uni_data = (uni_data-uni_train_mean)/uni_train_std</pre><p>In time series forecasting we cannot do the random splitting of data. Because we want to keep all the data in order of timestamps, so in this problem, we considered the first 30000 data points as training data and the remaining as cross-validation data.The reason for standardization is that the model runs very fast and also to bring values to specific ranges.<strong> Using train data we standardize our entire dataframe</strong></p><pre><strong>def</strong> univariate_data(dataset, start_index, end_index, history_size, target_size):<br>    <em>&quot;&quot;&quot;function to create input and ouput values for univariate time series forecasting&quot;&quot;&quot;</em><br>  data = []<br>  labels = []<br><br>  start_index = start_index + history_size<br>  <strong>if</strong> end_index <strong>is</strong> <strong>None</strong>:<br>    end_index = len(dataset) - target_size<br><br>  <strong>for</strong> i <strong>in</strong> range(start_index, end_index):<br>    indices = range(i-history_size, i)<br>    <em># Reshape data from (history_size,) to (history_size, 1)</em><br>    data.append(np.reshape(dataset[indices], (history_size, 1)))<br>    labels.append(dataset[i+target_size])<br>  <strong>return</strong> np.array(data), np.array(labels)<br><br><em># use the above function to create the datasets.</em><br>univariate_past_history = 20<br>univariate_future_target = 0</pre><pre>x_train_uni, y_train_uni = univariate_data(uni_data, 0, TRAIN_SPLIT,<br>                                           univariate_past_history,<br>                                           univariate_future_target)<br>x_val_uni, y_val_uni = univariate_data(uni_data, TRAIN_SPLIT, <strong>None</strong>,<br>                                       univariate_past_history,<br>                                       univariate_future_target)</pre><p>We already said that one of the challenging parts of time series forecasting is converting data into input and output format. The above function is used for this purpose.</p><p>In this problem we considered univariate_past_history = 20 which means we are considering past 20 records for prediction of the next value that is the first 20 values of the temperature variable is x1(indices 0 to 19) and x2 will be indices from 1 to 20. univariate_future_target = 0 means we want to predict the value at the current index that means y1 will be indexed at 19 and y2 index at 20.If univariate_future_target = 5 then y1 is index at 24.(using previous 20 timestamps record want to predict 25th timestamp temperature)</p><pre># TF Dataset preperation<br>BATCH_SIZE = 256 # bacth size in batch-SGD/variants<br>BUFFER_SIZE = 10000 # for shuffling the dataset</pre><pre>train_univariate = tf.data.Dataset.from_tensor_slices((x_train_uni, y_train_uni))<br>train_univariate = train_univariate.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()</pre><pre>val_univariate = tf.data.Dataset.from_tensor_slices((x_val_uni, y_val_uni))<br>val_univariate = val_univariate.batch(BATCH_SIZE).repeat()</pre><p>A batch size of 256 is fed in each epoch, using the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle"><strong>shuffle</strong></a> function data points is shuffled across each batch for an indefinite time using the<a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#repeat"> <strong>repeat</strong> </a>function.</p><pre># MODEL:<br>simple_lstm_model = tf.keras.models.Sequential([<br>    tf.keras.layers.LSTM(8, input_shape=x_train_uni.shape[-2:]),<br>    tf.keras.layers.Dense(1)<br>])</pre><pre>simple_lstm_model.compile(optimizer=&#39;adam&#39;, loss=&#39;mae&#39;)</pre><pre><br># Train and evaluate<br>STEPS_PER_EPOCH = 200<br>EPOCHS = 10</pre><pre>simple_lstm_model.fit(train_univariate, epochs=EPOCHS,<br>                      steps_per_epoch=STEPS_PER_EPOCH,<br>                      validation_data=val_univariate,  <br>                      validation_steps=50)</pre><p>Here we used a simple lstm model for forecasting consisting of one layer.MAE is used for loss minimization , hyperparameter tuning is to be done on modeling.</p><h3>Multivariate Forecasting</h3><p>A Multivariate time series has more than one time-dependent variable. Each variable depends not only on its past values but also has some dependency on other variables. This dependency is used for forecasting future values.Mainly there are two types of multivariate time series forecasting.</p><ul><li>Multivariate single step forecasting</li><li>Multivariate multiple step forecasting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*olAE8bLGcov-1IdzwTeoFQ.png" /><figcaption>creating multivariate dataframe</figcaption></figure><p>For multivariate time series forecasting we considered three features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*i45TQWUaI_AsZ5mxY_vnyw.png" /><figcaption>plot for multivariate dataframe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*5OtWUrF_L_HMPOVLNrPWZg.png" /></figure><p>Using train data we standardize our entire dataframe .</p><pre>def multivariate_data(dataset, target, start_index, end_index, history_size,target_size, step, single_step=False):<br>  data = []<br>  labels = []</pre><pre>start_index = start_index + history_size<br>  if end_index is None:<br>    end_index = len(dataset) - target_size</pre><pre>for i in range(start_index, end_index):<br>    indices = range(i-history_size, i, step) # step used here.<br>    data.append(dataset[indices])</pre><pre>if single_step: # single_step used here.<br>      labels.append(target[i+target_size]) <br>    else:<br>      labels.append(target[i:i+target_size])</pre><pre>return np.array(data), np.array(labels)</pre><p>There is a slight change in function to create input and output values. we have added two new parameters to the function.</p><p><strong>step:</strong> instead of taking data for each timestamp, do you want to generate data once every n steps . (for example if step = 6 ,then function consider data on every sixth time stamp)</p><p><strong>single_step:</strong> labels(output) from single timestamp or multiple time steps. It takes either True or False. If it is true then time series forecasting is<strong> Multivariate single step forecasting</strong> , that is we are predicting for only one timestamp value in the future. If the value is false then time series forecasting is <strong>Multivariate multi step forecasting</strong>, in future predicting multiple values at different time stamps</p><blockquote><em>All other steps like tensor dataset creation, modeling remains the same as univariate time series forecasting.Entire code is present in github.</em></blockquote><p>You can find my complete code in my <a href="https://github.com/basilkjose/Time-series/tree/main/Time%20Series%20Forecasting%20using%20LSTM%20Code%20Walkthrough"><strong>Github Repositor</strong>y</a> ,and if you have any suggestions, please contact me via <a href="https://www.linkedin.com/in/basil-k-jose-58b579166/"><strong>Linkedin</strong></a></p><h3>References</h3><ul><li><a href="https://www.tensorflow.org/tutorials/structured_data/time_series#%20Reasoning%20for%20explaining%20TF%20guides/tutorials:">https://www.tensorflow.org/tutorials/structured_data/time_series#%20Reasoning%20for%20explaining%20TF%20guides/tutorials:</a></li><li>https://<a href="https://machinelearningmastery.com/deep-learning-for-time-series-forecasting/">machinelearningmastery</a>.com/deep-learning-for-time-series-forecasting/</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aae01645491" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apes-ai/time-series-forecasting-using-lstm-code-walkthrough-3aae01645491">Time Series Forecasting using LSTM | Code Walkthrough</a> was originally published in <a href="https://medium.com/apes-ai">Apes AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reducing Commercial Aviation Fatalities | Kaggle Competition]]></title>
            <link>https://basilkjose.medium.com/reducing-commercial-aviation-fatalities-kaggle-competition-5f001283075c?source=rss-a571119d1ba3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f001283075c</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[case-study]]></category>
            <dc:creator><![CDATA[Basil K Jose]]></dc:creator>
            <pubDate>Thu, 07 Jan 2021 11:07:44 GMT</pubDate>
            <atom:updated>2021-01-14T06:51:22.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8nsm4KAPpbIMCE5bPTAaJg.jpeg" /><figcaption>image from Google</figcaption></figure><h3>Table of Contents</h3><ol><li>Overview</li><li>Business Problem</li><li>Dataset Analysis</li><li>Mapping the Real World Problem into ML problem</li><li>Performance Metric</li><li>Exploratory Data Analysis</li><li>Feature Engineering</li><li>Data preprocessing</li><li>Modeling</li><li>Future improvements</li><li>Result</li><li>References</li></ol><p>It was a <a href="https://www.kaggle.com/c/reducing-commercial-aviation-fatalities">Kaggle competition </a>which is organized by <a href="https://www.boozallen.com/"><strong>Booz Allen Hamilton </strong></a>company on Kaggle. Booz Allen Hamilton has been solving for business, government, and military leaders for over 100 years. competition is about reducing aviation fatalities we have to predict state of the pilot based on given physiological data in competition. So let’s start to explore the problem!</p><h3>Overview</h3><p>Most of the flight fatalities are due to the loss of airplane sate of awareness. One of the important today’s travelers are considered is safety. Accidents related flight leads to the loss of life of several people. So our challenge is to build a model to detect troubling events from aircrew’s physiological data.</p><p>The most frequent causes for these aviation <a href="https://www.nphm.com/cases-we-handle/aviation-accident/causes-of-airplane-crashes/">accidents</a> include:</p><ol><li>Pilot error</li><li>Mechanical error</li><li>Runway problems</li><li>Air traffic failure</li><li>Climate problems</li></ol><p>In this problem we mainly focus is on the first cause i.e, aviation accidents caused by pilot error, how to reduce that..</p><h3>Business Problem</h3><p>Air flight is one of the important ways of traveling. So the safety of passengers is primarily considered by most of the airplane companies. As a part of that pilots underwent severe training to handle different situations, important ability a pilot should pursue is multitasking capability.</p><p>Most of the flight fatalities or flight accidents due to pilot error are due to the loss of airplane state awareness. Airplane state awareness (ASA) is a pilot performance attribute wherein the pilot should be able to realize and respond quickly to any change of state of the airplane. Loss of airplane state awareness may lead to many dangerous situations and may result in loss of airplane control. Loss of ASA is mainly due to loss of attention on the part of pilots who may be distracted, sleepy, or in other dangerous cognitive states. Due to the stressful environment, while flying, the possibility of the loss of awareness is common.</p><p>In this dataset, you are provided with real physiological data from eighteen pilots who were subjected to various distracting events. The benchmark training set is comprised of a set of controlled experiments collected in a non-flight environment, outside of a flight simulator. The test set (abbreviated LOFT = Line Oriented Flight Training) consists of a full flight (take off, flight, and landing) in a flight simulator.</p><p>The pilots experienced distractions intended to induce one of the following three cognitive states:</p><ul><li>Channelized Attention (CA) is, roughly speaking, the state of being focused on one task to the exclusion of all others. This is induced in benchmarking by having the subjects play an engaging puzzle-based video game.</li><li>Diverted Attention (DA) is the state of having one’s attention diverted by actions or thought processes associated with a decision. This is induced by having the subjects perform a display monitoring task. Periodically, a math problem showed up which had to be solved before returning to the monitoring task.</li><li>Startle/Surprise (SS) is induced by having the subjects watch movie clips with jump scares.</li></ul><p>The aim is to build a model that can estimate the state of mind of the pilot in real-time using the physiological data given. When the pilot enters into any one of the above mentioned dangerous cognitive states, he/she should be alerted, thereby preventing any possible accident.</p><h3>Dataset Analysis</h3><p>The dataset are provided in csv files (both train and test dataset).</p><p>Now, let’s analyze each attribute in the <a href="https://www.kaggle.com/c/reducing-commercial-aviation-fatalities/data">dataset</a>.</p><p>The main sensors used for the collecting physiological data are EEG, ECG, Respiration, Galvanic skin response.</p><ul><li>id - (test.csv and sample_submission.csv only) A unique identifier for a crew + time combination. You must predict probabilities for each id.</li><li>crew - a unique id for a pair of pilots. There are 9 crews in the data.</li><li>experiment - One of CA, DA, SS or LOFT. The first 3 comprise the training set. The latter the test set.(The training data consist of three experiments: CA, DA, and SS. The output is one of the four labels: Baseline(no event), CA, DA, or SS. For example, if the experiment is CA, the output is either CA or Baseline(no event). The test data is taken from a full flight simulator. Here the experiment is called LOFT or Line Oriented Flight Training where the training of the pilot is carried out in a flight simulator, which artificially creates the environment of a real flight. In the test data, the experiment is given as LOFT and the output can be one of the four states at a given time.)</li><li>time - seconds into the experiment</li><li>seat - is the pilot in the left (0) or right (1) seat</li><li>eeg_fp1 ,eeg_f7 ,eeg_f8 ,eeg_t4 ,eeg_t6 ,eeg_t5 ,eeg_t3 ,eeg_fp2 ,eeg_o1 ,eeg_p3 ,eeg_pz ,eeg_f3 ,eeg_fz ,eeg_f4 ,eeg_c4 ,eeg_p4 ,eeg_poz eeg_c3 ,eeg_cz ,eeg_o2</li><li>ecg - 3-point Electrocardiogram signal. The sensor had a resolution/bit of .012215 µV and a range of -100mV to +100mV. The data are provided in microvolts.</li><li>r - Respiration, a measure of the rise and fall of the chest. The sensor had a resolution/bit of .2384186 µV and a range of -2.0V to +2.0V. The data are provided in microvolts.</li><li>gsr - Galvanic Skin Response, a measure of electrodermal activity. The sensor had a resolution/bit of .2384186 µV and a range of -2.0V to +2.0V. The data are provided in microvolts.</li><li>event - The state of the pilot at the given time: one of A= baseline, B= SS, C= CA, D= DA</li></ul><h3>Mapping the Real World Problem into ML problem</h3><p>This is a multiclass classification(A,B,C,D) problem .For each id , we need to predict the state of the pilot as belonging to one of the four given classes</p><h3>Performance Metric</h3><p>The problem we are handling is a multiclass classification problem where the number of classes is 4</p><ul><li>The evaluation matrix used in this competition is multiclass log loss</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*OYQmDRFFWFr9ZNw6.png" /><figcaption>multi class log loss</figcaption></figure><p>where N is the total number of data points, M is the number of classes.</p><p>yij is 1 if the data point i is predicted to be of class j, and is 0 otherwise.</p><p>pij is the probability of data point i belonging to class j</p><h3>Exploratory Data Analysis(EDA)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*IdpnIYS3h-LQMW0XlRUnng.png" /><figcaption>Null/Nan value checking</figcaption></figure><p>The first step to explore train data is to check data is balanced or imbalanced. For this purpose we used countplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*7CJQDfK1cRp8I108zEPy8A.png" /><figcaption>Frequency of e vents(count plot)</figcaption></figure><p>From the plot we can understand that train data is imbalanced</p><h4>Time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*uoitxQu3Rq7_xUEOBVUKCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*hEGGEbFyXlOn40xL68kcSw.png" /><figcaption>time feature boxplot and distplot</figcaption></figure><ul><li>We can see event B’s plot tells us that the values of the plot are present in the high and lower range of the time axis and there are very few values in the mid-range.</li><li>For other classes, the time feature is well distributed.</li><li>From the distplot, we can say that Time into the experiment is on an average between 0 to 360 sec.</li><li>From the above plot, we can understand that there is a huge difference in the train and test time of the experiment.</li></ul><h4>ECG (<strong>electrocardiogram</strong>)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*rVW3DKTggcHbamFvTeCouA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*S-waagQX1_DoNKn3WEPQdw.png" /><figcaption>ecg feature boxplot and distplot</figcaption></figure><ul><li>From the box plot, it is observed that the ecg data has some outliers. But we cannot simply remove them because these extreme values might be useful in predicting the event. When the value of ECG is high (more than 10000 microvolts), the pilot is more likely to enter into the DA state. Similarly, when the value is too negative, the pilot is likely to be in CA state.</li><li>From the pdf of ECG we can see the range of values for ecg is between the range of -20k to +35k uV (approx). We can see that there are very few values between the 20k to 25k uV range than other values of uV of ECG.</li></ul><h4>GSR (<strong>galvanic skin response</strong>)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*aM5pAHLxU7oQTmjmssclsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*jjkeofqgUmI32WdByZyX3A.png" /><figcaption>gsr feature boxplot and distplot</figcaption></figure><ul><li>The pdf of GSR has a range from 0 to 2000uV approximately.</li><li>GSR has some role in determining the event. For example, if the value from gsr is too high the pilot is more likely to be in SS state. Also if the sensor output is very low, the pilot is probably in DA state</li></ul><h4>Respiration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*t3oW7aJDgk910ldaGTUE5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*VBykeZbpGp4habS1mbj8DQ.png" /><figcaption>respiration feature boxplot and distplot</figcaption></figure><ul><li>We can see the same thing for pdf of respiration signal and the range of respiration signal is from 400 to 850 typically.</li><li>This sensor output is not at all separating the events. This might be because of the noise in the data</li></ul><h4>EEG ( <strong>electroencephalogram</strong>)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*JEEfpn6RCg37MVyBjyz8eQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*pNHSfYI5Bv4qPZg_0caEJg.png" /><figcaption>eeg feature boxplot and distplot</figcaption></figure><ul><li>We can also observe that mostly all the events are lying in the almost same range so we can’t simply put some value as a threshold and use it to classify the events.</li><li>From box plot most of the features are highly overlapping</li><li>We can see above both Train and Test eeg data follow about to normal distribution but test data have a bigger peak at zero(0) and more variance in test data</li></ul><h3>Feature Engineering</h3><p>Now let’s derive some features from existing features.</p><h4>Deriving Heart Beat Information From ECG</h4><p>In the given dataset ecg is recorded in microvolts. If we can extract heart rate from this ecg data it should be for modelling .For this purpose Python provides a powerful tool called <a href="https://biosppy.readthedocs.io/en/stable/biosppy.signals.html#biosppy-signals-ecg">Biosppy</a> which can do bio-signal processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*wvF_8a6gpKY9FQknjazAIg.png" /></figure><ul><li>The output heart rate from the biosppy module is of at some particular timesteps. The heart rate corresponding to all the time stamps in our data set is not available . So we need to find out these values.<a href="https://docs.scipy.org/doc/scipy/reference/interpolate.html"> Interpolation</a> is used for this purpose.</li></ul><h4><em>Deriving Respiration Rate Information From resp</em>iration( ‘r’ )</h4><p>It is the rise and fall of the chest.it represents the muscular activity of abdomen and diaphragm. so when a person is stressed ,the rate of respiration(respiration rate) will be high. For obtaining respiration rate we use same <a href="https://biosppy.readthedocs.io/en/stable/biosppy.signals.html#biosppy-signals-resp">biosppy</a> module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*YA4PxQtzuWbN-bN1SM8pHQ.png" /></figure><p>For here also we need to use interpolation technique to get respiration rate in all time stamps.</p><h4>Deriving Frequency Bands from EEG data</h4><p>The electroencephalogram (EEG) is a recording of the electrical activity of the brain from the scalp. The recorded waveforms reflect the cortical electrical activity.<br>Signal intensity: EEG activity is quite small, measured in microvolts (mV).<br>Signal frequency: the main frequencies of the human EEG waves are:</p><ul><li><strong>Delta</strong>: has a frequency of below 3 Hz. It tends to be the highest in amplitude and the slowest waves. It is normal as the dominant rhythm in infants up to one year and in stages 3 and 4 of sleep. It may occur focally with subcortical lesions and in general distribution with diffuse lesions, metabolic encephalopathy hydrocephalus or deep midline lesions. It is usually most prominent frontally in adults (e.g. FIRDA — Frontal Intermittent Rhythmic Delta) and posteriorly in children e.g. OIRDA — Occipital Intermittent Rhythmic Delta).</li><li><strong>Theta</strong>: has a frequency of 4 to 8Hz and is classified as “slow” activity. It is perfectly normal in children up to 13 years and in sleep but abnormal in awake adults. It can be seen as a manifestation of focal subcortical lesions; it can also be seen in generalized distribution in diffuse disorders such as metabolic encephalopathy or some instances of hydrocephalus.</li><li><strong>Alpha</strong>: has a frequency between 8 and 13 Hz. Is usually best seen in the posterior regions of the head on each side, being higher in amplitude on the dominant side. It appears when closing the eyes and relaxing, and disappears when opening the eyes or alerting by any mechanism (thinking, calculating). It is the major rhythm seen in normal relaxed adults. It is present during most of life especially after the thirteenth year.</li><li><strong>Beta</strong>: beta activity is “fast” activity. It has a frequency of 14 and greater Hz. It is usually seen on both sides in symmetrical distribution and is most evident frontally. It is accentuated by sedative-hypnotic drugs especially the benzodiazepines and the barbiturates. It may be absent or reduced in areas of cortical damage. It is generally regarded as a normal rhythm. It is the dominant rhythm in patients who are alert or anxious or have their eyes open.</li><li><strong>Gamma</strong> (&gt;25 Hz): High value indicates Anxiety, high arousal, stress, etc. A very low value indicates ADHD, depression, learning disabilities, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*vm8X9WKaTpdVtNBga37vzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUUGCLvdtk3ng8_wRbnBHA.png" /></figure><p>Here also we use <a href="https://biosppy.readthedocs.io/en/stable/biosppy.signals.html#biosppy-signals-eeg">biosppy</a> module and interpolation.</p><h4>Deriving potential difference from electrodes</h4><p>In this experiment, they are used 20 electrodes to fit the human brain. There are different formations(montages) to place the electrode in the brain. The potential difference between two electrodes gives mental activity going in that region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z08PQrFlXPK_gMnD2SKRgg.png" /><figcaption>different montages system</figcaption></figure><p>There are different montages system are present but commonly used montages system is 2nd one in the above figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*3BVXBUGKq3e819vxatB2Kw.png" /></figure><h4>Correlation Matrix : removing unimportant features from dataset</h4><p>As a final stage in the feature engineering stage, I have found correlation matrix features with events. From the correlation matrix find that.</p><ul><li>The effect of crew and ecg for predicting the event is high.</li><li>The feature seat is less correlated with the event so that we can remove that feature.</li><li>Potential differences are having more impact in predicting the events as compared to the simple eeg electrode data.</li><li>Theta feature is having some considerable effect in events. The correlation is considerable. So this feature will be useful in predicting the event.</li><li>The alpha low frequency bands derived from this eeg is having more effect in determining the events.</li><li>The beta frequency bands derived from this eeg is had some effect in determining the events. But the correlation is not very high. Its effect might be similar to the effect of 20 eeg electrode data in determining the events.</li></ul><p>First of all, we remove unimportant features like ‘seat’,’ experiment’(we want to predict an event without knowing the experiment). After that we remove derived features such as ‘beta’ and ‘gamma’ frequency bands because it has less correlation with the event, so we remove these features also.</p><h3>Preprocessing</h3><p>Here I have done standardization for converting numerical features. For this purpose used <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html">StandardScaler</a> .</p><h3>Modeling</h3><p>For modelling stage first, simply fit a random model and note down log loss, after train data using a linear model like logistic regression. I got a considerable reduction in log loss as compared to the random model. Since the dataset contain about 105 features ensembles models are expected to perform better. So I trained data using <a href="https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMClassifier.html">LightGBM</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*w4qPIaThhCPGs0QDKQyjFw.png" /></figure><h3>Future Improvements</h3><ul><li>Noise removal of physiological data can be done for obtaining more clean physiological data.</li><li>Try more hyperparameter tuning, fit other complex ensemble models.</li><li>Try to implement Deep learning models.</li></ul><h3>Results</h3><p>I got minimum log loss when I trained data using LightGBM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBe9aN6YvCAnQUmj24_8lg.png" /><figcaption>kaggle score after submitting test data</figcaption></figure><p>You can find my complete solution in my <a href="https://github.com/basilkjose/Reducing-Commercial-Aviation-Fatalities"><strong>Github Repositor</strong>y</a> ,and if you have any suggestions, please contact me via <a href="https://www.linkedin.com/in/basil-k-jose-58b579166/"><strong>Linkedin</strong></a></p><h3>References</h3><ul><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a></li><li><a href="https://www.kaggle.com/stuartbman/introduction-to-physiological-data">https://www.kaggle.com/stuartbman/introduction-to-physiological-data</a></li><li><a href="https://www.kaggle.com/shahaffind/reducing-commercial-aviation-fatalities-11th">https://www.kaggle.com/shahaffind/reducing-commercial-aviation-fatalities-11th</a></li><li><a href="https://medium.com/analytics-vidhya/reducing-commercial-aviation-fatalities-ec338e37900c">https://medium.com/analytics-vidhya/reducing-commercial-aviation-fatalities-ec338e37900c</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f001283075c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>