<?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 Cheryl Lai on Medium]]></title>
        <description><![CDATA[Stories by Cheryl Lai on Medium]]></description>
        <link>https://medium.com/@reinec?source=rss-2730a128ce83------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*BIRoixRnFW-k5EzJrkNTTw.jpeg</url>
            <title>Stories by Cheryl Lai on Medium</title>
            <link>https://medium.com/@reinec?source=rss-2730a128ce83------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:18:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reinec/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[Stratascratch: Facebook Interview Coding Question Medium — SQL + Python]]></title>
            <link>https://reinec.medium.com/stratascratch-facebook-interview-coding-question-medium-sql-python-9268e26700e6?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/9268e26700e6</guid>
            <category><![CDATA[yelp]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 10:40:11 GMT</pubDate>
            <atom:updated>2021-04-26T03:56:54.933Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stratascratch: Facebook, Yelp Interview Coding Question— SQL + Python</h3><ol><li><strong>Acceptance Rate by Date — Facebook</strong></li></ol><p><em>What is the overall friend acceptance rate by date? Your output should have the rate of acceptances by the date the request was sent. Order by the earliest date to latest. Assume that each friend request starts by a user sending (i.e., user_id_sender) a friend request to another user (i.e., user_id_receiver) that’s logged in the table with action = ‘sent’. If the request is accepted, the table logs action = ‘accepted’. If the request is not accepted, no record of action = ‘accepted’ is logged. Hint: For the SQL solution, cast your data types as a decimal rather than float in order for your solution to be validated properly. There is a rounding error if your solution is casted as a float.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*42RB0C6pzBndbQUbpaKR1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*7ZESSMn3d_CIx3M_SR8dFQ.png" /><figcaption>fb_friend_requests</figcaption></figure><h3><strong>SQL</strong></h3><pre>select tmp1.date, count(tmp2.user_id_sender)::float/count(tmp1.user_id_sender)::float from <br>(select * from fb_friend_requests<br>where action = &#39;sent&#39;<br>) tmp1<br>left join</pre><pre>(select * from fb_friend_requests<br>where action = &#39;accepted&#39;<br>) tmp2<br>on tmp1.user_id_sender = tmp2.user_id_sender<br>and tmp1.user_id_receiver = tmp2.user_id_receiver</pre><pre>group by tmp1.date</pre><h3><strong>Python</strong></h3><pre>import pandas as pd</pre><pre>sent = fb_friend_requests[fb_friend_requests[&#39;action&#39;]==&#39;sent&#39;]<br>accp = fb_friend_requests[fb_friend_requests[&#39;action&#39;]==&#39;accepted&#39;]<br>df = sent.merge(accp[[&#39;user_id_sender&#39;, &#39;user_id_receiver&#39;, &#39;action&#39;]], how=&#39;left&#39;, left_on=[&#39;user_id_sender&#39;, &#39;user_id_receiver&#39;], right_on=[&#39;user_id_sender&#39;, &#39;user_id_receiver&#39;])</pre><pre>df_sent = df.groupby(&#39;date&#39;)[&#39;action_x&#39;].count().reset_index()<br>df_accp = df.groupby(&#39;date&#39;)[&#39;action_y&#39;].count().reset_index()</pre><pre>df1 = df_sent.merge(df_accp, how=&#39;left&#39;, on=&#39;date&#39;)<br>df1[&#39;pc&#39;] = df1[&#39;action_y&#39;]/df1[&#39;action_x&#39;]<br>df1[[&#39;date&#39;, &#39;pc&#39;]]</pre><p>2. <strong>Highest Energy Consumption — Facebook</strong></p><p><em>Find the date with the highest total energy consumption from the Facebook data centers. Output the date along with the total energy consumption across all data centers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*sVTwgbGHHuNf-nyFkKzU-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*nN5sqrKdP5hx4A4xSxFrvA.png" /><figcaption>fb_eu_energy</figcaption></figure><h3>SQL</h3><pre>select date, sum(consumption) from <br>(select *, &#39;eu&#39; as region from fb_eu_energy</pre><pre>union all</pre><pre>select *, &#39;asia&#39; as region from fb_asia_energy</pre><pre>union all</pre><pre>select *, &#39;na&#39; as region from fb_na_energy<br>) tmp1<br>group by date<br>order by sum desc<br>limit 2</pre><h3>Python</h3><pre>import pandas as pd</pre><pre>df = pd.concat([fb_eu_energy, fb_asia_energy, fb_na_energy])<br>df = df.groupby(&#39;date&#39;)[&#39;consumption&#39;].sum().reset_index()<br>df[df[&#39;consumption&#39;] == max(df[&#39;consumption&#39;])]</pre><p><strong>3.Reviews of Categories — Yelp</strong></p><p><em>Find the top business categories based on the total number of reviews. Output the category along with the total number of reviews. Order by total reviews in descending order.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*MUleR0oZHFRFvxkBGjvOOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*ZGhlqskEhhK48338yOVA3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*gzZYySVhz7XoUbfsLAKMVw.png" /></figure><h3>SQL</h3><pre>with df as (select unnest(string_to_array(categories, &#39;;&#39;)) as cat, review_count from yelp_business)</pre><pre>select category, sum(review_count) as review_cnt from df<br>group by category<br>order by review_cnt desc</pre><h3>Python</h3><pre>import pandas as pd</pre><pre>yelp_business[&#39;cat_split&#39;] = yelp_business[&#39;categories&#39;].str.split(&#39;;&#39;)<br>df = yelp_business.explode(&#39;cat_split&#39;)<br>df.groupby(&#39;cat_split&#39;)[&#39;review_count&#39;].sum().sort_values(ascending=False).reset_index()</pre><p><strong>4.Popularity Percentage — Facebook</strong></p><p><em>Find the popularity percentage for each user on Facebook. The popularity percentage is defined as the total number of friends the user has divided by the total number of users on the platform, then converted into a percentage by multiplying by 100. Output each user along with their popularity percentage. Order records in ascending order by user id. The ‘user1’ and ‘user2’ column are pairs of friends.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*76Ukh9o1ZfTSlV4ufQuFBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*cKAqTHRHFDXnVPIeMbliaQ.png" /></figure><h3>SQL</h3><pre>with df as (select user1, user2 from facebook_friends<br>union all <br>select user2, user1 from facebook_friends)</pre><pre>select user1, 100 * count(distinct user2)::float/(select count (distinct user1)::float from df) from df<br>group by user1<br>order by user1 asc</pre><h3>Python</h3><pre>import pandas as pd</pre><pre>tmp = facebook_friends.rename(columns={&#39;user1&#39;:&#39;user2&#39;, &#39;user2&#39;:&#39;user1&#39;})<br>df = pd.concat([facebook_friends, tmp]).drop_duplicates().sort_values(&#39;user1&#39;)<br>df.groupby(&#39;user1&#39;)[&#39;user2&#39;].count()/len(df[&#39;user1&#39;].drop_duplicates()) * 100</pre><p><strong>5.Highest Cost Order — Amazon</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*VTVrJ8UN3Mwd4ajWt8gotw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Odiei49WoIKJHWO1qjrNng.png" /><figcaption>customers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*L-t0cr4QaV9QUrgMLODgpg.png" /><figcaption>orders</figcaption></figure><h3>SQL</h3><pre>with df as (select first_name, order_date, sum(order_quantity * order_cost) as total_cost, rank() over(order by sum(order_quantity * order_cost) desc) as ranking<br>from ( select * from customers<br>left join  orders on customers.id = orders.cust_id<br>where order_date between &#39;2/1/2019&#39; and &#39;5/1/2019&#39;) tmp<br>group by first_name, order_date)</pre><pre>select * from df where ranking=1</pre><h3>Python</h3><pre>import pandas as pd<br>from datetime import datetime</pre><pre>df = customers[[&#39;id&#39;, &#39;first_name&#39;]].merge(orders[[&#39;cust_id&#39;, &#39;order_date&#39;, &#39;order_quantity&#39;, &#39;order_cost&#39;]], how=&#39;left&#39;, left_on=&#39;id&#39;, right_on=&#39;cust_id&#39;)<br>df[&#39;total_cost&#39;] = df[&#39;order_quantity&#39;] * df[&#39;order_cost&#39;]<br>df = df[df[&#39;order_date&#39;].between(&#39;02/01/2019&#39;, &#39;05/01/2019&#39;, &#39;inclusive&#39;)].groupby([&#39;first_name&#39;, &#39;order_date&#39;])[&#39;total_cost&#39;].sum().reset_index()</pre><pre>#df[&#39;order_date&#39;] = pd.to_datetime(df[&#39;order_date&#39;], format=&#39;%Y-%m-%d&#39;).dt.strftime(&#39;%Y-%m-%d&#39;)</pre><pre>df[[&#39;first_name&#39;, &#39;order_date&#39;, &#39;total_cost&#39;]][df[&#39;total_cost&#39;] == max(df[&#39;total_cost&#39;])]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9268e26700e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[study notes: Convert pdf to audiobook using python (Google Text-to-Speech) and  export to mp3]]></title>
            <link>https://reinec.medium.com/study-notes-convert-pdf-to-audiobook-using-python-google-text-to-speech-and-export-to-mp3-3db9d2f81f87?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db9d2f81f87</guid>
            <category><![CDATA[pdf-to-audiobook]]></category>
            <category><![CDATA[gtt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[google-speech-to-text]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 15:18:27 GMT</pubDate>
            <atom:updated>2020-10-28T15:20:49.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>study notes: Convert pdf to audiobook using python (<em>Google Text-to-Speech) and</em> export to mp3</h3><p>1.Reading in pdf and extracting page number</p><pre>import PyPDF2<br>from gtts import gTTS<br>import re</pre><pre>book = open(’sample.pdf&#39;, &#39;rb&#39;) # load pdf - sample.pdf<br>pdfReader = PyPDF2.PdfFileReader(book)<br>pages =pdfReader.numPages</pre><p>2.Reading in data from each page and concatenate into a single text using for loop</p><pre>full_book = “My Audiobook&quot; # assign a title to audiobook</pre><pre>for i in range(0, pages): <br>    page = pdfReader.getPage(i)<br>    text = page.extractText()<br>    page_num = str(i+1) # to add page number info into string<br>    full_book = f&quot;{full_book} Page {page_num} {text}&quot;</pre><p>3.Remove redundant and repetitive phrases within text</p><pre>full_book = re.sub(&#39;(This page intentionally left blank.)|(Click here for Terms of Use.)|(Copyright 2020.)&#39;, &#39; &#39;, full_book)</pre><p>4.Convert to audiofile using <em>Google Text-to-Speech </em>and export to mp3</p><pre>obj = gTTS(text=full_book, lang=&#39;en&#39;, slow=False)</pre><pre>obj.save(’sample&#39;.mp3&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db9d2f81f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[study notes: LDA Topic Modelling]]></title>
            <link>https://reinec.medium.com/my-notes-topic-modelling-499286dde8a7?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/499286dde8a7</guid>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[lda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Wed, 27 May 2020 17:01:02 GMT</pubDate>
            <atom:updated>2020-11-03T05:07:55.221Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Work nourishes noble minds.” — SENECA</blockquote><p>Latent Dirichlet Allocation (LDA) is an unsupervised machine learning technique used for extracting</p><ul><li>number of topics in data</li><li>distribution of topics in each text</li><li>distribution of words in each topic</li></ul><p>A topic is a representation of salient keywords in a certain proportion and a good topic model will be able to classify each text to a topics based on the words used.</p><p><a href="https://www.kaggle.com/hj5992/nlp-topic-modelling?select=Reviews.csv"><em>Data</em></a></p><pre>import pandas as pd<br>import numpy as np<br>import string<br>from nltk.corpus import stopwords <br>from nltk.stem.wordnet import WordNetLemmatizer<br>import gensim<br>from gensim import corpora<br>from gensim.models import CoherenceModel<br>import pyLDAvis.gensim<br>import re<br>from wordcloud import WordCloud</pre><pre># Data of reviews by customers<br>df = pd.read_csv(&#39;Reviews.csv&#39;)</pre><pre>print(&#39;Dimension of df: &#39; + str(df.shape) + &#39;\n&#39;)<br>print(df.loc[0, &#39;Text&#39;])</pre><p><em>&gt;&gt; Dimension of df: (568454, 10)</em></p><p><em>&gt;&gt; I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most.</em></p><p>Basic Data Cleaning for textual data:</p><ul><li>Remove punctuations</li><li>Remove stopwords</li><li>Lemmatization</li></ul><pre># Data processing</pre><pre># Update with additional stopwords<br>stop = set(stopwords.words(&#39;english&#39;))<br>stop.update((&#39;br&#39;, &#39;food&#39;))</pre><pre># Remove punctuations<br>exclude = set(string.punctuation)</pre><pre># Lemmatize<br>lemma = WordNetLemmatizer()</pre><pre># Define function for data cleaning <br>def data_proc(x):<br>    x = x.rstrip()<br>    punc_free = &#39;&#39;.join(i for i in x if i not in exclude)<br>    stop_free = &#39; &#39;.join([i for i in punc_free.lower().split() if((i not in stop) and (not i.isdigit()))])<br>    normalized = &#39; &#39;.join(lemma.lemmatize(i) for i in stop_free.split())<br>    return normalized</pre><pre># Apply function to text<br>txt_proc = [data_proc(i).split() for i in df[&#39;Text&#39;]]</pre><pre>print(&#39;\nBefore Data Processing\n&#39;)<br>print(df.loc[0, &#39;Text&#39;])<br>print(&#39;\nAfter Data Processing\n&#39;)<br>print(&#39; &#39;.join(txt_proc[0]))</pre><p><em>&gt;&gt; Before Data Processing</em></p><p><em>I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most.</em></p><p><em>&gt;&gt; After Data Processing</em></p><p><em>bought several vitality canned dog product found good quality product look like stew processed meat smell better labrador finicky appreciates product better</em></p><pre># Combine all words in df<br>words = &quot;&quot;<br>for i in txt_proc:<br>    words = words + &#39; &#39;.join(i)</pre><pre># Create a WordCloud object<br>wordcloud = WordCloud(background_color=&quot;white&quot;, max_words=5000, contour_width=3, contour_color=&#39;steelblue&#39;)</pre><pre># Generate a word cloud<br>wordcloud.generate(words)<br>wordcloud.to_image()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0aTfhJG1PfN53tdqe1h-Tg.png" /></figure><p>An ID is generated for every unique word in the dataset. The corpus (bag-of-words) provide a mapping of the ID to the frequency of each word.</p><p>eg. (0, 1) — Word ID 0 occurs once in the first review (output below)</p><p>The corpus is used as an input for the LDA model.</p><pre># Create a dictionary of courpus (bag-of-words) where each unique term is assigned an index<br>dictionary = corpora.Dictionary(txt_proc)<br># Convert corpus into document term matrix using dictionary<br>corpus = [dictionary.doc2bow(i) for i in txt_proc]</pre><pre># View corpus for first review<br>print(corpus[0])</pre><p><em>&gt;&gt; [(0, 1), (1, 2), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 3), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1)]</em></p><p>For a more human readable format:</p><pre>indx = []<br>for i,j in corpus[0]:<br>    indx.append(str(dictionary[i]) + &#39;, &#39; + str(j))<br>print(indx)</pre><p><em>&gt;&gt; [‘appreciates, 1’, ‘better, 2’, ‘bought, 1’, ‘canned, 1’, ‘dog, 1’, ‘finicky, 1’, ‘found, 1’, ‘good, 1’, ‘labrador, 1’, ‘like, 1’, ‘look, 1’, ‘meat, 1’, ‘processed, 1’, ‘product, 3’, ‘quality, 1’, ‘several, 1’, ‘smell, 1’, ‘stew, 1’, ‘vitality, 1’]</em></p><p>Word ID 0 represents the word appreciates and it occurs once in the first review.</p><p>Training the LDA model on the corpus and dictionary:</p><pre># Train lda model<br>Lda = gensim.models.ldamodel.LdaModel<br>ldamodel = Lda(corpus, num_topics=5, id2word = dictionary, passes=15)</pre><pre># LDA model to generate 5 topic from entire dataset and 5 words for each topic and its weightage<br>topic = ldamodel.print_topics(num_topics=5, num_words=5)<br>for i in topic:<br>    print(i)</pre><p><em>&gt;&gt; (0, ‘0.021*”dog” + 0.014*”treat” + 0.010*”cat” + 0.010*”love” + 0.010*”like”’)<br>(1, ‘0.018*”taste” + 0.017*”like” + 0.013*”good” + 0.012*”flavor” + 0.011*”chocolate”’)<br>(2, ‘0.048*”tea” + 0.021*”taste” + 0.017*”drink” + 0.017*”like” + 0.016*”flavor”’)<br>(3, ‘0.044*”coffee” + 0.017*”flavor” + 0.016*”like” + 0.014*”cup” + 0.014*”taste”’)<br>(4, ‘0.017*”product” + 0.015*”amazon” + 0.014*”price” + 0.012*”store” + 0.010*”bag”’)</em></p><p>Topic 0 consist of keywords such as <em>dog, treat, cat, love </em>and<em> like. </em>Topic 0 is most likely to be about animal food (dog/cat mainly).</p><p>Overall, the entire dataset can be categorised into 5 main topics:</p><ul><li>Product type — animal food, chocolate, tea, coffee</li><li>Purchase location — amazon.</li></ul><p>The numbers represents the weightage for each word and its importance to the topic. LDA is able to classify each review to a different topic that is useful for further analysis.</p><p>To view the classification and probabilities of topics for each review:</p><pre>for i in range(0,3):<br>    print(ldamodel[corpus[i]])</pre><p><em>&gt;&gt; [(0, 0.7747076), (4, 0.19869387)]<br>[(0, 0.105494626), (1, 0.26752147), (2, 0.011341258), (3, 0.01122728), (4, 0.6044154)]<br>[(0, 0.10473981), (1, 0.53593975), (2, 0.060168535), (3, 0.04605796), (4, 0.25309402)]</em></p><ul><li>Review 1: 77% in Topic 0 , 20% in Topic 4</li></ul><p>To measure the usefulness of the topic model:</p><pre># Compute Perplexity<br>print(&#39;\nPerplexity: &#39;, ldamodel.log_perplexity(corpus)) </pre><pre><br># Compute Coherence Score<br>coherence_model_lda = CoherenceModel(model=ldamodel, texts=txt_proc, <br>                                     dictionary=dictionary, coherence=&#39;c_v&#39;)<br>coherence_lda = coherence_model_lda.get_coherence()<br>print(&#39;\nCoherence Score: &#39;, coherence_lda)</pre><p><em>&gt;&gt; Perplexity: -7.806956254733788</em></p><p><em>&gt;&gt; Coherence Score: 0.42355554276366475</em></p><p>A lower perplexity score indicates better generalisation and performance. However, perplexity score can sometimes deviate from human judgement by clustering words with vastly different meanings. This leads to ambiguous and non-interpretable topics generated.</p><p>The coherence score evaluates the semantic similarity among keywords within each topic to determine if topics are interpretable or grouped by statistical inference.</p><p>Visualising the topic model:</p><pre>lda_display = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary, sort_topics=False)<br>pyLDAvis.display(lda_display)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dENI6B_tx-A8wpSI6Cldtg.png" /></figure><p>Each bubble represents a topic:</p><ul><li>Size: prevalence and importance of topic within dataset</li><li>Proximity: clustering/overlapping of bubbles suggests topics are not clearly differentiated</li></ul><p>The bar chart on the right represents the Top 30 salient keywords in the dataset by count.</p><p>By selecting a bubble, the chart will be updated to show only the salient keywords for each topic highlighted in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKZQt0hBP6UzXFDE1d-s3g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=499286dde8a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[study notes: Python Numpy]]></title>
            <link>https://reinec.medium.com/my-notes-python-numpy-ae98b1751123?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae98b1751123</guid>
            <category><![CDATA[python-numpy]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 06:52:17 GMT</pubDate>
            <atom:updated>2020-11-03T05:09:57.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Array — table of elements of same type (usually numbers)</p><ul><li>rank: number of dim or array</li><li>shape: tuple of row by column of array</li><li>size: total number of elements in array</li></ul><p>1.Creating numpy array</p><pre>import numpy as np</pre><pre># Create array of rank 1<br>tmp = np.array([1, 2, 3])</pre><pre># Create array of rank 2<br>tmp = np.array([[1, 2, 3], [4, 5, 6]])</pre><pre># Create array from tuple<br>tmp = np.array((1, 2, 3))</pre><pre># Create array of 0 of size 3 x 3<br>tmp = np.zeros((3, 3))</pre><pre># Create array of constant value (or text)<br>tmp = np.full((3, 3), 4) </pre><pre>&gt;&gt; array([[4, 4, 4],<br>          [4, 4, 4],<br>          [4, 4, 4]])</pre><pre># Create array of random values (between 0 - 1)<br>tmp = np.random.random((3,3))</pre><pre># Create an array of sequence <br>tmp = np.arange(1,10,2) # range and step <br>tmp = np.arange(10) # starts from 0 and step not specified<br>tmp = np.linspace(0, 10, 5) # range and number of values <br></pre><p>2.Accessing array using index</p><pre>tmp = np.array([[1, 2, 3, 4],<br>                [5, 6, 7, 8],<br>                [9, 10, 11, 12],<br>                [13, 14, 15, 16]])</pre><pre># Select first 2 rows and alternate columns 0 &amp; 2<br>tmp1 = tmp[:2, ::2]</pre><pre># Select specific elements <br>tmp2 = tmp[[1, 1, 3],<br>           [0, 2, 1]]</pre><pre>&gt;&gt; array([5, 7, 14])</pre><pre># Selecting via conditions<br>tmp[tmp &gt; 10]</pre><pre>&gt;&gt; array([11, 12, 13, 14, 15, 16])</pre><p>3.Basic operations</p><pre># Adding and subtracting to an array<br>tmp - 1</pre><pre># Sum all array elements <br>tmp.sum()  #or <br>np.sum(tmp)</pre><pre>&gt;&gt; 136</pre><pre># Square each element<br>tmp**2</pre><pre># Square root each element<br>np.sqrt(tmp)</pre><pre># Adding arrays (need to have the same # col)<br>tmp3 = tmp[[1, 1, 0, 3],<br>           [0, 2, 1, 3]]</pre><pre>&gt;&gt; array([ 5,  7,  2, 16])</pre><pre># tmp3 is added to every row</pre><pre>tmp + tmp3</pre><pre>&gt;&gt; array([[ 6,  9,  5, 20],<br>          [10, 13,  9, 24],<br>          [14, 17, 13, 28],<br>          [18, 21, 17, 32]])</pre><pre># Transpose<br>tmp = np.array([[1, 2, 3], <br>                [4, 5, 6]])<br>tmp.T</pre><pre>&gt;&gt; array([[1, 4],<br>          [2, 5],<br>          [3, 6]])</pre><pre># Min/Max<br>tmp.max()</pre><pre># Row wise Min/Max<br>tmp.max(axis=1)</pre><pre># Column wise Min/Max<br>tmp.max(axis=0)</pre><p>4.Datatype</p><pre># Check datatype<br>tmp.dtype</pre><pre># Assign datatype<br>tmp = np.array([1, 2, 3], dtype=np.float64)</pre><p>5.Split strings</p><pre># Split string (default split on space)<br>tmp = np.array(&#39;Breakfast at Tiffanys&#39;)<br>np.char.split(tmp)</pre><pre># Split string using delimiter<br>tmp = np.array(‘Breakfast-at-Tiffanys&#39;)<br>np.char.split(tmp, sep=‘-&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae98b1751123" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[my notes: Python Pandas]]></title>
            <link>https://reinec.medium.com/my-notes-python-pandas-b61abee46ba?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61abee46ba</guid>
            <category><![CDATA[python-pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Thu, 12 Mar 2020 15:23:14 GMT</pubDate>
            <atom:updated>2020-04-14T09:18:26.517Z</atom:updated>
            <content:encoded><![CDATA[<p>Pandas data frame</p><ul><li>2D, tabular, mutable, labelled index</li></ul><p><strong>1.Creating a pandas data frame</strong></p><ul><li>Create empty data frame</li></ul><pre>import pandas as pd </pre><pre>df = pd.DataFrame()</pre><ul><li>Create using list</li></ul><pre>tmp = [‘hello&#39;, ‘world&#39;]</pre><pre>df = pd.DataFrame(tmp)</pre><ul><li>Create using dict</li></ul><pre>tmp = {’Name&#39; : [‘blair’, ‘cady’, ‘holly’],<br>       ‘Age&#39; : [20, 18, 25],<br>       ’Title&#39; : [‘gg’, ‘mg’, ‘bat’]}</pre><pre>df = pd.DataFrame(tmp)</pre><ul><li>Read from file</li></ul><pre>df = pd.read_csv(‘movie.csv’, index_col = ’Name’)</pre><p><strong>2.Basic operations on data frame</strong></p><ul><li>Column selection</li></ul><pre>df[’Name’]</pre><pre>df[[’Name’, ’Title’]]</pre><pre>df.loc[:, [’Name’, ’Title’]]</pre><ul><li>Row selection</li></ul><pre>df.loc[‘blair’]</pre><ul><li>Selection by index</li></ul><pre>df.iloc[:,0] #retrieve all rows and a single column<br>df.iloc[:,[0, 1]] #retrieve all rows and multiple single column</pre><pre>df.iloc[2] #retrieve one row<br>df.iloc[[0, 2]] #retrieve multiple row</pre><ul><li>Add new columns</li></ul><pre>ratings = [5, 5, 5]</pre><pre>df[‘Ratings’] = ratings</pre><ul><li>Add new rows</li></ul><pre>new_row = pd.DataFrame({’Name&#39; : [‘belle’],<br>                        ‘Age&#39; : [20],<br>                        ’Title&#39; : [‘bnb’],<br>                        ‘Ratings&#39; : [5]})</pre><pre>df = pd.concat([df, new_row]).reset_index(drop=True) #to ensure that the index resets else new_row will retain its original index</pre><ul><li>Delete columns</li></ul><pre>df.drop([’Title’, ‘Ratings], axis=1, inplace=True)</pre><ul><li>Delete rows</li></ul><pre>df.set_index(&#39;Name&#39;, inplace=True) #need to set the index for row deletion<br>df.drop([&#39;blair&#39;, &#39;holly&#39;], inplace = True)</pre><ul><li>Drop duplicate rows</li></ul><pre>df.drop_duplicates([‘Age’, ‘Ratings’])</pre><p><strong>3.Missing values</strong></p><ul><li>Check for missing values using isnull() and notnull()</li></ul><pre>import pandas as pd<br>import numpy as np</pre><pre>tmp = {’Name&#39; : [‘blair’, ‘cady’, ‘holly’, np.nan],<br>       ‘Age&#39; : [20, 18, np.nan, 25],<br>       ’Title&#39; : [‘gg’, ‘mg’, ‘bat’, np.nan]}</pre><pre>df = pd.DataFrame(tmp)</pre><pre>df.isnull()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*HTRVEZ7gR232ERY4u_VvLA.png" /></figure><ul><li>Fill missing values with constant values with fillna() and replace()</li></ul><pre>df.fillna(0) #fills empty cells with 0</pre><ul><li>Fill values with previous row data</li></ul><pre>df.fillna(method=‘pad’) #if nan value is in the first row it will not be filled</pre><ul><li>Fill values with next row data</li></ul><pre>df.fillna(method=‘bfill’) #if nan value is in the last row it will not be filled</pre><ul><li>Drop missing values with dropna()</li></ul><pre>df.dropna(inplace=True) #drop all rows and columns that contains any Nan/Null</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*cvtxCVp-Yzig8LdftOzhJw.png" /></figure><p><strong>4.Convert data type</strong></p><pre>df.Age = df.Age.astype(‘int64’) #ensure no null values </pre><pre>type(df.Age[0]) #type changed from numpy.float64 to numpy.int64</pre><p><strong>5.Data comparison and selection</strong></p><ul><li>Select data</li></ul><pre>df[df[’Name’]==‘blair]</pre><pre>df[df[’Name’]!=‘blair’]</pre><ul><li>Compare data</li></ul><pre>checks = df[’Name’]==‘blair’<br>df[‘Checks’] = checks #returns boolean</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*50jk_Sk__oNm9CVheElv9Q.png" /></figure><p><strong>6.Joins</strong></p><ul><li>Concatenate by rows for 2 dataframe (<strong>rbind</strong>)</li></ul><pre>tmp = pd.DataFrame({&#39;Name&#39; : [&#39;blair&#39;, &#39;cady&#39;],<br>                    &#39;Age&#39; : [20, 18],<br>                    &#39;Title&#39; : [&#39;gg&#39;, &#39;mg&#39;]},<br>                     index=[0, 1])</pre><pre>tmp1 = pd.DataFrame({&#39;Name&#39; : [&#39;holly&#39;, &#39;belle&#39;],<br>                     &#39;Age&#39; : [25, 20],<br>                     &#39;Title&#39; : [&#39;bat&#39;, &#39;bnb&#39;]},<br>                      index=[2,3]) #can combine without index</pre><pre>pd.concat([tmp, tmp1])</pre><ul><li>Concatenate by columns for 2 data frame (<strong>cbind</strong>)</li></ul><pre>tmp = pd.DataFrame({&#39;Name&#39; : [&#39;blair&#39;, &#39;cady&#39;,&#39;holly&#39;, &#39;belle&#39;],<br>                    &#39;Age&#39; : [20, 18, 25, 20]},<br>                     index=[0, 1, 2, 3])</pre><pre>tmp1 = pd.DataFrame({&#39;Title&#39; : [&#39;gg&#39;, &#39;mg&#39;, &#39;bat&#39;, &#39;bnb&#39;],<br>                     &#39;Ratings&#39; : [5, 5, 5, 5]},                  <br>                      index=[0, 1, 2, 3])</pre><pre>tmp.join(tmp1)</pre><ul><li>Joins</li></ul><pre>tmp = pd.DataFrame({&#39;Name&#39; : [&#39;blair&#39;, &#39;cady&#39;, &#39;belle&#39;],<br>                    &#39;Age&#39; : [20, 18, 20]})</pre><pre>tmp1 = pd.DataFrame({&#39;Name&#39; : [&#39;blair&#39;, &#39;cady&#39;,&#39;holly&#39;, &#39;belle&#39;],<br>                     &#39;Title&#39; : [&#39;gg&#39;, &#39;mg&#39;, &#39;bat&#39;, &#39;bnb&#39;],<br>                     &#39;Ratings&#39; : [5, 5, 5, 5]},                  <br>                      index=[0, 1, 2, 3])</pre><pre>#how: left, right, inner, outer<br>#on: primary index</pre><pre>pd.merge(tmp, tmp1, how =&#39;left&#39;, on =&#39;Name&#39;) </pre><p><strong>7. Data processing</strong></p><ul><li>Split with delimiter</li></ul><pre>df = pd.DataFrame({&#39;First Name&#39; : [&#39;blair&#39;, &#39;cady&#39;, &#39;holly&#39;],<br>                   &#39;Last Name&#39; : [&#39;waldorf&#39;, &#39;heron&#39;, &#39;golightly&#39;],<br>                   &#39;Title&#39; : [&#39;gg&#39;, &#39;mg&#39;, &#39;bat&#39;],<br>                   &#39;Timing&#39; : [&#39;9:00&#39;, &#39;11:30&#39;, &#39;6:28&#39;]})</pre><pre>time = df[&#39;Timing&#39;].str.split(&#39;:&#39;, n =1, expand=True) #n=1 indicates the split at the first occurrence of the delimiter</pre><pre>df[&#39;Hour&#39;] = time[0]<br>df[&#39;Min&#39;] = time[1]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*PJc_39RvozToDVh5o_V3gg.png" /></figure><ul><li>Combine with delimiter</li></ul><pre>df[&quot;Full Name&quot;]= df[&quot;First Name&quot;].str.cat(df[&#39;Last Name&#39;], sep =&quot;,&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*DDhhnRXnvYi9plpJIWy6Jw.png" /></figure><ul><li>Filter data</li></ul><pre>df1 = df[df[‘First Name&#39;]==&#39;blair&#39;] #contains value</pre><pre>df1 = df[df[‘First Name&#39;]!=&#39;blair&#39;] #does not contain value</pre><ul><li>Frequency of element in column</li></ul><pre>df[‘First Name&#39;].value_counts() #return count for each element</pre><pre>df[&#39;First Name&#39;].value_counts().max() #return max count</pre><pre>df[&#39;First Name&#39;].value_counts().idxmax() #return element with max count</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61abee46ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[my notes: Python Data Structures]]></title>
            <link>https://reinec.medium.com/my-notes-python-data-structures-65ff5c612c26?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ff5c612c26</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python-beginner]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 17:44:01 GMT</pubDate>
            <atom:updated>2020-04-14T09:20:05.683Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>“Where then do I look for good and evil? Not to uncontrollable externals, but within myself to the choices that are my own …” — EPICTETUS</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9KYu_ii33qJas9hTQKkeQ.png" /><figcaption>Data structures in Python</figcaption></figure><p>Data type does not have to be explicitly specified and is mutable.</p><ul><li>Check data type: <em>type()</em></li></ul><pre>x = 1</pre><pre>type(x)<br>&gt;&gt; int</pre><ul><li>Convert data type: <em>int()</em>,<em> float()</em>,<em> str()</em></li></ul><h3>Primitive</h3><p>1.Integers</p><p>2.Float (Decimal)</p><p>3.Strings</p><ul><li>Concatenate using +. Works on numbers that are stored as string</li></ul><pre>x = ‘hello&#39;<br>y = ‘world&#39;<br>x + y<br>&gt;&gt; ‘hello world&#39;</pre><pre>x = ’5&#39;<br>y = ‘6&#39;<br>x + y <br>&gt;&gt; ’56&#39;</pre><ul><li>Repeat string using *</li></ul><pre>x = * 2<br>&gt;&gt; ‘hellohello&#39;</pre><ul><li>Access string (positive and negative indexs)</li></ul><pre>x[1]<br>&gt;&gt; ‘e&#39;</pre><pre>x[-3:-1]<br>&gt;&gt; ‘ll&#39;</pre><ul><li>Slice string</li></ul><pre>x[1:]<br>&gt;&gt; ‘ello&#39;</pre><pre>x[0] + x[4]<br>&gt;&gt; ‘ho&#39;</pre><ul><li>Capitalize</li></ul><pre>x.capitalize()<br>&gt;&gt; ‘Hello&#39;</pre><pre>str.capitalize(‘hello’)<br>&gt;&gt; ‘Hello&#39;</pre><ul><li>Length</li></ul><pre>len(x)<br>&gt;&gt; 5</pre><ul><li>Replace string with other strings</li></ul><pre>x.replace(‘ello’, y)<br>&gt;&gt; ‘hworld&#39;</pre><pre>x.replace(‘ello’, ‘ey’)<br>&gt;&gt; ‘hey&#39;</pre><ul><li>Count occurrence of substring within string</li></ul><pre>a = ‘abcabcabcd&#39;<br>b = ‘abc&#39;</pre><pre>a.count(b)<br>&gt;&gt; 3</pre><pre>a.count(‘abcd’)<br>&gt;&gt; 1</pre><ul><li>Find lowest index within string where substring is found</li></ul><pre>x = ‘hello&#39;<br>z = ‘ello&#39;</pre><pre>x.find(z)<br>&gt;&gt; 1</pre><pre>x.find(‘llo’)<br>&gt;&gt; 2</pre><ul><li>Returns a list of words in a string using a delimiter</li></ul><pre>x = &#39;h e l l o&#39;</pre><pre>x.split(&#39; &#39;)<br>&gt;&gt; [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]</pre><ul><li>Remove leading and trailing whitespace. lstrip() to remove leading whitespace and rstrip() to remove trailing whitespace</li></ul><pre>x = &#39;    hello   &#39;</pre><pre>x.strip()<br>&gt;&gt; ‘hello&#39;</pre><ul><li>Insert numbers into strings</li></ul><pre>x = ‘I have {} cherries and {} fishes.&#39;<br>a = 5<br>b = 6</pre><pre>print(x.format(a, b))<br>&gt;&gt; I have 5 cherries and 6 fishes. </pre><p>4.Boolean</p><ul><li>Returns <em>True</em> or <em>False</em> (interchangeable with 1 and 0)</li></ul><h3>Non-Primitive</h3><p>More sophisticated data structure which allows a collection of data in various formats</p><p>1.Array</p><ul><li>Similar to lists, except that the types of objects store within it is constrained</li><li>Not the same as numpy array</li><li>Able to apply function to entire array as all objects are of the same data type. Faster processing and uses lesser memory</li><li>Type is specified at creation with type code eg ‘I’</li></ul><pre>import array as arr</pre><pre>x = arr.array(’I’, [1,2,3])</pre><p>2.List (create using [ ])</p><ul><li>Store heterogeneous objects</li><li>Mutable</li><li>Access list using [ ]</li></ul><pre>x = [] # Create empty list<br>x = [1, 2, 3] # Create list</pre><pre>x = list([1, ‘apple’, 2, 3]) # x = [1, ‘apple’, 2, 3] is the same</pre><pre>x[1]<br>&gt;&gt; ‘apple&#39;</pre><ul><li>Replace objects in list</li></ul><pre>x[1] = ‘cherry’</pre><pre>print(x)<br>&gt;&gt; [1, ‘cherry’, 2, 3]</pre><ul><li>Appending to list</li></ul><pre>x = [1,2,3,4,5]<br>x.append(6) #Adds to the last position by default</pre><pre>print(x)<br>&gt;&gt; [1,2,3,4,5,6]</pre><ul><li>Append to list at specific index</li></ul><pre>x.insert(0, 9)</pre><pre>print(x)<br>&gt;&gt; [9,2,3,4,5]</pre><ul><li>Remove item at specified index</li></ul><pre>x.pop(0) #Remove object at index 0</pre><pre>print(x)<br>&gt;&gt; [2,3,4,5]</pre><p>3.NumPy Array</p><ul><li>Mutable</li><li>Supports vectorized (element-wise addition, division etc) operations</li></ul><pre>import numpy as np</pre><pre>x = np.array([2, 4, 6, 8])<br>y = x/2</pre><pre>print(y)<br>&gt;&gt; [1. 2. 3.]</pre><ul><li>Create vector of zeros, ones or a constant/string</li></ul><pre>print(np.ones(3))<br>&gt;&gt; [1. 1. 1.]</pre><pre>print(np.zeros((2,2)))<br>&gt;&gt; [[0. 0.]<br>    [0. 0.]]</pre><pre>print(np.full((2,2), ‘x’) # Can also be an integer <br>&gt;&gt; [[‘x’ ‘x’]<br>    [‘x’ ‘x’]]</pre><ul><li>Create identity matrix</li></ul><pre>print(np.eye(2,2))<br>&gt;&gt; [[1. 0.]<br>    [0. 1.]]</pre><ul><li>Create vector of a sequence of numbers</li></ul><pre>np.arange(5)<br>&gt;&gt; array([0,1,2,3,4])</pre><ul><li>Access array and re-assignment</li></ul><pre>x = np.array([[2,4,6], [0,0,0]])</pre><pre>x[0,1]<br>&gt;&gt; 6</pre><pre>x[0,1] = 7</pre><pre>print(x)<br>&gt;&gt; [[ 2 4 7 ]<br>    [ 0 0 0 ]]</pre><pre>y = np.array([1, 2, 3, 4, 5])</pre><pre>y[::2] # x[start:stop:step]<br>&gt;&gt; array([1, 3, 5])</pre><pre>y[::-1] # Reverse objects within array<br>&gt;&gt; array([5, 4, 3, 2, 1])</pre><ul><li>Concatenate array</li></ul><pre>z = np.array([6, 7, 8, 9])</pre><pre>np.concatenate([y, z])<br>&gt;&gt; array([1, 2, 3, 4, 5, 6, 7, 8, 9])</pre><ul><li>Split array</li></ul><pre>x = np.arange(10) </pre><pre>x1, x2 = np.split(x, [3])<br>print(x1, x2)<br>&gt;&gt; [0 1 2] [3 4 5 6 7 8 9]</pre><pre>x1, x2, x3 = np.split(x, [3, 6])<br>print(x1, x2, x3)<br>&gt;&gt; [0 1 2] [3 4 5]  [6 7 8 9]</pre><ul><li>Dimension of array</li></ul><pre>x = np.array([[2,4,6], [0,0,0]])</pre><pre>x.shape<br>&gt;&gt; (2,3)</pre><ul><li>Data type/ type of data within array</li></ul><pre>type(x) # Data type<br>&gt;&gt; numpy.ndarray</pre><pre>x.dtype # Data type of object in array<br>&gt;&gt; dtype(‘int64’)</pre><ul><li>Convert from python list</li></ul><pre>py_list = [1, 2, 3, 4]</pre><pre>np_arr = np.array(py_list)</pre><p>4.Tuples (create using ( ))</p><ul><li>Similar to lists except that they are immutable (cannot do assignment)</li><li>Since they are immutable, processing of tuples are faster as compared to lists</li><li>Access tuple using [ ]</li></ul><pre>x = 1,2,3,4<br>y = (‘a’, ‘b’, ‘c’)</pre><pre>x[0]<br>&gt;&gt; 1</pre><pre>x[0] = 2 # Tuples are immutable<br>&gt;&gt; ERROR!</pre><p>5.Dictionary (create using { })</p><ul><li>Key-Value pair structure. Keys must be unique within a dictionary</li></ul><pre>x = { } # Create empty dictionary</pre><pre>x = {‘apple’: 1, ‘orange’:3, ‘cherry’: 5, ‘fish’: 6}</pre><pre>x[‘apple’]<br>&gt;&gt; 1</pre><pre>len(x)<br>&gt;&gt; 4</pre><pre>del x[‘apple’]</pre><pre>x<br>&gt;&gt; {orange’:3, ‘cherry’: 5, ‘fish’: 6}</pre><p>6.Sets</p><ul><li>Collection of distinct objects (lists with no duplicates)</li><li>Unordered but mutable</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ff5c612c26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[my notes: AWS DNS]]></title>
            <link>https://reinec.medium.com/my-notes-aws-dns-558d22856a0d?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/558d22856a0d</guid>
            <category><![CDATA[aws-route53]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[aws-dns]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 09:01:54 GMT</pubDate>
            <atom:updated>2020-04-05T06:57:54.085Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“When i see an anxious person, I ask myself, what do they want? For if a person wasn’t wanting something outside of their own control, why would they be stricken by anxiety?” — EPICTETUS</blockquote><p><strong>Route 53</strong> is a highly available and scalable Domain Name System (DNS) by Amazon.</p><p>DNS is a service that translate human readable domain name to IP add (IPv4–32 bits &amp; IPv6–128 bits). This allow devices to communicate with each other over the network.</p><p>ELB does not have a pre-defined IPv4 address and we resolve to them using a DNS name.</p><p>Access controls to Route 53 can be managed using AWS IAM service to control users who are allowed to make changes to DNS records.</p><p>Query logging is available using CloudWatch. CloudTrail available fto record and log API call history for Route 53.</p><p>Top level domain names are controlled by IANA (Internet Assigned Numbers Authority)</p><ul><li>Top level: .<strong><em>com</em></strong>, .<strong><em>gov</em></strong>, .com.<strong><em>sg</em></strong>, .gov.<strong><em>sg</em></strong></li><li>Second level: .<strong><em>com</em></strong>.sg, .<strong>gov</strong>.sg</li></ul><p>DNS record types supported by Route 53:</p><p>1.Start of Authority (SOA) record: Every DNS record begins with an SOA record. It contains information such as:</p><ul><li>Name of server that supplied data for the zone</li><li>Administrator of the zone</li><li>Current version of the data file</li><li>Default number of seconds for the time-to-live (TTL) file on resource records (<strong>TTL</strong>: the length a DNS record is cached on the resolving server/ users local PC in seconds. The lower the TTL, the faster changes in DNS propagates throughout the internet. Usually 48 hours)</li></ul><p>2.Name Server (NS) record: Used by top level domain servers to direct traffic to content DNS server which contains authoritative DNS records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUF-SOPSVCohaCgVVRXVBw.png" /></figure><p>3.Address (A) record: Translate name of the domain to an IP address</p><p>4.Canonical Name (CNAME) record: Resolve one domain name to another. eg mapping domain name for mobile website. <a href="http://m.url.com/">http://m.url.com</a> and <a href="http://mobile.url.com/">http://mobile.url.com</a>. CNAME cannot be used for naked domain name (without the www or mobile in domain name)</p><p>5.Alias record: Create alias records to route traffic to selected AWS resources such as ELB, CloudFront, Elastic Beanstalk, API gateway, VPC interface endpoints and S3 buckets configured as websites. They work like CNAME record but is able to map one DNS to another target DNS name (preferred over CNAME).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=558d22856a0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[study notes: Handling Skewed data for Machine Learning models]]></title>
            <link>https://reinec.medium.com/my-notes-handling-skewed-data-5984de303725?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/5984de303725</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[skewed-data]]></category>
            <category><![CDATA[skewness]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 13:05:01 GMT</pubDate>
            <atom:updated>2020-11-04T08:51:15.773Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is skewed when its distribution curve is asymmetrical (as compared to a normal distribution curve that is perfectly symmetrical) and <em>skewness</em> is the measure of the asymmetry. The skewness for a normal distribution is 0.</p><p>There are 2 different types of skews in data, left(negative) or right(positive) skew.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*7U_8hKJyts77ZtcsBvDtmQ.png" /></figure><p><strong>Effects of skewed data:</strong> Degrades the model’s ability (especially regression based models) to describe typical cases as it has to deal with rare cases on extreme values. ie right skewed data will predict better on data points with lower value as compared to those with higher values. Skewed data also does not work well with many statistical methods. However, <strong><em>tree based models are not affected</em></strong>.</p><p>To ensure that the machine learning model capabilities is not affected, skewed data has to be transformed to approximate to a normal distribution. The method used to transform the skewed data depends on the characteristics of the data.</p><p><strong>To check for skew in data:</strong></p><pre>df.skew().sort_values(ascending=False)</pre><p><strong>Dealing with skew data:</strong></p><p>1.log transformation: transform skewed distribution to a normal distribution</p><ul><li>Not able to log 0 or negative values (add a constant to all value to ensure values &gt; 1)</li></ul><pre># Log transform a single column <br>df[‘col1’] = np.log(df[‘col1’] </pre><pre><br># Log transform multiple columns in dataframe <br>df = df[[‘col1&#39;, ‘col2&#39;]].apply(lambda x: np.log(x))</pre><p>2.Remove outliers</p><p>3.Normalize (min-max)</p><p>4.Cube root: when values are too large. Can be applied on negative values</p><p>5.Square root: applied only to positive values</p><p>6.Reciprocal</p><p>7.Square: apply on left skew</p><p>8.Box Cox transformation: transform non-normal to approximate a normal distribution using eqn 1 below, with λ between [-5,5]. The optimum λ is selected which gives the best approximation to a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*6gNVEkLScDe9u3XhTGYj2A.png" /><figcaption>eqn 1</figcaption></figure><p>eqn 1 only works for positive values of y. Use eqn 2 when there are negative values of y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*deSu8im8urSsGPv-9GmuSw.png" /><figcaption>eqn 2</figcaption></figure><p><strong>Skewness in target variable: </strong>Use undersampling, oversampling or SMOTE</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5984de303725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[my notes: AWS Database]]></title>
            <link>https://reinec.medium.com/my-notes-aws-database-aeefcd40ebee?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeefcd40ebee</guid>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-database]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 08:13:07 GMT</pubDate>
            <atom:updated>2020-04-05T06:58:26.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>Relational DB:</h3><ul><li>SQL Server, Oracle, MySQL Server, PostgreSQL, Aurora, MariaDB</li><li>RDS manages backups, software patching, failure detection and recovery</li><li>Automated backups or snapshots</li><li>Provides encryption in transit (SSL) and at rest (AWS KMS). KMS keys are specific to regions they are created in</li><li>Multi AZ (Disaster Recovery): when primary DB fails, DNS will automatically connect to the secondary DB</li><li>Read Replicas (Performance, up to 5 copies): Every write to the primary DB will be replicated to the read replica. When primary DB fails, there is no automatic failover (need to manually connect it to the read replica). Read replica helps to reduce the load on the primary DB by keeping a identical copy of the data and sharing the load of read traffic with the primary DB</li><li>Monitoring using CloudWatch and tracking using CloudTrail</li></ul><p><strong>Aurora:</strong></p><ul><li>Only serverless RDS</li><li>2 copies of data in each AZ, min of 3 AZ. Always have 6 copies. Only in regions with &gt; 3 AZ</li><li>Write availability will not be affected with loss of &lt; 2 copies of data, read availability will not be affected with loss of &lt; 3 copies of data</li><li>Starts with 10GB — 64TB (10GB increments with storage autoscaling)</li><li>Self-healing. Continuously scans for errors and repairs automatically</li><li>Backups and snapshots are performed with no impact on DB performance</li><li>Backups retention period of 1 (default) — 35 days</li><li>Snapshots can be shared with other AWS accounts</li><li>Read Replicas for Aurora: Aurora replicas &amp; MySQL read replicas</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*twua6SWWrV2dMRc_6dtB4g.png" /></figure><ul><li>Migrating MySQL DB to Aurora DB:</li></ul><p>— Create an Aurora read replica from MySQL DB which will create an writer and reader node (in separate AZ and different DNS endpoint). Promote either node to primary.</p><p>— Take snapshot of one of the Aurora read replica node and restore a new Aurora DB from the snapshot.</p><h3>Non-Relational DB:</h3><ul><li>Adding a new field for 1 record does not create a new column across all row that can lead to many empty cells. Can have data with different format/columns</li></ul><p><strong>DynamoDB:</strong></p><ul><li>Severless</li><li>Used for mobile, web, gaming, ad-tech, IoT and many other apps</li><li>Schemaless with initial limit of 256 tables per region</li><li>Supports document and key-value data models</li><li>Data is stored in partition backed by SSD</li><li>Spread across 3 geographically distinct data centres</li><li>Encryption at rest (AWS KMS), only when creating new DynamoDB table. Once enabled, it cannot be disabled</li><li>Backup retention period &lt; 35 days</li><li>Eventual consistent read (default): Consistency is reached &lt; 1s</li><li>Strongly consistent read: Consistency reached in &lt;&lt; 1s (may not be available when there is network delay/ outages)</li><li>Can be monitored using Cloudwatch and tracked using CloudTrail</li></ul><h3>Data Warehousing:</h3><ul><li>Business intelligence</li><li>Cognos, Jaspersoft, SQL Server reporting services, Oracle Hyperion, SAP NetWeaver</li><li>Allow query on large and complex data</li><li>OLTP (Online Transaction Processing): Direct query to extract rows, no computation</li><li>OLAP (Online Analytics Processing): Computation like finding sum, average etc</li><li>Specify DB to be used for OLTP or OLAP</li></ul><p><strong>Redshift (for OLAP):</strong></p><ul><li>Single AZ deployment</li><li>Single node (160Gb)</li><li>Multi-Node: Leader node (manage client connections, receive queries), Compute node (store data, perform queries and computation), maximum of 128 compute nodes</li><li>Advanced compressions: Columnar storage can be compressed more than row-based data stores since data are more similar across columns than rows. Multiple compression techniques. Do not need indexes or materialised views, requiring less space. Automatically samples data and select most appropriate compression scheme.</li><li>Massively Parallel Processing (MPP): distributes data and query across nodes. Easy to scale out (add more nodes) to maintain fast performance</li><li>Backup: 1 day (default) — 35 days. Minimum 3 copies (original and replica on compute node, backup on S3), replicate snapshots to S3 in other region for DR</li><li>Pricing: Compute node hours, backups, data transfer (only within VPC)</li><li>Security: Encrypted in transit (SSL), at rest (AES-256), takes care of key management (client manage own keys using hardware security module (HSM), or AWS key management service (KMS))</li><li>Audit logs are stored in S3 and monitoring through CloudWatch</li></ul><h3>ElastiCache:</h3><ul><li>Improves DB and web application performance using managed in-memory caches instead of relying on slower disk-based databases</li><li>Cache frequent identical queries (list of bestsellers)</li><li>Open-source in-memory caching engine: Memcached (for simplicity), Redis (more advanced caching)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*ZM2R4FTnVE2S-O2baTStOw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeefcd40ebee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[my notes: Missing data & Data imputation]]></title>
            <link>https://reinec.medium.com/my-notes-missing-data-data-imputation-9605c07f523a?source=rss-2730a128ce83------2</link>
            <guid isPermaLink="false">https://medium.com/p/9605c07f523a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-imputation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[missing-data]]></category>
            <dc:creator><![CDATA[Cheryl Lai]]></dc:creator>
            <pubDate>Tue, 14 Jan 2020 17:46:01 GMT</pubDate>
            <atom:updated>2020-03-20T08:57:04.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Do nothing</h3><ul><li>Use algorithm that handle missing data</li><li>XGBoost: Decides best way to impute for each dataset on the training loss reduction</li><li>LightGBM: Input parameter to ignore missing values</li></ul><h3><strong>2. Delete</strong></h3><ul><li>Remove records in the data frame with missing data when the percentage is low (&lt; 5%)</li><li>Remove entire columns when the percentage of missing data in each column is high (&gt; 50 %) and is not an essential feature to the model</li></ul><h3><strong>3. Mean/ Median Imputation</strong></h3><ul><li>Calculate mean/median of each column using the non-missing values and replacing it into the missing cells within each column</li><li>Fast and easy</li><li>Works only for numerical data</li><li>For data with outliers use median instead of mean</li><li>Ignore interrelationships between features</li><li>Diminish any correlations between features with imputations (affects multivariate analysis)</li></ul><h3><strong>4. Mode/ Constant value Imputation</strong></h3><ul><li>Replace the missing cells with the most frequent value occurring within the column</li><li>Replace missing cells with 0 or a user defined constant value</li><li>Fast and easy</li><li>Works for Numerical and Categorical data</li><li>Diminish any correlations between features with imputations (affects multivariate analysis)</li><li>Introduce bias</li></ul><h3><strong>5. K-Nearest Neighbour Imputation</strong></h3><ul><li>Missing values are predicted based on its similarity (feature similarity) to neighbouring points within the data set</li><li>Values from the k neighbouring points can be computed based on the average or weighted distance (for continuous data) and most frequent value (for categorical data)</li><li>Rows to be removed when there are too many cells missing</li><li>The # of training data must be &gt; # of nearest neighbour</li><li>When there are &gt; 1 feature missing, all the other features are used as the multiple neighbour donor</li><li>Works better for numerical data than categorical data</li><li>Creates a single model that can be used across all features</li><li>Slow for large data (scan all data to find most similar)</li><li>Computationally expensive (entire dataset is stored in memory)</li><li>Have to decide choice of K</li><li>Sensitive to outliers</li><li>Accuracy decrease with higher dimension as the difference between the nearest and farthest neighbour is diminished</li></ul><h3><strong>6. Random Forest Imputation</strong></h3><ul><li>Uses a random forest model to impute missing data by using it as the target variable</li></ul><h3><strong>7. Multivariate Imputation by Chained Equation (MICE) Imputation</strong></h3><ul><li>Multiple regression models are created sequentially by using different columns with missing values as the target variable.</li><li>A regression model is fitted to the predictors to impute the missing data</li><li>With the imputation in the target variable, another column with missing value is chosen as the target variable and fitted on the original and imputed data</li><li>The imputation is repeated and at the end of 1 cycle, all the columns with missing values are filled will be filled by the predictions from regression models</li><li>The cycle is repeated by n times (where n is user defined) or when the coefficient in the regression models converges</li><li>High accuracy</li><li>Works for Numerical and Categorical data</li><li>Measures uncertainty of missing values</li><li>Able to handle complexities in data such as bounds or skip patterns</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*nZOF23L4gLDwD4TUhFNG-w.png" /></figure><h3><strong>8. Deep Learning Imputation</strong></h3><ul><li>Build a neural network model to impute missing values for both categorical and numerical features</li><li>Preferred choice for categorical data</li><li>Model is able to work with categorical data using feature encoder</li><li>Imputations are done on single column each time by specifying features used for training (on target variable)</li><li>Slow for large data</li></ul><h3><strong>9. Extrapolation/ Interpolation</strong></h3><ul><li>Interpolation is estimating the missing value based on other observations within the range of a set of known data points</li><li>Extrapolation is estimating beyond the range of the data and requires more assumptions</li></ul><h3><strong>10. Regression Imputation</strong></h3><ul><li>Predict missing values (as target variable) by using a regression line and relevant features as predictors from data</li><li>Assumes linear relationship between features</li><li>May affect/restrict variability and distribution of data</li></ul><h3><strong>11. Stochastic Regression Imputation</strong></h3><ul><li>Similar to regression imputation with an additional residual term added to each prediction</li><li>Residual term is normally distributed with mean = 0 and variance = variance of predictor variable</li></ul><h3><strong>12. Hot-Deck Imputation</strong></h3><ul><li>Find sample of points that are similar to the missing values on other variables and randomly choosing a point from the sample</li><li>Imputation is restricted to the range of the sample</li><li>The random component increases variability in the data</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9605c07f523a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>