<?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[KenLok - Medium]]></title>
        <description><![CDATA[My musings and experiments. My notebook - Medium]]></description>
        <link>https://medium.com/kenlok?source=rss----29fe98de7b5---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>KenLok - Medium</title>
            <link>https://medium.com/kenlok?source=rss----29fe98de7b5---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:06:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/kenlok" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to create a calendarGraph]]></title>
            <link>https://medium.com/kenlok/how-to-create-a-calendargraph-1f3de780d479?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/1f3de780d479</guid>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Mon, 17 Jun 2019 08:06:14 GMT</pubDate>
            <atom:updated>2019-10-22T02:12:55.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*jP92HY8CmktGCxL5QL2nuQ.png" /></figure><h4>Why Calendar Graph?</h4><p>I had a need to draw a heatmap on a calendar of sorts, scoured the internet for some examples but came up with very few results. This article serves to fill that gap.</p><p>This is similar to GitHub’s contribution graphic. However in this example, the aim is to show activity versus inactivity as compared to GitHub’s aim to show level of activity.</p><p>The full code and raw data sample can be found on my GitHub:</p><p><a href="https://github.com/ken333135/calendarGraph">https://github.com/ken333135/calendarGraph</a></p><h4>The starting point / data</h4><p>For my purpose, i wanted to have a visual representation of my reading activity throughout the year. The data which i had looked something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*xidtQHC18jp_onLmhIQ98A.png" /><figcaption>DataSet for Books Read</figcaption></figure><h4>The Transformations</h4><p>Before we can plot this into a calendarGraph, there are a few transformations we would have to make to the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff172d4c9877b0343948a39815d1d7a/href">https://medium.com/media/5ff172d4c9877b0343948a39815d1d7a/href</a></iframe><p>The code above converts the datetime from string format to the datetime format in Python. We also get the earliest and latest date (min_date, max_date)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/589fcea911a187791d88e7e326d2c532/href">https://medium.com/media/589fcea911a187791d88e7e326d2c532/href</a></iframe><p>Following that we transform the data into a format where every row contains information for a single day.</p><p>This is what the bookv2 looks like once it is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*9GkvpiXtKde8aI7CzXDQ3Q.png" /></figure><p>Next up we have to generate the ‘calendar’ that we would be plotting. This means 365 rows for the 365 days in a year. To do this we make use of a helper function date_generator</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b669992a48bb64f73d31676150fa4f8d/href">https://medium.com/media/b669992a48bb64f73d31676150fa4f8d/href</a></iframe><p>Then we combine the 2 dataframes we have so far to create a table that contains 2 columns. First column being the ‘Date’, 1 row for every day in the year. The second column is the ‘Title’, days where there are no reading activity are filled with a ‘NaN’</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d14e88871ebaeeb35fd9c2b8a0e253/href">https://medium.com/media/a9d14e88871ebaeeb35fd9c2b8a0e253/href</a></iframe><p>Following that, we create additional columns to store essential information for the actual plotting. We create columns for ‘Day of Week (DOW)’, ‘Week_number’, ‘Month_number’ etc.</p><p>The column ‘color_proxy’ is the column that will tell the plot later what color to fill each cell with. The color_proxy is just a number between 0 to 12. 0 being the number for ‘white/no color’ which signifies no reading activity. The numbers 1 to 12 correspond to a different color for each month in a year.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d52a01fcf34842eac6cdb123f9790e32/href">https://medium.com/media/d52a01fcf34842eac6cdb123f9790e32/href</a></iframe><p>Finally the last part is to define the color map ‘cmap’.</p><p>The length of the list cmap should correspond to ‘color for empty’+’color for each month’, so that would be 1 + 12 = 13 colors.</p><p>If everything went alright, you should have yourself a plot that shows the 12 months in a year with colored cells for days that have activity.</p><p>It is not the prettiest or most polished graph at the moment, but i hope this serves as a good starting point for those that are looking to draw something similar!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f3de780d479" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/how-to-create-a-calendargraph-1f3de780d479">How to create a calendarGraph</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Create Sankey Diagrams from DataFrames in Python]]></title>
            <link>https://medium.com/kenlok/how-to-create-sankey-diagrams-from-dataframes-in-python-e221c1b4d6b0?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/e221c1b4d6b0</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sankey]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Wed, 08 May 2019 08:18:41 GMT</pubDate>
            <atom:updated>2019-05-08T08:13:40.129Z</atom:updated>
            <content:encoded><![CDATA[<h4>A wrapper for Plotly’s Sankey Diagram to make life easier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*McsRlQR9dg5zlc1RFQpQXg.png" /><figcaption>Example of basic Sankey Diagram</figcaption></figure><p>The Sankey Diagram is a plot that can tell a story. It is a form of flow diagram in which the width of the flow arrows is proportional to the quantity of flow.</p><p>It is a perfect visual tool for visualizing the apportionment from an initial pot to subsequent smaller pots. Some great examples of how a Sankey Diagram can tell a beautiful visual story of <a href="https://www.reddit.com/r/dataisbeautiful/comments/bludr6/annual_spending_breakdown_for_households_whose/">Annual Household Spend</a> as well as a <a href="https://www.reddit.com/r/dataisbeautiful/comments/bl5gwz/the_search_for_a_software_engineering_role/">Job Search Process</a>.</p><p>So how do we create a Sankey Diagram. Let’s get to it</p><h4>What makes up a Sankey Diagram?</h4><p>A Sankey Diagram is basically made up of <em>source </em>and <em>target </em>pairs. Flows run from the source to the target. Each of these flows then have a value/size of the flow.</p><h4>The Data</h4><p>Let’s take for example a set of data that we would like to visualize using a Sankey Diagram. In Python, it is common to have your data in a dataframe. Below is a sample of the dataset we will be working with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*vMAuzRm1TEvIue3oUu5a_g.png" /><figcaption>Sample Dataset</figcaption></figure><p>This format of dataset with levels in different columns can be very easily obtained using the ‘groupby().agg()’ function in python. Documentation on how to use it can be found <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*McsRlQR9dg5zlc1RFQpQXg.png" /><figcaption>Example of basic Sankey Diagram</figcaption></figure><p>This is the final output we are trying to get. In a glance one can visually determine the flow of the data as well as the relative proportions of each of the flows.</p><h4>Wrapper Function for Plotly’s Sankey</h4><p>Below is the wrapper function that i used to generate the fig needed to create a plotly Sankey Diagram.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a87a2a77e9d2b30a8434459cbb69ef/href">https://medium.com/media/48a87a2a77e9d2b30a8434459cbb69ef/href</a></iframe><p>In short what the wrapper function does is <br>1. Take in a dataframe specified by the user<br>2. Creates ‘source’ and ‘target’ pairs according to the column specified by the user<br>3. Creates an aggregated ‘value’ for each ‘source’ and ‘target’ pair<br>4. Feed those values into the fig object as defined by Plotly<br>5. Return a fig object that can be used to create a Plotly Sankey Diagram</p><h4>How to use the genSankey function</h4><pre>genSankey(df,cat_cols=[],value_cols=&#39;&#39;,title=&#39;Sankey Diagram&#39;)</pre><p><em>df</em> is in the same format as our sample dataset shown above,which is the standard output of pandas’ groupby().agg()</p><p><em>cat_cols </em>is a list of the columns that you want to include in your flow diagram. So in this case it would be <em>[‘lvl1’,’lvl2&#39;,’lvl3&#39;,’lvl4&#39;]</em> if we want to include all 4 levels in our diagram.</p><p><em>value_cols</em> is a string that should be the column name of your ‘values’ for each flow. In this case it would be <em>‘count’.</em></p><p><em>title</em> is as the name suggests, the title we would like to give to our Sankey diagram.</p><p>In python code, it would look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd111a4f74e311031026e36a48926dc3/href">https://medium.com/media/cd111a4f74e311031026e36a48926dc3/href</a></iframe><p>Running the above script would generate a Sankey Diagram in a html file that you can save to your local drive.</p><p>Voila! A quick and easy way to create a Sankey Diagram from your dataframe.</p><p>If you are interested to modify the function on your own, the docs for Plotly’s Sankey can be found <a href="https://plot.ly/python/sankey-diagram/">here</a></p><p>Do leave a comment and let me know if this helped you!<br>Look out for Part 2 where i will explain the genSankey function and what it does under the hood in greater detail</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e221c1b4d6b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/how-to-create-sankey-diagrams-from-dataframes-in-python-e221c1b4d6b0">How To Create Sankey Diagrams from DataFrames in Python</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to draw an Interactive Network Graph using Dash]]></title>
            <link>https://medium.com/kenlok/how-to-draw-an-interactive-network-graph-using-dash-b6b744f60931?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/b6b744f60931</guid>
            <category><![CDATA[network-graph]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 06:34:45 GMT</pubDate>
            <atom:updated>2018-10-31T06:34:45.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*_056ZJFNisIEAZzKtu2lmg.png" /></figure><p>So in a recent project, i was working with basket data analysis. Using Association Rule Mining, i was able to extract a list of item rules.</p><p>Each rule has a corresponding value of Support, Confidence and Lift. The details of which are for another post altogether.</p><p>This post is dedicated to trying to visualise these set of rules in a network graph. Doing so will allow us to identify clusters of items frequently bought together and pick out complement items and itemsets.</p><p>Through my trusty friend google, i wasn’t able to find an existing library that would allow me to plot all of these rules in an interactive way. The closest i could find was this documentation from Dash, and my code is an adaptation of the code <a href="https://plot.ly/python/network-graphs/">here</a>. Hence, the reason for this post, to share what i have learnt with everyone and as documentation for future me.</p><h4>The Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*pWKyG99i8Jg0dV4cir68Sg.png" /><figcaption>The Dataset of Association Rules</figcaption></figure><p>A brief description of the columns above</p><p>itemset : (item x, item y) and the rule is read {x-&gt;y}</p><p>count : how often this itemset appears in the whole dataset</p><p>support_x : support of item x</p><p>support_y : support of item y</p><p>support : support of the itemset (x,y)</p><p>confidence : how often the rule {x-&gt;y} holds true</p><p>lift : shows the existence/lack of relationship between x and y</p><p>As i generated the Association Rules for every possible itemset in the entire dataset, i had about 300,000+ rules. However, the count and support for the rules quickly taper off when sorted in descending order. Hence for the visualisation, we will only be plotting the top 2000 Association Rules.</p><h3>Using Dash</h3><p>If you are not familar with using Dash, this might be a little confusing for you. <a href="https://plot.ly/products/dash/">Dash is a Python framework for building analytical web applications</a>. Very useful for building dashboards and interactive visualisations.</p><p>Our aim is to create a connected graph, where the user can explore and investigate the clusters within the graph.</p><p>Libraries that we will be using</p><pre>import dash<br>import dash_html_components as html<br>import dash_core_components as dcc<br>from dash.dependencies import Input, Output<br>import plotly.graph_objs as go</pre><pre>import networkx as nx</pre><p>networkx is the main library that makes our visualisation work. To understand more about graphs, nodes and edges, head over to their <a href="https://networkx.github.io/documentation/networkx-1.10/tutorial/index.html">docs </a>to get up to speed.</p><h4>Creating the Graph using networkx</h4><pre>num_nodes = 2000<br>edge = df[&#39;itemset&#39;][:num_nodes]</pre><pre>#create graph G<br>G = nx.Graph()<br>#G.add_nodes_from(node)<br>G.add_edges_from(edge)<br>#get a x,y position for each node<br>pos = nx.layout.spring_layout(G)</pre><p>First we define how many rules we want to plot, in this case 2000.</p><p>nx.Graph() initializes a networkx graph.</p><p>Adding edges (relationship between 2 nodes) to a graph automatically creates the corresponding nodes as well. Hence in our case, we only need to add edges. If you have a node that is not connected, and is all by its lonsesome, then you need to add that node into the graph.</p><p>To add an edge to the graph, simply use G.add_edges_from([(1,2),(2,3)]). This will add 2 edges (1,2) and (2,3), as well as 3 nodes, [1,2,3] to the graph. The function accepts a list of tuples of edges.</p><p>pos = nx.layout.spring_layout(G) assigns each of the node in the graph a x and y coordinate, so that they can be plotted onto a graph. There are other types of layout such as random_layout, shell_layout, circular_layout and you can try them out and see which suits your needs.</p><h4>Creating the Edges</h4><pre>#Create Edges<br>edge_trace = go.Scatter(<br>    x=[],<br>    y=[],<br>    line=dict(width=0.5,color=&#39;#888&#39;),<br>    hoverinfo=&#39;none&#39;,<br>    mode=&#39;lines&#39;)</pre><pre>for edge in G.edges():<br>    x0, y0 = G.node[edge[0]][&#39;pos&#39;]<br>    x1, y1 = G.node[edge[1]][&#39;pos&#39;]<br>    edge_trace[&#39;x&#39;] += tuple([x0, x1, None])<br>    edge_trace[&#39;y&#39;] += tuple([y0, y1, None])</pre><p>What the above code is doing is first creating a go.Scatter (this is a method in Dash) trace for the edges. Then it creates a line for each edge by iterating through all the edges in G.edges(). This is directly from the Dash docs.</p><h4>Creating the Nodes</h4><pre>node_trace = go.Scatter(<br>    x=[],<br>    y=[],<br>    text=[],<br>    mode=&#39;markers&#39;,<br>    hoverinfo=&#39;text&#39;,<br>    marker=dict(<br>        showscale=True,<br>        colorscale=&#39;YlGnBu&#39;,<br>        reversescale=True,<br>        color=[],<br>        size=10,<br>        colorbar=dict(<br>            thickness=15,<br>            title=&#39;Node Connections&#39;,<br>            xanchor=&#39;left&#39;,<br>            titleside=&#39;right&#39;<br>        ),  <br>        line=dict(width=2)))</pre><pre>for node in G.nodes():<br>    x, y = G.node[node][&#39;pos&#39;]<br>    node_trace[&#39;x&#39;] += tuple([x])<br>    node_trace[&#39;y&#39;] += tuple([y])</pre><p>Basically the same method as creating edges. First create a trace in Dash and then populating it by iterating through all the nodes in G.nodes().</p><h4>Adding color and hovertext</h4><pre>#add color to node points<br>for node, adjacencies in enumerate(G.adjacency()):<br>    node_trace[&#39;marker&#39;][&#39;color&#39;]+=tuple([len(adjacencies[1])])<br>    node_info = &#39;Name: &#39; + str(adjacencies[0]) + &#39;&lt;br&gt;# of connections: &#39;+str(len(adjacencies[1]))<br>    node_trace[&#39;text&#39;]+=tuple([node_info])</pre><p>For Dash graphs, there is an option to show information when the user hovers over the points on the plot. This is determined by node_trace[&#39;text&#39;]and node_info specifies what information is shown on hover.</p><p>The above code loops through all the nodes and adjacent nodes (adjacent means that they are connected) in the graph. It adds color to the node, specifies the hovertext to display for each node and adds it to the node[‘text’]</p><p>There we have created the graph! *Applause* But how do we display it though? Next part will be where Dash comes in.</p><h4>Creating the Dash Visualisation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87697c0e1594c8b8eda2c02e858e0da8/href">https://medium.com/media/87697c0e1594c8b8eda2c02e858e0da8/href</a></iframe><p>The above code creates the network graph in Dash. Notice that data=[edge_trace,node_trace] which we have created and populated earlier. Most of the code above is from the Dash networkx docs as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39c945fb4c019793bcdde630ad733c53/href">https://medium.com/media/39c945fb4c019793bcdde630ad733c53/href</a></iframe><p>app.layout is what specifies how your Dash app looks. I won’t explain how it works in this post.</p><p>@app.callback allows your graph to be interactive and listen to user events such as click or selection.</p><h4>Final Product</h4><p>This is how the Dash app looks once you have done all that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LTZ-YHzg2W3JCIdyNevdw.png" /><figcaption>Screen Capture of Dash App</figcaption></figure><p>Using the box select tool, the user can select a cluster of interest. Then the number of nodes selected and the names of the nodes within the selection will be printed on screen.</p><p>Hovering the mouse over the points will display the name of each node and the number of connections they have as well.</p><p>The full code can be found on GitHub as well.</p><p><a href="https://github.com/ken333135/NetworkGraphDash">ken333135/NetworkGraphDash</a></p><p>Hope this was of help and made for an interesting read!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b744f60931" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/how-to-draw-an-interactive-network-graph-using-dash-b6b744f60931">How to draw an Interactive Network Graph using Dash</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 things i learnt with my first React App]]></title>
            <link>https://medium.com/kenlok/3-things-i-learnt-with-my-first-react-app-7c57eb7068aa?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/7c57eb7068aa</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning-journey]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Mon, 03 Sep 2018 03:59:31 GMT</pubDate>
            <atom:updated>2018-09-03T03:59:31.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Having completed my first mini-project after learning about ReactJS about a month ago, here are the top 3 points as a memo to myself and others who are just starting out like me!</p><p>I started out with this <a href="https://reactjs.org/tutorial/tutorial.html">tutorial</a> which gives a good step by step on the installation and getting started</p><p>To better understand what i am talking about, the GitHub repo and app link are below:<br><a href="https://github.com/ken333135/RegExplorer">Github</a><br><a href="https://regexplorer.herokuapp.com/">RegExplorer</a></p><h3>Use of Functions and Components</h3><p>This serves 2 purposes, code reusability and cleanliness.<br>First thing to know is that the main part of a ReactApp is this part here</p><pre>class App extends React.Component {<br>    render(<br>    &lt;your HTML here&gt;<br>    )<br>}</pre><p>This render()is where all your HTML and JSX code goes and this ultimately creates the HTML that is your page/app. Instead of writing all your HTML in this render() ,you can use functions and components to make your code look cleaner. Here is what i mean.</p><pre>render() {<br>    return(<br>      &lt;div&gt;<br>        &lt;div&gt;&lt;CreateHeader /&gt;&lt;/div&gt;<br>        &lt;div className=&quot;leftbox&quot;&gt;<br>          &lt;CreateTextbox/&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;rightbox&quot;&gt;<br>          &lt;CreateRegexbox /&gt;&lt;br/&gt;<br>          &lt;CreateOutputbox /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><p>This is what my render() looks like, easy to read at a glance and anyone else looking at it should be able to understand what is going on in your code as well. CreateHeader, CreateTextbox, CreateRegexbox and CreateOutputbox are all functions that i created in my code.</p><pre>function CreateHeader(props) {<br>  return (<br>    &lt;div className=&quot;headerContainer&quot;&gt;<br>      &lt;h1 style={{fontFamily:&quot;Arvo&quot;}&gt;RegExplorer&lt;/h1&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>CreateHeader creates a &lt;div&gt; that contains a &lt;h1&gt; header as title for my App. Imagine if i had 20 lines of HTML instead of 3, having a function to create my header helps to reduce the clutter and improve legibility. Another great benefit would be if i for some reason wanted to have multiple headers, i can simply call the createHeaderfunction however many times i want in class App render().</p><p>Functions also allow you to do pre-processing and computations before rendering your output. For example</p><pre>function CreateOutputbox(props) {<br>  var output = &#39;&#39;;<br>  var x;<br>  for (x in props.output) {<br>    output += props.output[x]+&#39; &#39;;<br>  }<br>  return (<br>    &lt;div className=&quot;outputboxContainer&quot;&gt;<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;p id=&quot;outputbox&quot;&gt;{output}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here i do some string manipulation before returning the output as part of the HTML.</p><p>*Important* Anything within the { } in the return() is read as JavaScript by React. Hence you can return variables or even perform operations within the curly braces.</p><h3>Methods need to be declared and bound in the parent class</h3><p>React components/functions also work with the idea of parent and children, where the child component/function can inherit certain attributes/methods from the parent class.</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      text: &#39;&#39;,<br>      regex: &#39;&#39;,<br>      output: &#39;hello&#39;<br>    };<br>    this.handleTextChange = this.handleTextChange.bind(this);<br>    this.handleRegexChange = this.handleRegexChange.bind(this);<br>  }</pre><p>In my case, i wanted my parent class ‘App’ to have the 3 states (kind of like properties) of [text, regex, output]. Using a constructor, i initialise the 3 states in the ‘App’ class. I also want these states to be changed whenever a value is changed in one of the children functions (regexbox, textbox).</p><p>To do so, i have to create a method which allows for the updating of the 3 states within the parent class ‘App’.</p><pre>class App extends React.Component {<br>  constructor(props) {<br>  &lt;...&gt;<br>  }</pre><pre> handleTextChange(event) {<br>    this.setState({text: event.target.value});<br>    let output<br>    try {<br>      output = (event.target.value).match(RegExp(this.state.regex,&#39;g&#39;))<br>    }<br>    catch(err) {<br>      output = &quot;Error!&quot;<br>    }<br>    this.setState({output:output})<br>  }<br>}</pre><p>I create a method handleTextChange(event) that listens for an event (a text change in this case) and then does some update of the state accordingly, using the this.setState method.</p><p>This method has to be bound to the parent class ‘App’ in the constructor</p><pre>this.handleTextChange = this.handleTextChange.bind(this);</pre><p>Only then can it be passed to the child function as a prop. I do this when i call the function CreateTextbox in the render()</p><pre>render() {<br>    return(<br>      &lt;div&gt;<br>        &lt;div&gt;&lt;CreateHeader /&gt;&lt;/div&gt;<br>        &lt;div className=&quot;leftbox&quot;&gt;<br>          &lt;CreateTextbox text={this.state.text} handleTextChange={this.handleTextChange} /&gt;<br>        &lt;/div&gt;<br>      ...<br>     &lt;/div&gt;<br>}</pre><p>With this, the child function CreateTextbox will have 2 props of [text, handleTextChange] passed on to it. In the funciton, the props can be accessed via props.&lt;propname&gt; which in this case would be props.handTextChange</p><pre>function CreateTextbox(props) {<br>  return (<br>    &lt;div className=&quot;textboxContainer&quot;&gt;<br>      &lt;div className=&quot;labelbox&quot;&gt;<br>        &lt;label for=&quot;textbox&quot;&gt;Your Text Here&lt;/label&gt;<br>      &lt;/div&gt;<br>      &lt;textarea id=&quot;textbox&quot; onChange={props.handleTextChange}  /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>this.setState is asynchronous</h3><p>What does asynchronous mean? I found a good explanation <a href="https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean">here</a></p><blockquote>When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.</blockquote><p>I don’t really know how to explain it, so let me try to illustrate with an example.</p><p>Let’s say:<br>this.state.text = ‘originalhello’<br>event.target.value = ‘hello’</p><pre>handleTextChange(event) {<br>    this.setState({text: event.target.value});<br>    output = (this.state.text)<br>    this.setState({output:output})<br>  }</pre><p>In the above case, output = ‘originalhello’.</p><p>This is because event though line2 attempted to change the state of text to ‘hello’, because this.setState is asynchronous, it does not wait for the task to finish before moving on to the next. Hence output is still assigned the value of this.state.text’s original value of ‘originalhello’</p><p>However if we tweak it abit</p><pre>handleTextChange(event) {<br>    this.setState({text: event.target.value});<br>    output = (event.target.value)<br>    this.setState({output:output})<br>  }</pre><p>In this case, output = ‘hello’</p><h3>TheEnd</h3><p>That sums up the 3 main points i took away from this experience. Please pardon any inaccuracies or fuzzy explanations, if you are an experience React user reading this, please kindly point me in the right direction! Comment below and let me know if there are any points i got grossly wrong. Thanks for your help in advance :D</p><p>Or if you are new like me as well, do let me know your own experiences and things you picked up along the way. To share is to learn and grow together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c57eb7068aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/3-things-i-learnt-with-my-first-react-app-7c57eb7068aa">3 things i learnt with my first React App</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a Flask app on Heroku vs Azure]]></title>
            <link>https://medium.com/kenlok/setting-up-a-flask-app-on-heroku-vs-azure-ee7616369b11?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/ee7616369b11</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 07:55:14 GMT</pubDate>
            <atom:updated>2018-08-20T07:55:14.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/438/0*ayL0j9alkeIgoUj5.png" /></figure><p>This post serves as a quick guide to deploying your Flask web-app on Azure and Heroku, as well as a comparison of the ease of the whole process.</p><p>I decided to write this down for my own reference in the future, and for anyone else who may be trying to achieve the same. The countless hours i spent googling and figuring it where i went wrong, i hope this will save someone else from that same process.</p><h3>Azure</h3><p>First let’s start with the deployment on Azure.</p><p>I found this really good guide on <a href="http://timmyreilly.azurewebsites.net/starter-site-for-flask-on-azure-web-apps/">Timmy’s blog</a>.</p><p>He provides an awesome step by step explanation of the process, and he has a repo with all the required template files. This part is really important as Azure has many “required” files that are not part of the standard Flask file structure.</p><p>Without these config files, your Flask web app will not be able to run on the Azure cloud even after you have deployed your app.</p><p>Files such as</p><ul><li>.deployment</li><li>deploy.cmd</li><li>requirements.txt</li><li>web.2.7.config and web.debug.config</li></ul><p><a href="http://timmyreilly.azurewebsites.net/starter-site-for-flask-on-azure-web-apps/">Timmy’s blog</a> goes into great detail about what each of these files does, so you should definitely head over to check that out if you are interested.</p><p>However, following his steps faithfully unfortunately did not work out 100% for me. Perhaps it was because one of the packages (pandas) i required in my web app was not part of the standard in Azure’s python 2.7</p><p>Additionally, installing one of these packages required a compiler, which was not available on the Azure App Service.</p><p>Hence more googling brought me to <a href="http://jackstromberg.com/2018/07/installing-python-wheel-files-on-an-azure-app-service/">JackStromberg’s blog</a>. Here he explains how to use wheel files to install packages/modules that cannot be installed normally with pip.</p><p>Following his instructions, i was able to obtain the wheel (.whl) files on the Azure App service. Using the wheel files, i was able to get the pandas module. I thought that would fix the “Internal Server Error” i kept getting from the Azure App Service whenever i tried to access my site</p><p>Unfortunately, it was still not to be. After debugging my code line by line, i finally found the cause of the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*UNMy7_tRGqsKyqNhtVVXTA.png" /></figure><p>I was uploading and reading in a .xlsx excel file. When run locally on my own machine, this worked fine with the pandas version 0.20.3.</p><p>The frustrating part was that with the same version of pandas installed on the Azure App Service, the code kept failing on the <em>pandas.ExcelFile</em>. After hours of googling and trying different methods including <em>pandas.read_excel,</em> I was still stuck with the same error.</p><p>After countless hours, i finally decided to abandon hosting my app on Azure and switch to Heroku instead</p><h3>Heroku</h3><p><a href="https://www.heroku.com/">Heroku</a> is also a Platform as a Service (PaaS) much like Azure.</p><p>I am going to say it right now, the process was a 100 times easier on Heroku. It took me just under 2 hours to get my Flask app up and running on the Heroku servers.</p><p>To deploy, you can choose to use the Heroku Dashboard on your browser or download the <a href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a> and deploy your app from the command line.</p><p>I am going to show an example using the Dashboard.</p><p>First click on the “New” button on the top right of your Heroku Dashboard, and choose “Create New App”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOJYqxl_BYe1KTXZtMkBoQ.png" /></figure><p>Next, give your app a name and choose a region (Only US and Europe are available, i reside in Asia and it works fine as well)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*aklY-7DIu94snkm6SrlNBQ.png" /></figure><p>Then choose your deployment method, in my case i chose Github. You will be prompted to log in to your Github account and give permissions to Heroku to access the repos in your account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*L24DRjec6uaOI3dWZ80ESA.png" /></figure><p>Once done, you can choose between “Automatic deploys” or “Manual deploy”. Automatic means everytime you push a change to your Github repo, Heroku will run a build process for your web app. Manual deploy only triggers when you hit the “Deploy Branch” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSmiH8hYeZjm2hl7AalAzA.png" /></figure><p>And there you have it! Your web app is now running on the Heroku servers.</p><p>Except not quite, if you are using Flask, you will need to do these 2 steps/add these files to your project folder.</p><ol><li>Procfile</li></ol><p>The Procfile should be a text file that is named <strong>“Procfile”</strong> and not “Procfile.txt”. This should be placed in the app’s root directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*1s1JwD1dfBV4M2ReclCF5Q.png" /></figure><p><a href="http://gunicorn.org/">Gunicorn</a> is a pure-Python HTTP server for WSGI applications. More information can be found <a href="https://devcenter.heroku.com/articles/python-gunicorn">here</a></p><p><em>main:app </em>is the part you must take note off. i use “main” in this case because my Flask file is called “main.py”. If yours was “app.py” then you would put <em>app:app </em>in your Procfile (important!)</p><p>2. requirements.txt</p><p>The requirements.txt tell Heroku what modules to install during the build process, so that your web app will have access to these modules when it is running.</p><p>Here is what my requirements.txt looks like. Remember to include gunicorn as one of the requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*Flea_kVbvycY48ommj_agQ.png" /></figure><p>The numbers at the end are just the versions of the modules you want Heroku to install. You do not have to create this file manually, instead you can use pipfreeze to generate a list of all the dependencies your app has automatically.</p><p>After adding these 2 files to your app folder and pushing it to your Github repo. Your app should be running nicely on the Heroku servers now. If you still encounter any issues, Heroku has a great error logging that you can use to investigate any errors. Just click on “view logs” on the top right hand corner of the Dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*qmbOoXFUAQektUw2mTf2tA.png" /></figure><p>Overall, my experience with Heroku has been infinitely friendlier and with greater success.</p><p>Hopefully this will help someone else who is a little lost like I was before embarking on this project. Hopefully i have saved you from a few hours of frustrated googling and hair pulling.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7616369b11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/setting-up-a-flask-app-on-heroku-vs-azure-ee7616369b11">Setting up a Flask app on Heroku vs Azure</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting the Top Words in a multi-class Text Classification problem]]></title>
            <link>https://medium.com/kenlok/getting-the-top-words-in-a-multi-class-text-classification-problem-ad39e5a57eb2?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad39e5a57eb2</guid>
            <category><![CDATA[multi-class]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-classification]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Tue, 19 Jun 2018 02:44:17 GMT</pubDate>
            <atom:updated>2018-06-19T03:18:13.402Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on a project that involved multi-class text classification problem. The idea was to train a model to predict the category (out of 16 possible categories) of a report based on a body of free text.</p><p>To prepare the data, i used the CountVectorizer and TfIdfVectorizer from scikit-learn.</p><p>CountVectorizer transforms the corpus into tokens (individual words) and gives you a corpus vocabulary that assigns every token a unique integer id. As most machine learning algorithms tend to work with numbers and not words, this phrases the corpus in a way that can be fed into these machine learning models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aece2b4889b340a12df2a08309947fc9/href">https://medium.com/media/aece2b4889b340a12df2a08309947fc9/href</a></iframe><pre>3378</pre><pre>{&#39;main&#39;: 1914,<br> &#39;breaker&#39;: 718,<br> &#39;put&#39;: 2351,<br> &#39;position&#39;: 2275,<br> &#39;loco&#39;: 1866,<br> &#39;ableunable&#39;: 392,<br>...<br>}<br></pre><p>The ‘3378’ is the total length of the corpus vocabulary. Meaning that there are 3378 unique words/strings present in the corpus.</p><p>In the example above; ‘main’ corresponds to id ‘1914’ in the vocabulary, ‘breaker’ corresponds to id ‘718’ and so on.</p><p>Next, to understand which are the tokens that score higher based on the Term Frequency — Inverse Document Frequency Score (TfIdf) of each class. We can transform the data into a sparse dataset/matrix by doing the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/825579c74a85dd01edd0f1174465a532/href">https://medium.com/media/825579c74a85dd01edd0f1174465a532/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*03DcyFPmxgMlQwsZh3X6EQ.png" /><figcaption>Sparse matrix of Tfidf scores</figcaption></figure><p>The output above shows the score of the 3378 tokens (columns) for each document (rows) in the corpus, as well as it’s associated class.</p><p>With this we can then sum the scores for each of the 3378 tokens by the 16 classes in our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*ffEBAxra9AuF6ThoiqpzSQ.png" /><figcaption>Sparse matrix grouped by Classes</figcaption></figure><p>Armed with this information, we can now start to understand the importance of each token in identifying a particular class. A higher TfIdf score could mean 1 of 2 things.</p><ol><li>The token has a high frequency of appearance in the document</li><li>The token is rare in the corpus</li></ol><p>In the example above, the highlighted value of 2.155245 for token id ‘3376’ can mean that the presence of this token in a particular document would mean a higher probability that the document is of class ‘COMS’</p><p>But what word is this token id ‘3376’?</p><p>With this function below, we can grab the top n words of each class and display them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/508b5a73a5369180f2df1424bc377b07/href">https://medium.com/media/508b5a73a5369180f2df1424bc377b07/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*F4aFVwzLMHyt2X484tEydA.png" /><figcaption>Top 6 words for class ‘ACON’ and its TdIdf Score summed</figcaption></figure><p>Wrapping this function in a loop will allow us to investigate the top n words of each class in our dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78b7ad6a003c8e90db8689a6e45f10f5/href">https://medium.com/media/78b7ad6a003c8e90db8689a6e45f10f5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*WQL-xHHTt9Apa2BPhn_Qng.png" /><figcaption>Top 5 words for each class</figcaption></figure><p>How i made use of this information was to further clean up the freetext. If there were any generic words/tokens that was in the top 10 spots of any class, i would go back and remove them from the original dataset, before training the model again.</p><p>Generic words such as ‘faulty’, ‘testing’ that i knew by intuition did not point to any class in particular. Doing this extra step of ‘feature engineering’ helped improve the prediction accuracy of some of the under performing classes.</p><p>Hope this was useful to some of you.</p><p>Thank you for reading and do share your thoughts with me!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad39e5a57eb2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/getting-the-top-words-in-a-multi-class-text-classification-problem-ad39e5a57eb2">Getting the Top Words in a multi-class Text Classification problem</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experimenting with Multi-Label Prediction]]></title>
            <link>https://medium.com/kenlok/experimenting-with-multi-label-prediction-16fa5c0638f8?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/16fa5c0638f8</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[multi-label]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Wed, 23 May 2018 03:43:19 GMT</pubDate>
            <atom:updated>2018-06-19T02:44:58.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*sr4anwCI-zPmGTpp.jpg" /></figure><p>So previously we forayed into the world of Multi-Label Classification. If you want to check that out, <a href="https://medium.com/kenlok/learning-about-multi-label-classifiers-811039f1154d">click here</a>.</p><p>Well, this time we are going to get down and dirty, because what better way to know what all these are than to actually try them our ourselves?</p><p>I was hunting around for a problem/dataset that would be our practice range. Turns out Kaggle had a competition recently that fits the bill exactly!</p><p><a href="https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge"><em>Toxic Comments Classification Challenge</em></a></p><h3>Getting Started — Data Exploration</h3><p>Well the premise was simple enough, take a comment (plucked from Wikipedia’s talk page edits) and determine the different levels of cancer (types of toxicity in proper terms) that the comment gives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*ItwAvkxc_cbux0xHyS2wrA.png" /></figure><p>This is what the data set looks like. (159571 rows , 8 columns)</p><p>First let’s try to understand what we have here a little better before diving in with the multi-label stuff.</p><h4>Label Count</h4><p>How many of the comments actually fall under each label</p><pre>toxic               15294<br>severe_toxic         1595<br>obscene              8449<br>threat                478<br>insult               7877<br>identity_hate        1405</pre><h4>Multi-Label Count</h4><p>How many comments have 2 or more labels associated?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*VrcGPcV4HxXyOPIvVuvOwQ.png" /></figure><p>As can be seen, a good chunk of the comments do not even have any labels associated with them.</p><p>(People are not as evil as you think!)</p><h3>Getting Started — For Real</h3><p>Since we are dealing with text processing, I have always read that you need to do some cleaning before training your model. Removing stopwords, extra whitespaces, lemmatize etc.</p><p>Well guess what, we are not going to do any of that! (you WHUT?)<br>My goal here was just to try out a few different classifier models and see which one worked better. If we feed them all the same baseline inputs, then it should still be a fair competition right?</p><h4>Naive Bayes</h4><p>This was the first one i tried.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f777094cd36192f13686ebee2b7e2961/href">https://medium.com/media/f777094cd36192f13686ebee2b7e2961/href</a></iframe><p>The Pipeline function provided by sklearn makes the necessary transformation to your data so that it can be fed into the Classifier.</p><p>OneVsRestClassifier is a wrapper so that our NaiveBayes can be used in Binary Relevance style to predict the multi-labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*I0bYoU1s3qvqTxhUZbMd8g.png" /><figcaption>Score for NaiveBayes</figcaption></figure><h4>LinearSVC</h4><p>The beauty of using Pipelearn and sklearn is that the code to run the different models are basically the same! Save for the Classifier that you put into the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*yZ1WUBcnf01KVk5zIvO-8A.png" /><figcaption>Score for LinearSVC</figcaption></figure><h4>Logistic Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*lWGWj3umft7tCP4fip_2rg.png" /><figcaption>Score for Logistic Regression</figcaption></figure><p>The run times for the above 3 models were extremely fast, nothing took more than a minute to run.</p><p>The following 2 however, are a different story</p><h4>GradientBoostingClassifier</h4><p>If you are like me and have no idea what Gradient Boosting is. Check out this <a href="http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/"><strong>Kaggle Master</strong></a><strong> </strong>explain it in (hopefully) simpler terms.</p><p>What i feel is the basic idea behind Gradient Boosting is (taken from Kaggle Master)</p><ol><li>Fit a model to the data. — F1(x) = y</li><li>Fit a model to the residuals. — h1(x)=y-F1(x)</li><li>Create a new model. — F2(x) = F1(x)+h1(x)</li></ol><p>So i guess it is a form of gradient descent? Where the model tries to learn/fit the residuals in order to make the weak learner a better model.</p><p>Creating a pipeline for the GradientBoostingClassifier</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c7f3bfebe86c541764f3c6e16fec33/href">https://medium.com/media/32c7f3bfebe86c541764f3c6e16fec33/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*_WKwo6IxH2UckgX8HpMg2Q.png" /><figcaption>Results for GBC</figcaption></figure><p>This part took 1Hour27Minutes to run. A very significant difference from the earlier models we tried. Worst part is, the results are not as good as the simpler models like LinearSVC.</p><h4>RandomForest</h4><p>Random Forest is a ensemble of classification trees, where the prediction is derived via a voting mechanism from an array of decision trees. The forest classifier is a black box though, i have no idea what the classification tree looks like behind the scence.</p><p>This took 39Minutes to run. Half of the runtime as compared to GBC, but still significantly longer as compared to the simpler models.</p><p>The good news is, the accuracy of the Random Forest seems to beat the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*4gxFNJMXmHWH7D-N0fE6mw.png" /><figcaption>Score for RandomForest</figcaption></figure><h3>Conclusion</h3><p>Just a simple experimentation this time round.</p><p>What i learnt</p><ol><li>Complex does not necessarily mean better. The GBC did not fare the best even though it took the longest to train and I have heard the term gradient boosting behind a hot method now (XGBoost)</li><li>Time vs Accuracy. In some cases, the efficiency of training and running the model may be a important factor to consider. What is the time allowance in your use case? Practicality vs Reliability</li></ol><p>Anyways, congratulation to RANDOM FOREST!</p><p>You are the winner! (for now… until i get the chance to try out something else that can beat your record)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16fa5c0638f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/experimenting-with-multi-label-prediction-16fa5c0638f8">Experimenting with Multi-Label Prediction</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning about Multi-Label Classifiers]]></title>
            <link>https://medium.com/kenlok/learning-about-multi-label-classifiers-811039f1154d?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/811039f1154d</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Tue, 22 May 2018 08:25:28 GMT</pubDate>
            <atom:updated>2018-05-22T08:25:27.322Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently started a project that involved the classifying of a body of freetext and labelling it with 1 of about 100+ possible labels.</p><p>Having not much experience with building and training such models myself, i turned to the great web for relevant readings and materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*pKBsye-ZicSsjBSD.jpg" /></figure><p>This is some of things i got from reading</p><blockquote><a href="https://scholarsarchive.byu.edu/cgi/viewcontent.cgi?article=7114&amp;context=etd"><em>‘A Common Misconception in Multi-Label Learning </em></a><em>‘</em></blockquote><blockquote><em>by Michael Benjamin Brodie (Brigham Young University)</em></blockquote><p>Below are some of the notes i captured.</p><h3>What is a Multi-Label Classifier?</h3><p>In normal classification problems, the result/output typically takes on a binary value (0 or 1, yes or no)</p><p>In a multi-label problem, the output may have multiple possible values.</p><p>For example, in satellite imagery (like the one below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*9Up5JblfSGONEUVYQCvwkQ.jpeg" /></figure><p>The image above may take on the labels of : Water, Buildings, Trees, Roads</p><p>If the model was trained to identify the elements that can be seen in the picture.</p><p>Each of the label i.e ‘Water’, would take on a binary value of 0 or 1 to determine if the image will carry the label of ‘Water’</p><h3>Some of the Multi-Label Classifiers available</h3><h4>1. Binary Relevance (BR)</h4><p>Independently train <em>n</em> models to predict <em>n</em> outputs, in which the results are then aggregated to give a final prediction.<br><strong>Pro</strong> — Easy to construct and run<br><strong>Con </strong>— Ignore dependencies that may exist amongst the labels</p><h4>2. Labelled Powerset (LP)</h4><p>Creates compound variables (essentially cartesian products, or every possible combination) of the labels<br><strong>Pro </strong>— Serves as a baseline for multi-label prediction models<br><strong>Con</strong> — Not practical for tasks with large number of labels as the number of compound variables; 2^n, scales exponentially as the number of labels (n) increases</p><h4>3. Chain Classifer (CC)</h4><p>Builds upon the Binary Relevance (BR) model, but CC gets the <a href="http://scikit-learn.org/stable/auto_examples/multioutput/plot_classifier_chain_yeast.html">prediction output of the preceding models in the chain as features</a><br><strong>Pro</strong> — Allows the chain to learn correlations amongst labels<br><strong>Con</strong> — Chains in each model are random, so correlations may still be missed</p><h4>4. Ensemble of Chain Classifiers (ECC)</h4><p>An ensemble of multiple randomly ordered Chain Classifiers and a voting mechanism<br><strong>Pro</strong> — More likely to capture inter-dependencies of labels, improving accuracy<br><strong>Con</strong> — Additional resources required for computation</p><h4>5. Bayesian Chain Classifiers (BCC)</h4><p>A 2 step process.<br>Step 1 a Bayesian Network is first used to learn the dependencies amongst the labels<br>Step 2 BCC then constructs an ordering based on the learned dependencies</p><p>To note: A limit is usually placed on the the network to simplify the model, hence preventing it from learning more complex interactions involving 2 or more labels<br><strong>Pro</strong> — Better balance of accuracy and computational resources<br><strong>Con</strong> — Inability to capture more complex interactions</p><h4>6. Super Class (SC)</h4><p>Group similar labels to learn the inter-dependencies with greater speed. A more efficient version of Labelled Powerset (LP)<br><strong>Pro</strong> — Reduces the possible dependency search space<br><strong>Con</strong> — Still has a chance to end up in a non-ideal local minima and give poor prediction results</p><h4>7. Classifier Trellis (CT)</h4><p>Labels are put into a predefined dependency structure, this structure can be gradually improved upon through training.<br><strong>Pro</strong> — Reduces the problem of having a large undefined dependency search space. Giving CT the ability to handle problems with thousands of labels.<br><strong>Con </strong>— CT uses a ‘pairwise matrix of mutual information to compute dependencies’, hence it also cannot learn complex interaction (&gt;2 labels)</p><h3>Metrics for Multi-Label Classifiers</h3><h4>1. Hamming Loss</h4><p>Measures the symmetric difference between the predicted and actual label sets.</p><p>In case you are like me and have no idea what symmetric difference means:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*kCvAG4yVll4oOc80.jpg" /></figure><p><a href="https://en.wikipedia.org/wiki/Symmetric_difference">The union without the intersection</a></p><p>Essentially, what both the actual and predicted labels set say differently.</p><h4>2. 0/1 Loss</h4><p>Measures the percentage of the predicted label set that is incorrect.</p><p>If the weighting of the loss function is equal for 0 and 1, it essentially is measuring the model’s prediction accuracy.</p><h4>3. F1 Score (macro-averaged)</h4><p>Measured by the average of all the F1 scores of all the labels.</p><p>The F1 score is defined as:</p><blockquote><em>2*(Recall*Precision) / (Recall+Precision)</em></blockquote><p>Recall : Ratio of correctly predicted positive observations to all the observation in the actual class</p><p>Precision : Ratio of correctly predicted positive observations to the total predicted positive observations</p><h4>4. F1 Score (micro-averaged)</h4><p>Micro F1 computes the F1 score globally for all labels instead of taking the average across al the classes (Macro F1)</p><p>That concludes this post</p><p>Till next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811039f1154d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/learning-about-multi-label-classifiers-811039f1154d">Learning about Multi-Label Classifiers</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baby steps into deep learning with Fast.ai]]></title>
            <link>https://medium.com/kenlok/baby-steps-into-deep-learning-with-fast-ai-734b5b0e5e3f?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/734b5b0e5e3f</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Tue, 22 May 2018 08:25:04 GMT</pubDate>
            <atom:updated>2018-05-22T08:39:32.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*EAxOdc-3a8nG96zZnH5RaQ.png" /></figure><p>Back from a short hiatus.</p><p>Recently i have been trying my hand at using what I’ve learnt from the <a href="http://fast.ai/">Fast.ai</a>course taught by Jeremy Howard — <a href="http://course.fast.ai/">http://course.fast.ai/</a></p><p>Basically <a href="http://fast.ai/">Fast.ai</a> provides a intuitive and user friendly library for beginners like me to start off with actually building, training and making use of deep learning towards solving a problem.</p><p>There are 7 courses in part 1 of the course, and the amazing thing is that by the 2nd or 3rd lecture, he already has you up and running and being able to apply a neural network to a problem of your choice.</p><p>Personally i feel that this has helped me alot in my journey. I prefer to learn on-the-job, which means while i am actually trying it out with my own 2 hands and working on a project/problem. The <a href="http://fast.ai/">Fast.ai</a> course gives a top down approach where Jeremy teaches the practical aspect of application first, before diving down into the details of hyperparameters and technicalities. This has helped me to learn much quicker and better as I can try out the code and see what it actually does instead of having to sit through countless hours of lectures and go through a super steep learning curve before actually being able to create and train my own neural network.</p><p>So please do check out the <a href="http://fast.ai/">Fast.ai</a> course if you are interested and a doer-learner like me.</p><p>Link is at the top of the post!</p><p>Let me share my 2 cents on what I have gained from the course thus far.</p><p>A neural network in a way tries to mimic the human brain. Where each layer is akin to a neuron and is part of the journey of information input through the brain (the neural network) to the output (or thoughts/decision).</p><p>Why a neural network is so incredible is because it can solve infinitely complex problems and can mimic/learn the idiosyncrasies of your problem set, without you actually knowing what those special traits/features are.</p><p>The most basic neural net will can consist of 2 layers, a linear layer and a non-linear layer. By tuning the values of these 2 layers (essentially matrices), one can mimic infinitely complex problems and use the network to find solutions. And by stacking more of these linear+non-linear layers alongside each other to create a deeper neural network, the network can better replicate/model the particular problem that you are working on.</p><p>Training the network, which basically mean tuning the weights in each of these matrices (layers are matrices), can be an intensive process and runs best with a GPU. There are many methods to ‘speed up’/optimize the training such as Adam (Adaptive moment estimation), Stochastic Gradient Descent, momentum etc. But in my view these are important to know but not critical in being able to train your network. You can still get the job done the ‘brute-force’ way if you must.</p><p>The network is trained by feeding the network with tagged examples. Much like showing a child an apple and telling him that this is an ‘apple’, except you have to these thousands, ten thousands of times. Everytime the network is fed a training example, it changes the weights in its matrices in order to output a result that is closer to the label of the example given. So the network learns incrementally, albeit in small steps that can be sped up and led in the right direction by the optimizers mentioned above.</p><p>Of course this is a very shallow and crude explanation of what a neural network actually is, and i am still at only the beginning of this journey to understand deep learning and neural networks.</p><p>Hopefully i will be like a neural network that will continue to learn incrementally and take steps towards a local minima of my own.</p><p>Till next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734b5b0e5e3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/baby-steps-into-deep-learning-with-fast-ai-734b5b0e5e3f">Baby steps into deep learning with Fast.ai</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS-GO competitive match data — Part 2]]></title>
            <link>https://medium.com/kenlok/cs-go-competitive-match-data-part-2-ff4a621bc794?source=rss----29fe98de7b5---4</link>
            <guid isPermaLink="false">https://medium.com/p/ff4a621bc794</guid>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[counter-strike]]></category>
            <dc:creator><![CDATA[ken lok]]></dc:creator>
            <pubDate>Tue, 22 May 2018 08:24:15 GMT</pubDate>
            <atom:updated>2018-05-22T08:24:15.111Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to part 2 of our road to Diamond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*COXaDtSNQDOdsPDQxmWOug.jpeg" /></figure><p>Earlier we looked at all things grenades. This time we will be taking a step back and taking a broader view of things.</p><p>The 2nd data table provides us with instances of all damage done with information on the weapon used, the hitbox, the team net value and much more. I won’t bore you anymore with the details and let’s get right to it.</p><p>Some questions that we may want answers to:</p><ol><li>Which gun does the most damage (total)</li><li>Which gun is the most widely used</li><li>Which hitbox is targeted the most</li><li>Which guns are used/bought in correlation to the team’s total value</li></ol><p>First off, we all want to know which gun to buy right? What guns do the pros favor, and which gives the most bang for the buck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*UxKc5xBOu-0FAPMZ.jpg" /></figure><p>Although the plot above is very tiny, it is evident that the AK47 tops the damage chart by a huge margin. Even the AWP in 2nd place is less than half the total damage of the AK47.</p><p>Next we want to find out if this huge disparity is caused by the a higher frequency of use of the AK47 or is the damage and accuracy of the AK47 just that amazing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*9euqmiiUU4-0q4oj.jpg" /></figure><p>As can be seen, the AK47 has a super high usage rate, about 3 times of its closest competitor M4A4. I guess we can safely say that the AK47 is almost everyone’s weapon of choice in the mirage map.</p><p>However, let’s take the AK47 out of the picture for a moment so that we can have a better understanding of where the other weapons stand as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*mXLKIB80Bl9lmQRI.jpg" /></figure><p>Even with the AK47 out of the picture, we still see a few hot favourites such as the all famous AWP, M4A4 and M4A1 taking the lead. Surprisingly, there are a few pistols that are in the top 10 spot as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*CNAzXGz2-Q1Y9LBS.jpg" /></figure><p>Let’s take a closer look</p><p>So there you have it, the top 2nd to 11th place in damage rankings, with AK47 as the reigning king.</p><h3>Accuracy</h3><p>Now let’s try to figure which gun is the most accurate (i.e giving the most head shots)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*K1qx9oaBoIaofNCx.jpg" /></figure><p>The graph above ranks the guns by the number of shots done to the head</p><p>Seems like most shots in the head are by pistol wielders, with some rifles up there in the top spots as well.</p><h3>Weapon Choice</h3><p>Now let’s try to figure out the types of guns people buy, in relation to their $ value. We will most likely see pistols and maybe SMG bought during ECO rounds. And AWPs and rifles being purchased when everyone is feeling rich and going all out. Let’s take a look Now let’s try to figure out the types of guns people buy, in relation to their $ value. We will most likely see pistols and maybe SMG bought during ECO rounds. And AWPs and rifles being purchased when everyone is feeling rich and going all out. Let’s take a look</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aJhbyaMDKASA8SRE.jpg" /></figure><p>So the x axis is how much money the whole team has, starting with 0 from the left. As can be seen, pistols are very popular up to the 5000 mark. Then they usually transit to SMGs at the 20,000 mark and then Snipers and Rifles at the 25,000 to 30,000 range.</p><p>Well that is all we have for this post.</p><p>Feel free to leave a comment or tell me what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4a621bc794" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenlok/cs-go-competitive-match-data-part-2-ff4a621bc794">CS-GO competitive match data — Part 2</a> was originally published in <a href="https://medium.com/kenlok">KenLok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>