<?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[NTUOSS - Medium]]></title>
        <description><![CDATA[Happy hacking with NTUOSS! - Medium]]></description>
        <link>https://medium.com/ntuoss?source=rss----bd776c72fe5---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>NTUOSS - Medium</title>
            <link>https://medium.com/ntuoss?source=rss----bd776c72fe5---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:55:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ntuoss" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TGIFHacks #108 — Front End with React]]></title>
            <link>https://medium.com/ntuoss/tgifhacks-108-front-end-with-react-d79b10d76c97?source=rss----bd776c72fe5---4</link>
            <guid isPermaLink="false">https://medium.com/p/d79b10d76c97</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Laksh]]></dc:creator>
            <pubDate>Fri, 14 Feb 2020 17:25:21 GMT</pubDate>
            <atom:updated>2020-02-14T17:25:21.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>TGIFHacks #108 — Front End with React</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*v0MUJbK02fMWG4-G" /><figcaption>Artwork by <em>Bryna Goh Jia Rui</em></figcaption></figure><h3>1. Introduction</h3><p>This workshop is mainly concerned with learning the basics of React but since HTML, CSS and JS are important prerequisites, we will first go through a brief overview of them. After that, we will learn about React and see how it can make web development a lot easier. Note that slides for this workshop can be found <a href="https://docs.google.com/presentation/d/1WQSVTRAipOvTB5sFmqQnnohsEboqqLhKcgkromM7ha8/edit">here</a>.</p><h3>2. A Web Dev Analogy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*pNREGiTjwWD4EFKC" /></figure><p>You can think of web development like building a house.</p><h3>2.1 HTML</h3><p>HTML can be though of as the bricks. It is used to present content in a structured manner to the viewer, much like how bricks are used to provide structure to a house.</p><p>HTML is made up of special tags which contain information on how to represent the content inside them. We can see this with the following example</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;grey-background-section&quot;&gt;<br>      &lt;h1&gt;This is a heading&lt;/h1&gt;<br>      &lt;p&gt;This is a paragraph&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You can ignore all the boilerplate code for now. The above code snippet shows a div element. A div is any unique section on the web page. Inside is h1 tag which represents a heading, and p represents a paragraph . If you save the above code in a file called index.html, the result will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*TvtmH7i2NbTLIK3Q" /></figure><p>There are numerous other tags such as a for links, img for images, and button for buttons.</p><h3>2.2 CSS</h3><p>A house is not very fun to live in if it’s just bricks and doors. To make it livable, we must paint it. Similarly, we use CSS to add decorations to make our website look more appealing.</p><p>Let’s make our previous HTML look better. Make a folder called css and inside it make a file called index.css.</p><pre>body {<br>  font-family: Arial, Helvetica, sans-serif;<br>  background-color: #f4f4f4;<br>}</pre><pre>.grey-background-section {<br>  background-color: #454545;<br>  border-radius: 18px;<br>  padding: 10px;<br>}</pre><pre>h1,<br>p {<br>  color: #aaaaaa;<br>}</pre><p>We can use the name of the tag we want to change the appearance for and then specify the appearances we want changed. We can also use the class names which we had defined earlier in the HTML to change the view of that specific class.</p><p>We must link to this CSS somewhere in our HTML. To do this, we add the following lines of code between the &lt;head&gt;&lt;/head&gt; tags of our html:</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;css/index.css&quot; /&gt;</pre><p>After all this, your web-page should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OrX9F6njRLPTTeVy" /></figure><h3>2.3. Javascript</h3><p>Although it’s nice to have a roof over our heads, a house would suck to live in if there was no plumbing and no electricity. Similarly, a website isn’t very fun if all you can do with it is stare at it. JavaScript let’s us add some functionality to the website.</p><p>Let’s make the heading change when we click on the div. We wil create a folder called js and in that, make a file called index.js. Add the following code into it:</p><pre>const section = document.querySelector(&#39;.grey-background-section&#39;);</pre><pre>const heading = document.querySelector(&#39;#heading&#39;);</pre><pre>section.addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(&#39;CLICKED&#39;);<br>  heading.textContent = &#39;Clicked&#39;;<br>});</pre><p>We first store the heading and div as variables and then say that whenever the div is clicked, the heading should change. We can include this file into our HTML after the body tag by adding the following code:</p><pre>&lt;script src=&quot;js/index.js&quot;&gt;&lt;/script&gt;</pre><p>Now, whenever you click the div, this should be the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q5SjfIyXJfdJ9SL8" /></figure><p>Congratulations, you just did DOM manipulation!</p><p>That is the end to our analogy and our brief overview of the basics of web development. Do note that this didn’t even cover 1% of front-end development. Do learn more about each of these after the workshop. That being said, let’s talk about JS frameworks.</p><h3>3. What are frameworks ????</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*J_QpNl0UbdAbJN3Y" /></figure><p>The purpose of JavaScript frameworks is simple:</p><blockquote><em>Mapping application state to the DOM</em></blockquote><p>What might not be clear from the previous section is that manipulating the DOM is very error prone, messy, and very hard to scale as the project gets bigger.</p><p>Frameworks such as React, Angular, or Vue help developers by making mistakes that could happen by direct DOM manipulation virtually impossible. If you want to understand this a bit more, here’s some <a href="https://medium.com/@mattburgess/javascript-frameworks-why-to-use-them-at-all-8cce2804c092">further reading</a>.</p><p>Helpful side-effects of these frameworks is that they help reduce code, provide reusable elements, keep code structured and provide a vast array of helpful plug-ins and libraries made by other fans of the framework.</p><p>Simply put, using a framework will make it easier for you to make a website than simple JS DOM manipulation.</p><h3>4. What’s React?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*G9dbhkDendWVqlOE.png" /></figure><p>React is a JavaScript library developed by Facebook and is meant for making user interfaces. It’s also the most popular framework right now. These are some of the great things about it:</p><ul><li>Really easy to learn</li><li>Makes front-end development a lot easier</li><li>Reusable components (objects) which manage their own state</li><li>Virtual DOM increases leading speed</li><li>You can write HTML inside JavaScript</li></ul><p>Now let’s go over the basics of React.</p><h3>5. Getting Started</h3><p>We will be doing most of this workshop on <a href="https://www.codesandbox.io/">codesandbox.io</a>. This site will allow us to test out React and see how it runs and works without having to download anything onto our computer for now. Near the end of the workshop, we will go over how to set up React on your own laptop.</p><p>Let’s go to <a href="https://www.codesandbox.io/">codesandbox.io</a> and sign in using GitHub. Once you do, you will be greeted by this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mt-fpKgc3vDLLDYK" /></figure><p>Go ahead and click on Create Sandbox. You will now see a vast array of Sandboxes which you can create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ovk2ySDVNyNwTcWj" /></figure><p>As you can see, React is first since it’s the most popular. Click on it to create a React sandbox. If all went correctly, you should be greeted by this terrifying screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l--fBal0Jjp5eB19" /></figure><p>Don’t worry, we will go through everything from scratch. Let’s close the Dependencies tab to avoid any confusion. Now let&#39;s talk about the file structure.</p><h3>6. The Files</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*hfTAbkD18bPiXO-X" /></figure><p>As you can see, 4 different files were generated, let’s see what each one of them do:</p><ol><li>package.json: This file contains all the information about the app we are making such as the version numbers, names of dependencies and libraries which we are using, as well as custom commands which we can use.</li><li>index.html: React is essentially a single page application framework. This means that no matter what we make, it will be shown to the browser via this file. That being said, we rarely touch this file. Just know that whatever we make will be rendered between the &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; tags</li><li>index.js: If we don’t touch the index.html file, how do we make stuff? This is where JSX comes in. JSX combines HTML and JS into a single file. This is then parsed and sent to the index.html to be rendered.</li><li>styles.css: This is a file which contains style rules for our entire website.</li></ol><p>Most of what you will be doing as a React developer is making many files like index.js and connecting them together while adding CSS to make your site look good. Let’s do some coding now!</p><h3>7. Rendering our first component</h3><p>Let’s delete everything from index.js and write everything from scratch. We will now be greeted by a blank screen.</p><p>To use react, we first need to import it. We do this by writing:</p><p>import React from &quot;react&quot;;</p><p>This library just deals with the logic behind react but has no information about how to render anything onto the browser. To do this we must import ReactDOM:</p><p>import ReactDOM from &quot;react-dom&quot;;</p><p>We will create our first component now. React components can either be made using classes or functions. We will begin by making a class based component. We create a class named App which will inherit properties from React.Component:</p><p>class App extends React.Component {}</p><p>Inside this, we need to initialise the render() function which will control the elements inside the component. This is where we basically put all of our HTML. The class should now look like this:</p><pre>class App extends React.Component {<br>  render() {}<br>}</pre><p>Inside the render function, we need to return the HTML which we want to render:</p><pre>class App extends React.Component {<br>  render() {<br>    &lt;div className=&quot;App&quot;&gt;<br>        &lt;h1&gt;Hello CodeSandbox&lt;/h1&gt;<br>        &lt;h2&gt;Start editing to see some magic happen!&lt;/h2&gt;<br>    &lt;/div&gt;<br>  }<br>}</pre><p>Now that our component is created, we need to render this. To do this, we first need to specify where we want to render it. Outside the class, we add the following line to find the root of the web page:</p><p>const rootElement = document.getElementById(&quot;root&quot;);</p><p>After this, we use ReactDOM to render our component inside the root:</p><p>ReactDOM.render(&lt;App /&gt;, rootElement);</p><p>We can also import the CSS at the top of the file and now our code should look like this:</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;h1&gt;Hello CodeSandbox&lt;/h1&gt;<br>        &lt;h2&gt;Start editing to see some magic happen!&lt;/h2&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const rootElement = document.getElementById(&quot;root&quot;);<br>ReactDOM.render(&lt;App /&gt;, rootElement);</pre><p>And you should see the following being rendered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m0xBC3iajN6vN_xs" /></figure><p>Congratulations! You just rendered your first React component. Let’s start building the final product now and learn more about components.</p><h3>8. Components</h3><p>Before we start, let’s add some boilerplate CSS which will be needed throughout our website to styles.css:</p><pre>body {<br>  background: #cccccc;<br>  color: #333333;<br>  font-family: &quot;Open Sans&quot;, &quot;Lucida Grande&quot;, &quot;Lucida Sans Unicode&quot;, Arial,<br>    Helvetica, Verdana, sans-serif;<br>  font-size: 16px;<br>  line-height: 1.6em;<br>  margin: 0;<br>}</pre><pre>.container {<br>  width: 70%;<br>  margin: auto;<br>  overflow: hidden;<br>  background: #eeeeee;<br>  height: 98vh;<br>  display: flex;<br>  flex-direction: column;<br>}</pre><pre>.content {<br>  display: flex;<br>  flex-direction: row;<br>}</pre><p>We will now remove everything inside the outermost div of our App component, and change the div to be: &lt;div className=&quot;container&quot;&gt;. All you should be able to see now is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ggkgrstLrFHt7SxY" /></figure><p>The great thing about React is that it allows us to make our own custom components and use them as HTML elements. Let’s see how this works by making the navbar for our chatting app.</p><p>In src, make a folder called components. Inside that, make a folder called Navbar which should now contain file called Navbar.js and a file called styles.css. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*_ujrod2cJCmsxX6G" /></figure><p>So, for every new component we want to create, we create a folder with the name of the component, which contains a JavaScript file and the CSS file for that component.</p><p>Let’s add the following code to Navbar.js:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class Navbar extends React.Component {<br>  render() {<br>    return (<br>      &lt;header className=&quot;navbar&quot;&gt;<br>        &lt;div className=&quot;app-name&quot;&gt;Telegram&lt;/div&gt;<br>        &lt;div className=&quot;chat-name&quot;&gt;<br>          &lt;strong&gt;Chat Name&lt;/strong&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br>    );<br>  }<br>}</pre><pre>export default Navbar;</pre><p>Notice how we don’t need to use ReactDOM. This is because we won’t be rendering this component through this javascript file. The file that imports this component will deal with that. Now let’s make the navbar look better by adding the following to styles.css:</p><pre>.navbar {<br>  background-color: #5682a3;<br>  color: #ffffff;<br>  display: flex;<br>  justify-content: start;<br>  align-items: center;<br>  padding-left: 1em;<br>  height: 2em;<br>}</pre><pre>.app-name {<br>  display: flex;<br>  width: 30%;<br>}</pre><pre>.chat-name {<br>  display: flex;<br>  width: 70%;<br>}</pre><p>Right now we can’t see our component because we haven’t rendered it anywhere. Let’s import this component into index.js and use it there. Add this line to the top of index.js:</p><p>import Navbar from &quot;./components/Navbar/Navbar&quot;;</p><p>We have imported the component, but how do we use it? Well, React components are similar to self-closing HTML tags. Change the return statement to return the following:</p><pre>return (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;Navbar /&gt;<br>      &lt;/div&gt;<br>    );</pre><p>Now you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UWTJiHXwMzdyIkjz" /></figure><p>Now you know how to make your own components and use them within other components! The usefulness will become apparent to you as we begin making the telegram messages. Now let’s make some components which we can interact with.</p><h3>9. Props</h3><p>Now that we have our navbar, let’s show a list of our chats on the left side of the page. To do this, we will create a ChatList component. Let&#39;s do the same thing we did before which is making a folder with the name of the component and adding in the respective files.</p><p>The ChatList.js file will have the following content:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class ChatList extends React.Component {<br>  render() {<br>    return &lt;div className=&quot;chat-list&quot;&gt;&lt;/div&gt;;<br>  }<br>}</pre><pre>export default ChatList;</pre><p>And add the following to the styles.css:</p><pre>.chat-list {<br>  width: 34%;<br>  background-color: #dcdcdc;<br>  height: 98vh;<br>  border-right: 2px #cdcdcd solid;<br>}</pre><p>Now add &lt;div className=&quot;content&quot;&gt;&lt;/div&gt; after the navbar inside App.js and add &lt;ChatList /&gt; inside this div.</p><p>You should be able to see the grey bar to the left of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JGCxZyj1ZYW7QIQ" /></figure><p>It looks depressingly empty. Let’s try adding some content inside this list! Although we could copy paste the code for the chat tabs multiple times, we can make use of components and save ourselves a lot of time. Let’s make another folder for ChatTab and make the ChatTab.js and styles.css folders. Paste this code into ChatTab.js:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class ChatTab extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;chat-tab&quot;&gt;<br>        &lt;img<br>          src=&quot;https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png&quot;<br>          alt=&quot;Avatar&quot;<br>        /&gt;<br>        &lt;div className=&quot;chat-tab-details&quot;&gt;<br>          &lt;h4&gt;Chat Name&lt;/h4&gt;<br>          &lt;p&gt;Latest Message&lt;/p&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default ChatTab;</pre><p>And add the following to the styles.css:</p><pre>.chat-tab {<br>  height: 2em;<br>  margin: auto;<br>  padding: 0.5em;<br>  display: flex;<br>  line-height: 1em;<br>}</pre><pre>.chat-tab h4,<br>p {<br>  padding: 0;<br>  margin: 0;<br>}</pre><pre>.chat-tab img {<br>  width: 2em;<br>  border-radius: 20px;<br>  margin-right: 10px;<br>}</pre><pre>.chat-tab-details {<br>  display: flex;<br>  width: 80%;<br>  justify-content: center;<br>  align-items: start;<br>  flex-direction: column;<br>  font-size: 12px;<br>}</pre><p>Now to make this component visible, we can insert it between the div inside ChatList.js. You should now have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sZsJ3-4Y8BPtO7hk" /></figure><p>Great! We have a single chat in our list. In the future we will have multiple such tabs, and each tab will have a different chat name and latest message. We can’t make a new component for each new chat tab. So what do we do? This is where props come in.</p><p>You may have noticed that some HTML tags have attributes such as &lt;img src=&quot;&quot; /&gt; and &lt;a href=&quot;&quot;&gt;&lt;/a&gt;. Similarly, our components can take in attributes as props.</p><p>We will change &lt;ChatTab /&gt; to &lt;ChatTab name=&quot;TGIFHacks Chat&quot; latestMessage=&quot;Eyyyyyyyyyy&quot; /&gt;</p><p>Now, name and latestMessage have been passed in as variables to the ChatTab component. Inside ChatTab.js, we change Chat Name to {this.props.name} and Latest Message to {this.props.latestMessage}.</p><p>Now you will be able to see that our chat tab is customized!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A70f58GtA96Jq5Xk.PNG" /></figure><p>You can now easily make multiple instances of &lt;ChatTab /&gt;, one below the other and have an entire list of chats:</p><pre>&lt;div className=&quot;chat-list&quot;&gt;<br>  &lt;ChatTab name=&quot;TGIFHacks Chat&quot; latestMessage=&quot;Dis workshop is lit&quot; /&gt;<br>  &lt;ChatTab name=&quot;CE2007 Group&quot; latestMessage=&quot;I&#39;m dying&quot; /&gt;<br>  &lt;ChatTab name=&quot;MDP Chat&quot; latestMessage=&quot;End my suffering&quot; /&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a-sKFWvn5-qRdB7h" /></figure><p>If we want to avoid copy pasting code, we can make an array of objects outside the return statement and iterate through it:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;<br>import ChatTab from &quot;../ChatTab/ChatTab&quot;;</pre><pre>class ChatList extends React.Component {<br>  render() {</pre><pre>    const chats = [<br>      {<br>        name: &quot;TGIFHacks Chat&quot;,<br>        latestMessage: &quot;Dis workshop is lit&quot;<br>      },<br>      {<br>        name: &quot;CE2007 Group&quot;,<br>        latestMessage: &quot;I&#39;m dying&quot;<br>      },<br>      {<br>        name: &quot;MDP Chat&quot;,<br>        latestMessage: &quot;End my suffering&quot;<br>      },<br>    ]</pre><pre>    return (<br>      &lt;div className=&quot;chat-list&quot;&gt;<br>        {<br>          chats.map(chat =&gt; {<br>            return &lt;ChatTab name={chat.name} latestMessage={chat.latestMessage} /&gt;<br>          })<br>        }<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default ChatList;</pre><p>We can now look at our different chats! But how do we select a chat and open it? And how do we change the chat name in the navbar? Let’s learn more about states in react and solve these problems.</p><h3>10. State</h3><p>Every react component has attributes of its own (state) as well as attributes that were passed down to it from its parent (props). Using the component’s state, you can control the member variables of the component.</p><p>When we select a certain chat to open up, we are changing the state of the entire App since multiple children of this component will need to know about the chat which we are looking at.</p><p>To use the state of a component, we first need to initialise it. We do this by using a constructor. Add the following lines before the render(){} function:</p><pre>constructor(props) {<br>    super(props);<br>    this.state = {<br>      chatName: &quot;&quot;<br>    };<br>  }</pre><p>Notice how we take in the props. This is because the props are passed down to the component using the constructor. This is done by default if we don&#39;t make our own constructor like in the previous section, but if we do make our own constructor, we have to take in the props. super(props) is used to call the constructor of the parent component.</p><p>Since the App will have the chat name as a state, and the navbar needs to display it, we need to pass it down as a prop to the navbar. We do it by changing &lt;Navbar /&gt; to</p><pre>&lt;Navbar chatName={this.state.chatName}/&gt;</pre><p>As you can see, we access the state using this.state.variable. We now go into Navbar.js and change &lt;strong&gt;Chat Name&lt;/strong&gt; to:</p><pre>&lt;strong&gt;{this.props.chatName}&lt;/strong&gt;</pre><p>Now, whenever we click on a chat on the sidebar, we want the chat name of App to change. How do we do this? We will need a function in ChatTab which will change the state of App. Since only a function inside App can change the state of App, we can create a function here and pass it down to ChatTab as a prop! Define the following function in App.js after the constructor:</p><pre>handleChatClick = newChatName =&gt; {<br>    this.setState({<br>      chatName: newChatName<br>    });<br>  };</pre><p>Javascript arrow functions can seem confusion at first but let’s break it down. handleClick is the name of the function. It takes in a parameter called newChatName. Inside the curly braces, which is the function body, we use this.setState({}) to change the chatName to the new value. Why don&#39;t we just do this.state.chatName = newChatName? Because react will re-render the web-page only when we use setState.</p><p>Now let’s pass in this function to ChatTab by first changing &lt;ChatList /&gt; to :</p><pre>&lt;ChatList onChatSelect={this.handleChatClick} /&gt;</pre><p>Here, we pass in the function as props to the ChatList component. The name of the prop will be onTabClick.</p><p>Inside ChatList.js, change &lt;ChatTab name={chat.name} latestMessage={chat.latestMessage} /&gt; to:</p><pre>&lt;ChatTab<br>  name={chat.name}<br>  latestMessage={chat.latestMessage}<br>  onClick={this.props.onChatSelect}<br>/&gt;</pre><p>Finally, we go into ChatTab.js and to the outermost div we add:</p><pre>onClick={() =&gt; this.props.onClick(this.props.name)}</pre><p>This basically means that whenever the div is clicked, it&#39;ll take in no parameters. but call the onClick function we passed to it as a prop and pass into it the name of the current chat tab.</p><p>If you following all the steps, if you refresh your web page, your navbar should start with no chat name and whenever you click on one of the cta tabs, the name in the navbar should change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fN9G2DjIZgSWZbLO" /></figure><p>And that’s the basics of react! Let’s revise everything we have done once again by implementing the chatting feature.</p><h3>11. Putting it all together</h3><p>Let’s implement the chatting feature. Let’s first make a ChatColumn component which will be on the right hand side of the screen and contain the messages as well as the text box. Add the following to ChatColumn.js:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;<br>import TextBox from &quot;../TextBox/TextBox&quot;;</pre><pre>class ChatColumn extends React.Component {</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;chat-area&quot;&gt;&lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default ChatColumn;</pre><p>The CSS is as follows:</p><pre>.chat-area {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  width: 66%;<br>  background-color: #dcdcdc;<br>  height: 98vh;<br>}</pre><p>Now, this column will contain the text area where the user will write the message. This list of messages will also be visible inside this component. Since both the children of this component will need access to what the user is currently typing, message will need to be a prt of the state of this component and will need to be passed down to the TextBox and the ChatStream.</p><p>So let’s make message a part of the component&#39;s state by adding the following outside the render function:</p><pre>constructor(props) {<br>  super(props);<br>  this.state = {<br>    message: &quot;&quot;<br>  };<br>}</pre><p>We also need to create a function which will change the state whenever the user types something:</p><pre>handleChange = event =&gt; {<br>  this.setState({ [event.target.name]: event.target.value });<br>};</pre><p>This function is called when an event occurs. The event is passed into the function. The event has information about the target object that initiated the event. The target has a name and a value. We will name the target ourselves later on, and the value will be what the user has typed. This function will be passed down as a prop to our next component which is the TextBox:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class TextBox extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;text-box&quot;&gt;<br>        &lt;textarea<br>          value={this.props.message}<br>          onChange={this.props.onChange}<br>          placeholder=&quot;Write a message...&quot;<br>          rows=&quot;3&quot;<br>          name=&quot;message&quot;<br>        /&gt;<br>        &lt;button type=&quot;button&quot;&gt;SEND&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default TextBox;</pre><p>Notice how the value of the textarea is being passed down to it as a prop. This basically means that what is shown in the text area will be the state of the message value in ChatColumn (This is the event.target.value). Also notice that whenever the text inside the textarea is changed, it&#39;s onChange function is called which uses the onChange function passed to this component as a prop. Also notice that the name of the textarea is <em>message</em> (This is event.target.name). To style this, add the following CSS code:</p><pre>.text-box {<br>  width: 85%;<br>  margin: auto;<br>  display: flex;<br>  direction: row;<br>  align-items: center;<br>  justify-content: space-between;<br>  height: 20%;<br>}</pre><pre>.text-box button {<br>  all: unset;<br>  color: #5682a3;<br>  font-weight: bold;<br>}</pre><pre>textarea {<br>  border-top: none;<br>  border-right: none;<br>  border-left: none;<br>  overflow: auto;<br>  outline: none;</pre><pre>  -webkit-box-shadow: none;<br>  -moz-box-shadow: none;<br>  box-shadow: none;</pre><pre>  resize: none;</pre><pre>  background-color: transparent;<br>  border-bottom: #5682a3 solid 2px;<br>  width: inherit;<br>}</pre><p>Now we will add the TextBox component inside the div in ChatColumn as follows:</p><pre>&lt;TextBox message={this.state.message} onChange={this.handleChange} /&gt;</pre><p>You should now have a working text area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/0*OhxIBrOJiAbmY5MH" /></figure><h3>12. Connecting to the back-end</h3><p>Now let’s add the section where all the messages will be displayed. Make a component called ChatStream and add the following to ChatStream.js:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class ChatStream extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;chat-stream&quot;&gt;<br>        &lt;div className=&quot;chat-stream-content&quot;&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default ChatStream;</pre><p>Add the following to ChatColumn.js:</p><pre>constructor(props) {<br>  super(props);<br>  this.state = {<br>    message: &quot;&quot;,<br>    messages: []<br>  };<br>}</pre><pre>componentDidMount() {<br>}</pre><p>The state of this component contains messages which will be an array of messages in the displayed chat. But wait, what the hell is componentDidMount()??? This is something known as a lifecycle method.</p><p>Lifecycle methods are predefined methods made by react. Each component is born, lives, and dies 😟. This is known as the component lifecycle. Here is a list of all the functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a5S-HvJZ1GLpumeZ" /></figure><p>There are functions which run on mounting such as the constructor. Some run whenever a component is updated such as getDerivedStateFromProps, and some run when the component is removed from the webpage such as componentWillUnmount.</p><p>What we care about is componentDidMount. This is a function which is called the first time a component is added to the DOM. Inside this function, we wil be calling our back-end to retrieve our messages.</p><p>Now since we don’t have a backend yet, we will be using a free service called <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a>. This site will allow us to retrieve data as if it is in our back-end.</p><p>Now let’s get started with fetching some data. To do this, we will use the fetch API. Add the following inside componentDidMount:</p><pre>fetch(&quot;https://jsonplaceholder.typicode.com/comments&quot;)<br>      .then(res =&gt; res.json())<br>      .then(<br>        result =&gt; {<br>          console.log(result.slice(0, 10));<br>          this.setState({<br>            messages: result.slice(0, 10)<br>          });<br>        },<br>        error =&gt; {<br>          console.log(error);<br>        }<br>      );</pre><ol><li>We first specify the url from where we want to fetch the data.</li><li>We wait for the data to be fetched using the then keyword.</li><li>After waiting, we get a result which we store inside res.</li><li>We convert the result we got back into JSON format using res.json().</li><li>We again wait for this function to run using .then().</li><li>After we get the JSON data, we take in the result and any error.</li><li>If there is a result, we print it out using console.log() and set the message state to the results we got back (We only take the first 10 elements of the result array using splice).</li><li>If there is an error, we print it out using console.log().</li></ol><p>Finally, add &lt;ChatStream messages={this.state.messages}/&gt; above &lt;TextBox&gt; in ChatColumn.js.</p><p>If you now refresh your page and open up the Console at the bottom, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z9iilFtKSY5Jto05" /></figure><p>Congratulations! You just got data from a server for the first time. Now let’s convert this array of messages into messages on the web page.</p><p>Firstly, add the following to the CSS for ChatStream:</p><pre>.chat-stream {<br>  width: 85%;<br>  margin: auto;<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: start;<br>  height: 75%;<br>}</pre><pre>.chat-stream-content {<br>  flex-grow: 1;<br>  overflow: auto;<br>  min-height: 0;<br>}</pre><pre>::-webkit-scrollbar {<br>  width: 10px;<br>}</pre><pre>::-webkit-scrollbar-track {<br>  background: #f1f1f1;<br>}</pre><pre>::-webkit-scrollbar-thumb {<br>  background: #888;<br>}</pre><pre>::-webkit-scrollbar-thumb:hover {<br>  background: #555;<br>}</pre><p>Now we need to make a component which will display each message.</p><p>Make a component called Message:</p><pre>import React from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>class Message extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;message&quot;&gt;<br>        &lt;img<br>          src=&quot;https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png&quot;<br>          alt=&quot;Avatar&quot;<br>        /&gt;<br>        &lt;div className=&quot;message-content&quot;&gt;<br>          &lt;h4&gt;{this.props.user}&lt;/h4&gt;<br>          &lt;p&gt;{this.props.message}&lt;/p&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Message;</pre><p>styles.css:</p><pre>.message {<br>  height: 2em;<br>  padding: 0.5em;<br>  display: flex;<br>  line-height: 1em;<br>}</pre><pre>.message h4,<br>p {<br>  padding: 0;<br>  margin: 0;<br>}</pre><pre>.message img {<br>  width: 2em;<br>  border-radius: 20px;<br>  margin-right: 10px;<br>}</pre><pre>.message-content {<br>  display: flex;<br>  width: 80%;<br>  justify-content: center;<br>  align-items: start;<br>  flex-direction: column;<br>  font-size: 12px;<br>}</pre><p>Notice that we are taking in the username and message as props. Now let’s display these messages inside ChatStream. Add the following code between the div in ChatStream.js:</p><pre>{this.props.messages.map(message =&gt; (<br>          &lt;Message<br>            message={message.body.slice(0, 45)}<br>            user={message.name.slice(0, 7)}<br>          /&gt;<br>        ))}</pre><p>This might seem complicated but what we are essentially doing is mapping through each message in our this.state.messages. For each message object, we are rendering a Message component which uses the body and name property of the message (We use slice since the values returned from the API were way too long).</p><p>If everything went correctly, you should be able to see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p5St-66S6mXq8627" /></figure><p>Now let’s finish things up by letting you add your own message. Since the ChatColumn component contains both the message composer and the list of messages, we should define the function for adding a message here. Add the following before the render function:</p><pre>handleSendMessage = () =&gt; {<br>  var newMessage = {<br>    body: this.state.message,<br>    name: &quot;Username&quot;<br>  };<br>  this.setState(prevState =&gt; ({<br>    messages: [...prevState.messages, newMessage],<br>    message: &quot;&quot;<br>  }));<br>};</pre><p>This function makes a new message object using our current state. It then adds it to the current list of messages and then updates the state. We also set message to be empty so that the text area also becomes empty. Let&#39;s pass it down to TextBox by adding onSubmit={this.handleSendMessage}. We can now integrate it into the TextBox by adding onClick={this.props.onSubmit} to the button.</p><p>Now you can type a message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uzujbO9kyXPQadVV" /></figure><p>And after clicking on SEND, it’ll show up in the list of messages!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZrQvvF9EVf1Vh0yo" /></figure><p>Ofcourse, if you refresh, your new message will disappear because we aren’t sending the new message to a back-end. Be sure to tune in to our workshop next week to figure out how! So these are the basics of React. Let’s see what all we have learnt.</p><h3>13. Summary</h3><p>We have learnt the following things about React:</p><ol><li>Why you should use React</li><li>Components</li><li>Props</li><li>State</li><li>React lifecycle methods</li></ol><p>We have barely scratched the surface of React. You can find more useful resources and next steps in the slides which are referred to at the top.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79b10d76c97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntuoss/tgifhacks-108-front-end-with-react-d79b10d76c97">TGIFHacks #108 — Front End with React</a> was originally published in <a href="https://medium.com/ntuoss">NTUOSS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TGIFHacks #102 — Rapid Prototyping]]></title>
            <link>https://medium.com/ntuoss/tgifhacks-102-rapid-prototyping-dabf9af73fb3?source=rss----bd776c72fe5---4</link>
            <guid isPermaLink="false">https://medium.com/p/dabf9af73fb3</guid>
            <category><![CDATA[design-sprint]]></category>
            <category><![CDATA[ntuoss]]></category>
            <category><![CDATA[rapid-prototyping]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[tgifhacks]]></category>
            <dc:creator><![CDATA[Kunal Mishra]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 08:09:10 GMT</pubDate>
            <atom:updated>2019-10-20T08:09:10.144Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/ntuoss/getting-in-data-science-with-pandas-ed4a282d7710?source=collection_home---4------1-----------------------">T</a>GIFHacks #102 — Rapid Prototyping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VfMHaSIjF78NaLVuwgBGw.png" /><figcaption>Artwork by Brendan Hyde</figcaption></figure><h3>Event Details</h3><p><em>Venue: Lecture Theatre 1, North Spine, NTU</em></p><p><em>Time: 6:30pm — 8:30pm</em></p><p><em>Speaker: Kunal Mishra | </em><a href="/service/mailto: kunmishra2599@gmail.com"><em>Email </em></a><em>| </em><a href="http://www.github.com/kunmishra2599"><em>Github </em></a><em>| </em><a href="https://www.linkedin.com/in/kunal-mishra/"><em>LinkedIn</em></a></p><h3>Part 1: Design Sprinting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*Mz9zU6utfBevsOGraH1xYg.png" /></figure><h4>What is a design sprint, and why is it important?</h4><p>For those of you who aren’t aware, a design sprint is designed to be a process (spanning multiple days) that helps the participants arrive at a workable and feasible idea for a hackathon or a competition, using prototypingt tools and ideation. While there are many different sprints available, I personally like <a href="https://designsprintkit.withgoogle.com/assets/tools/Product%20Sprint%20Deck%20-%203-Day%20Template.pdf">Google’s 3 day sprint </a>which covers the same stuff in a shorter time-frame.</p><p>Since I’ve designed this worshop to help prepare you for a hackathon, I’ve compressed that sprint into a 2 hour workshop that’s going to covers three of the five steps in their sprint: Understanding, diverging and deciding. The workshop will cover the rest: Prototyping and or validating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITVKvvVBf7FDacTv7pNYIQ.png" /><figcaption>The General Design sprint process</figcaption></figure><p>Having spent hours at a hackathon brainstorming ideas, I feel design sprints are useful in saving you those critical first few hours as you arrive at your idea. It’s always worth spending an hour or two critically thinking about this stuff so you can spend the remainder working on winning the hackathon.</p><h4>Part 1.1: Generating problems (10–15 mins)</h4><p>Divide yourselves into groups of up to 4. This first part deals with what are called: How-Might-We’s. It involves the use of sticky notes on which you jot down your ideas. How: assumes opportunities exist, Might: says we don’t have to find something and We: is all about doing this together. If you’re there for the workshop, I’d have passed you a stack of sticky notes and some markers to write stuff down with.</p><p>These are essentially problem spaces that need solving. The key with this is to think of a problem that’s not too broad (Eg. fighting the patriarchy) or too narrow (more parking spaces in NTU South Spine).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*EySTRRtbo8jgYni5vK2aTw.png" /><figcaption>Something too broad and too narrow.</figcaption></figure><p>At iNTUition, you are free to do whatever you want unlike most other hackathons. Think of ideas and themes that are close to you Grab a post-it, write down one idea per note, use a sharpie to do so. Come up with 5 per person in your group(you should have 20). Remember to work individually!</p><h4>Part 1.2.1: Classifying problems / Affinity Mapping (5–10 minutes)</h4><p>Look at all your post-its. Classify them based on similar themes/categories: For example, career/school/government/public services. Look for duplicates and repetitive themes as well! The idea with this is to group together similar ideas and see how diverse each of your ideas are!</p><p>You can stack the stickies along each other as a mega-thread! For similar ideas, stack directly on top of the other.</p><h4>Part 1.2.2: Voting on problems (5 minutes)</h4><p>Take this time and individually on what you find interesting. Take your markers/pens and tick on the ideas. Each person gets 5 ticks to give away, so choose wisely! You can choose your own ideas and you can give multiple ticks to some ideas. In the end, we’ll be looking at the problemsthat are the most highly voted.</p><h4>Part 1.3.1: Understanding the problems (15 minutes)</h4><p>In this next part, look at the problem spaces and think a little bit about your vision. How can you make your solution into something people actually want? Think about generalising your solution to other people to cover as much ground as possible. Think abiout the following points:</p><ul><li><em>User Research</em> — Who are the users? What is their journey in the solution?</li><li><em>Competitor Audit</em> — What are the current solutions out there and where do you stand compared to them?</li><li><em>Technology</em>: Considerations &amp; Opportunities — How will you build the solution (in 24 hours)? — listing skills and experiences</li><li><em>Existing Product Audit </em>— What have you done so far? What worked and what didn’t? (This is more for during the hackathon to do a check on where you’ve reached in the design pathway)</li></ul><h4>Part 1.3.2: Brainstorming ideas using Crazy 8s (15 minutes)</h4><p>Now that you’ve considered this, grab a piece of A4 paper. Each person gets one. Divide it into 8 rectangles by folding. Use each square and sketch or write down your ideas for your problem and how you can tackle it. It can be as simple as the UI for your app or as complex as the userflow and their experience. Try to fill all 8 rectangles out and build on your original idea.</p><h4>Part 1.3.3: Voting on your crazy ideas and taking the nex steps(15 minutes)</h4><p>We’re back to voting. Same rules apply, each person gets 5 ticks to pick the best solutions and features to work on. Following this, find the idea with the most ticks on a fresh A4 sheet, sketch out 8 features or solutions that stem from these highly voted ideas.</p><h4>Part 1.4: Execution(22 hours)</h4><p>Congratulations on reaching this stage! Take a look at your sheet with the highest voted solution and the post-its with the highest voted problems. Take the A4 paper:</p><ul><li>Divide roles</li><li>Determine userflow</li><li>Literally anything to get your idea going. Take as many sheets as you want! Doodle and draw whatever you need to get your hack going!</li></ul><h3>Part 2: Prototyping tools</h3><p>Now that you have your ideas, here’s some tools that might help with your prototyping!</p><h4>Wireframing tools:</h4><p><strong>Web Based:</strong></p><ul><li><a href="https://wireframe.cc/"><em>Wireframe.cc</em></a></li><li><a href="https://www.fluidui.com/"><em>Fluid UI </em></a>— emphasis on web apps</li></ul><p><strong>Local software:</strong></p><ul><li><a href="https://pencil.evolus.vn/"><em>Pencil Project</em></a></li><li><a href="https://balsamiq.com/products/mockups/"><em>Balsamiq Mockups</em></a> — this has a 30 day free trial</li><li><em>Ye old Paper and Pencil</em> — underrated, lots of designs were worked out with bare hands and should never be underestimated</li></ul><h4>Boilerplates and Templates</h4><p><strong>For Quick and Easy website making:</strong></p><ul><li><a href="https://getbootstrap.com/docs/4.1/examples/"><em>Twitter Bootstrap 4.1</em></a><em> </em>— very very simple to use, nice responsiveness and easy implementation. 10/10 would recommend for easy modification of stock components</li><li><a href="https://materializecss.com/getting-started.html"><em>Materialize.css</em></a><em> </em>— a little shinier and fancier, but hogs more memory on loading. Based on Google’s Material Design rules</li><li><a href="http://getskeleton.com/"><em>Skeleton CSS</em></a><em> </em>— the most barebones grid system I’ve ever used. Basic and doesn’t get in the way of things. Basic™.</li><li><a href="https://github.com/h5bp/html5-boilerplate"><em>HTML5 Open-source Boilerplate</em></a></li></ul><p><strong>For setting up a Node.JS app and webpack templates:</strong></p><ul><li><a href="https://github.com/sahat/hackathon-starter"><em>Boilerplate by Github user sahat</em></a> — very comprehensive, easy to understand ReadMe and lots of integrations</li><li><a href="https://github.com/vuejs-templates/webpack"><em>VueJS Webpack</em></a></li><li><a href="https://v5.angular.io/guide/webpack"><em>Angular Webpack</em></a></li><li><a href="https://medium.com/@fastlane80/setup-react-js-with-npm-babel-6-and-webpack-in-under-1-hour-1a714f973506"><em>ReactJS Webpack</em></a> — leaves you with 23 more hours!</li></ul><p><strong>Web-hosting solutions</strong></p><ul><li><a href="https://pages.github.com/"><em>Github Pages</em></a> — simple to use, easy collaboration, but may experience some problems with React/Node based apps</li><li><a href="https://firebase.google.com/docs/hosting/"><em>Google’s Firebase </em></a>— integrates well with Firebase Database(JSON Backed) and has SSL certification too! Fancy features for app testing as well.</li><li><a href="https://www.heroku.com/"><em>Heroku</em></a> — good for WebApps, more advanced server options</li><li><a href="https://aws.amazon.com/s3/"><em>AWS S3 Buckets</em></a> — little complicated, but advanced options available, depending on your hack. Probably not recommended for beginners. Linux hosting options available for SSH</li><li><a href="https://ngrok.com/"><em>Ngrok </em></a>— shareable links from localhost, may experience slowdown in speeds though, but ideal for sharing within teams</li></ul><h3>The End</h3><p>If you’ve reached here, thanks for going through with the workshop! Hopefully this has helped you in some way! If you have any questions, feel free to reach out to me <a href="/service/mailto: kunmishra2599@gmail.com">here</a>! Thanks, and godspeed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dabf9af73fb3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntuoss/tgifhacks-102-rapid-prototyping-dabf9af73fb3">TGIFHacks #102 — Rapid Prototyping</a> was originally published in <a href="https://medium.com/ntuoss">NTUOSS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Odyssey: Practical Machine Learning]]></title>
            <link>https://medium.com/ntuoss/data-odyssey-practical-machine-learning-c22c20cc061?source=rss----bd776c72fe5---4</link>
            <guid isPermaLink="false">https://medium.com/p/c22c20cc061</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[Simeng Han]]></dc:creator>
            <pubDate>Sat, 07 Sep 2019 16:39:18 GMT</pubDate>
            <atom:updated>2019-09-07T16:39:18.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yHjBlfAWo8O-EC_l.jpeg" /></figure><p>Artwork by Brendan Hyde</p><p><strong><em>Disclaimer: This workshop is for educational purposes only. No prototype or outcome of any type is intended for commercial use.</em></strong></p><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5X6Z6xUN8WIHuuiq.png" /></figure><p><strong>Machine Learning</strong> is an interdisciplinary subject where computer science and statistics intersect. <br> In the workshop today, we will focus on the practical aspect of machine learning, i.e.,coding. In most cases, we give our algorithm an input and it gives us an output.<br> However, for a machine learning algorithm, we first feed a lot of data to the algorithm to let the algorithm determine itself how it should react to the data. This is the process of determining the parameters of the machine learning <strong>model</strong>.</p><p>In <strong>supervised</strong> machine learning, we feed the input and <strong>label</strong>, into the model and it will learn how to predict the output when we feed new inputs. Think about supervised learning as learning with a teacher who tells you the right answers.</p><p>In <strong>unsupervised</strong> machine learning, we only feed the input and the model will learn to predict the output solely based on the input. Think about unsupervised learning as learning without a teacher. Not all real-world data have a label, thus the necessity of unsupervised learning.</p><p>The second workshop will introduce two machine learning algorithms in order to demonstrate how the field can be used in real-world scenarios. <br> This includes logistic regression, a supervised method to solve classification problems, as well as k-means clustering, an unsupervised method to group together clusters of data by certain criteria.</p><p>We will use <a href="https://scikit-learn.org/stable/index.html">scikit-learn</a>, a python package built for implement machine learning algorithms. <br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">Logistic Regression with scikit-learn</a><br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html">K-Means with scikit-learn</a></p><h3>Google Colaboratory</h3><p>Copy this <a href="https://colab.research.google.com/drive/114hqdZq7EtMqYCNuMhwcb6xyLOZ6S1Dt">notebook</a> to your own drive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ItFpWkfAhNJxSpOG.png" /></figure><p>Go to <a href="https://drive.google.com/drive/folders/1udniYJu3xmxuNFud8FDn0yyESkXOAzCF?usp=sharing">this link</a> to download the data to be used in this workshop and upload it to Google Colaboratory.</p><h3>Odyssey Begins</h3><ol><li>Supervised Odyssey: Supervised Classification</li><li>Unsupervised Odyssey: Unsupervised Classification</li><li>End of journey</li></ol><h3>Packing up: Environment Setup</h3><blockquote><em>Import the module for linear regression algorithm from sklearn, plotting packages from matplotlib and data loading package numpy</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*owyg0mE0x_gM9ThP.png" /></figure><blockquote><em>Use numpy to load the txt file as a data object</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tFR2vwRwirP4yGJc.png" /></figure><blockquote><em>Inspect more details</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fOGsKUs0aGqkIiPs.png" /></figure><blockquote><em>Plot all data</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*28wqZYsPdugN5RbG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*6GHF-qr3L3MIfId1.png" /></figure><p>Logistic Regression is used when the dependent variable(target) is categorical, i.e., we want to find <strong>class</strong> which each of the variables belongs to. For example, to classify spam emails, we find whether an email belongs to the spam class or the normal class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*uB24dYpL51xJCYu5.png" /></figure><pre><strong>Algorithm intuition</strong> <strong>(</strong><a href="https://www.desmos.com/calculator/naf1qogfjn)"><strong>online demo</strong></a><strong>)</strong></pre><h3>Coding with sklearn</h3><blockquote><strong><em>Sigmoid</em></strong><em> function adds non-linearity into the model <br></em><strong><em>z</em></strong><em> is the input to the sigmoid function, which is the dot product of input </em><strong><em>X</em></strong><em> and the weight </em><strong><em>w</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tm1VU_-M-AAID1UQ.png" /></figure><p>Logistic regression predictive function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-c1Oxm6neJ388MR.png" /></figure><p>To conduct logistic regression with sklearn, we first create a <strong>LogisticRegression</strong> object<br> Then we <strong>fit</strong> the model to the <strong>data</strong><br> The <strong>intercept_</strong> and <strong>coef_</strong> are the model parameters(weights)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lK9qKkk_AHVZbEUv.png" /></figure><blockquote><em>After obtaining the parameters, let’s visualize the result by plotting the decision boundary. <br> Students whose score points are above the decision boundary will be admitted while the students below the decision boundary will be rejected</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*rMU9uVHyVMD17OAP.png" /></figure><blockquote><em>Now let’s use our trained logistic regression model to predict if a student will be accepted or rejected.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*krBfchQRidFcKfxl.png" /></figure><blockquote><em>Import the image reading module from matplotlib and the K-Means module from sklearn</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZMXfcWjSUgX0BqBE.png" /></figure><p>Read the image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DdUyWbe-Ep2O90TP.png" /></figure><p>A 2D image is comprised of two dimensional RGB values.<br> 700 is the row number.<br> 1000 is the column number.<br> 3 is the R, G, B value respectively.</p><p><strong>K-means</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bnS0yNTn4nCcchPw.png" /></figure><p>K-means is one of the most popular unsupervised clustering algorithms.<br> “K” in K-means refers to k number of clusters.<br> “Means” refers to finding the means, or centroids of the clusters.</p><pre><strong>Algorithm intuition (o</strong><a href="http://alekseynp.com/viz/k-means.html"><strong>nline demo</strong></a><strong>)</strong></pre><h3>Coding with sklearn</h3><blockquote><em>Reshape the image to be 2-dimension<br> To run the KMeans algorithm, we first create a scikit-learn KMeans object with the number of clusters assigned to 20, which is the number of colors we want for the compressed image. Fit the model to the data, then use the centroids to compress the image</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GdRLydD-f9y_Kfvm.png" /></figure><blockquote><em>Reshape X_recovered to have the same dimension as the original image<br> Now we can plot the original and the compressed image side by side.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FH7oFH7KQ5aezJ7SfAgx1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJhbizQgHSX96Zr2.png" /></figure><p>Congratulations on completing the Machine Learning Odyssey!<br> In this workshop we have learned how to use machine learning algorithms to solve some simple real-world problems.<br> In the next, which is also the last workshop of the NTUOSS Data Science workshop series, we will teach you <strong>deep learning</strong>, which is a subfield of machine learning and is even more interesting!</p><p>An approachable book if you want to learn more <a href="http://ciml.info/">A Course in Machine Learning</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zqJF8Y8mBtKdHN4G.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c22c20cc061" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntuoss/data-odyssey-practical-machine-learning-c22c20cc061">Data Odyssey: Practical Machine Learning</a> was originally published in <a href="https://medium.com/ntuoss">NTUOSS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TGIFHacks #98 — Getting in Data Science with Pandas]]></title>
            <link>https://medium.com/ntuoss/getting-in-data-science-with-pandas-ed4a282d7710?source=rss----bd776c72fe5---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed4a282d7710</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Wilson Thurman Teng]]></dc:creator>
            <pubDate>Sat, 31 Aug 2019 15:02:53 GMT</pubDate>
            <atom:updated>2019-09-18T12:32:39.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>TGIFHacks #98 — Getting into Data Science with Pandas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MP4mRAS1REne8wMN.png" /></figure><p><em>Artwork by </em><a href="https://github.com/hyde-brendan"><em>@hyde-brendan</em></a></p><p>This workshop features a hands-on approach to learning the basics of <a href="https://pandas.pydata.org/pandas-docs/stable/">Pandas</a>, <a href="https://matplotlib.org/tutorials/index.html">Matplotlib</a>, <a href="https://seaborn.pydata.org/introduction.html?highlight=jointplot">Seaborn</a> &amp; <a href="https://scikit-learn.org/stable/tutorial/index.html">Scikit-learn</a>. Familiarity with Python syntax or programming data types (e.g.integer,float,etc) would be useful but not required to complete this workshop.</p><p><strong>For a hands-on walk-through of the workshop with step-by-step explanations of the code, a recording of the workshop is available (Skip to 17:39 if you have already successfully setup and uploaded the 3 required data files to Colab):</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuOEKrymbvoc%3Fstart%3D105%26feature%3Doembed%26start%3D105&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuOEKrymbvoc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuOEKrymbvoc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/32fe1a83f5c82faeed216a35e7881765/href">https://medium.com/media/32fe1a83f5c82faeed216a35e7881765/href</a></iframe><p>For the full code discussed in this workshop, please please head over to <a href="https://github.com/wilsonteng97/NTUOSS-PandasBasics">this Github repository</a>.</p><p>For errors, typos or suggestions, please do not hesitate to <a href="https://github.com/wilsonteng97/NTUOSS-PandasBasics/issues/new">post an issue</a>! Pull requests are very welcome, thank you!</p><p><strong>Disclaimer:</strong> <em>This document is only meant to serve as a reference for the attendees of the workshop. For a full, comprehensive documentation of the python libraries discussed, please check the official documentations linked above.</em></p><h3>1. Introduction</h3><p>This workshop is primarily about getting yourselves started with Data Analysis. We will begin by covering some background on why pandas, then move on to how to get it running on <a href="https://research.google.com/colaboratory/faq.html">Google Colab</a> and then finally cover some of the basic commands which you’ll be using when working with Data Analysis.</p><p>Since this is a basic workshop, we’ll walk you through the setup phase for colab.</p><h3>1.1 Google Colaboratory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*VKFZW64X6E9g24Vb.png" /></figure><p>Colab is a free Jupyter notebook environment that requires no setup, and runs entirely (writing, running, &amp; sharing code) on the Cloud. For those of you familiar with Jupyter Notebooks, you can think of colab as a Jupyter Notebook stored in Google Drive. A typical notebook document is composed of cells, each of which can contain code, text or images.</p><h3>1.2 Setting up Google Colab</h3><p><strong>Instructions for first-timers using Google Colab on Google Drive:</strong></p><ol><li>Create a gmail account (if you do not have one already).</li><li>Download the .zip file from <a href="https://github.com/wilsonteng97/NTUOSS-PandasBasics/archive/master.zip">this link</a>.</li><li>Extract the .zip file, find HDB_ResalePrices.ipynb.</li><li>Create a a new Folder <strong>TGIF Pandas Basics</strong> on your Google Drive.</li><li>Upload HDB_ResalePrices.ipynb inside this new folder.</li><li>Click on HDB_ResalePrices.ipynb.</li><li>Select “Open with”, select “Connect more apps”.</li><li>Search for “colab”, press “Connect”.</li><li>Select “Open with Google Colaboratory”.</li><li>Drag the 3 files from Data (in your extracted .zip file) into Google Colab.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b0pBT-hMnf1M-OJ1.png" /></figure><p><strong>Instructions for those who have used Google Colab on Google Drive before:</strong></p><ol><li>Download the .zip file from <a href="https://github.com/wilsonteng97/NTUOSS-PandasBasics/archive/master.zip">this link</a>.</li><li>Extract the .zip file, find HDB_ResalePrices.ipynb.</li><li>Create a a new Folder <strong>TGIF Pandas Basics</strong> on your Google Drive.</li><li>Upload HDB_ResalePrices.ipynb inside this new folder.</li><li>Right-click on HDB_ResalePrices.ipynb, mouse-over &quot;Open with&quot; and select &quot;Google Colaboratory&quot;.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dNbKy1MjT-sheL1a.png" /></figure><p>6. Drag the 3 files from Data (in your extracted .zip file) into Google Colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LR52s8yaSqCzdlnC.png" /></figure><h3>1.3 Data Science Process</h3><p>Data Analysis typically involves the following steps:</p><ol><li>Problem statement/shaping</li></ol><blockquote>A Data Science Project should be business oriented. Problem statements/shaping should be done with the intent of achieving results.Can you relate the problem to data? Would data help you in practice?</blockquote><p>2. Data Collection</p><blockquote>Collect relevant data that matches the problem.</blockquote><p>3. Data Cleaning/Processing</p><blockquote>Some common errors in data to lookout for are missing/corrupted values, datatype mismatches.</blockquote><p>4. EDA(Exploratory Data Analysis)/Visualization</p><blockquote>Find patterns in your data and compute vital statistics (e.g.Mean,Median, Standard deviation, etc)</blockquote><p>5. Data Modelling</p><blockquote>Split your data in train and test sets. Create a machine learning model from your training set for prediction.</blockquote><p>6. Data Evaluation</p><blockquote>Evaluate your model using a suitable metric (e.g.Mean squared error, f1 score, etc) and try to improve the score that metric.</blockquote><h3>2. HDB Resale Prices Example</h3><p><em>Dataset taken from </em><a href="https://data.gov.sg/group/infrastructure"><em>Data.gov.sg</em></a></p><p>Now that we’ve discussed the Data Science process, let’s dive into our example. As some of you may have guessed, we are going to predict the price of HDB resale flats!</p><p><strong>Problem Statement:</strong><em>Can we predict the the resale price of a house given the floor area of the house (in m2)?</em></p><p>As such, we are using the floor_area_sqm feature to predict resale_price.</p><h3>2.1 Import Libraries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XeahvprCMTbQ7HsO.png" /></figure><h4>2.1.1 For Data Processing/Cleaning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j_4v7783bG3CeQjF.png" /></figure><p><a href="https://pandas.pydata.org/pandas-docs/stable/">Pandas</a> is typically used for data manipulation &amp; analysis and is highly optimized with critical code paths written in Cython or C++.</p><p><a href="https://www.numpy.org/">Numpy</a> is used to manipulate large, multi-dimensional arrays and matrices, which is very useful for processing data for Data modelling.</p><h4>2.1.2 For Visualization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*n8qM6WkxtLvK10-0.png" /></figure><p><a href="https://matplotlib.org/tutorials/index.html">Matplotlib</a> is a multi-platform data visualization library built on NumPy arrays.</p><p><a href="https://seaborn.pydata.org/introduction.html?highlight=jointplot">Seaborn</a> is based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.</p><h4>2.1.3 For Machine Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*za2UDEQnLtWTcl8n.png" /></figure><p><a href="https://scikit-learn.org/stable/tutorial/index.html">Scikit-learn</a> provides a range of supervised and unsupervised machine learning algorithms.</p><p><a href="https://keras.io/">Extra: Keras</a> is a high level API typically used for rapid prototyping on small data sets.</p><p><a href="https://www.tensorflow.org/">Extra: Tensorflow</a> is a framework that provides both high and low level APIs and is typically used on large data sets because of it’s high performance.</p><p><a href="https://pytorch.org/">Extra: Pytorch</a> is lower-level API focused on direct work with array expressions. It has gained immense interest recently, becoming a preferred solution for academic research, and applications of deep learning requiring optimizing custom expressions.</p><h3>2.2 Reading data into Dataframe format</h3><p>Before we can do any Datascience work, we must convert the data we want to analyse into a Dataframe object. In this case, our data is in the .csv format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2becf727fbb2824375d1f008c40abff9/href">https://medium.com/media/2becf727fbb2824375d1f008c40abff9/href</a></iframe><h3>2.3 Data Cleaning/Processing</h3><p>Now we are ready to clean our data!</p><h4>2.3.1 Concatenating separate data frames</h4><p>Sometimes, you may get your data separated into multiple files although they have the same formats. This is especially common since the limit for excel is 1,048,576 rows and datasets are typically very large, especially with deep learning becoming more popular.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d65825b41e17e852faf4a52c25722c17/href">https://medium.com/media/d65825b41e17e852faf4a52c25722c17/href</a></iframe><h4>2.3.2 Remove features unnecessary for your problem</h4><p>After exploring your data, you may want to remove features that do not contribute to your problem, and are hence unnecessary. Removing features from your dataframe helps to prevent cluttering and allows you to save memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05775fc46385d0851f64bd9b29340315/href">https://medium.com/media/05775fc46385d0851f64bd9b29340315/href</a></iframe><h4><strong>2.3.3 Remove NaN values from Dataframe</strong></h4><p>Within Pandas, a missing value is denoted by NaN. You can either choose to remove rows which contain NaN datapoints or replace these values. For example, replace it with the result of a function of the other numerical features. This will be highly dependent on the context of your problem. For the purpose of this workshop, we will remove the NaN values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c0e36154e95451529de07ece7ae92f2/href">https://medium.com/media/1c0e36154e95451529de07ece7ae92f2/href</a></iframe><h4>2.3.4 Sorting Dataframe</h4><p>For ease of analysis, you may want to sort your dataframe according to a few features. For the example below, the order of sorting will be the following: [&#39;feature1&#39;, &#39;feature2&#39;, &#39;feature3&#39;, &#39;feature4&#39;]</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6470eb82b559eb408bddb8247c6f4721/href">https://medium.com/media/6470eb82b559eb408bddb8247c6f4721/href</a></iframe><h4>2.3.5 Changing dtype of features to better suit context of Dataset</h4><p>Before we continue, this is a overview of the common datatypes you will encounter in Pandas. To find out more, <a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html#dtypes">check out the official Pandas Documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*v9ktVrPLhdCmiaWP.png" /></figure><p>We will first have to find out the datatype for each feature in the dataframe. This can be done using the.info() method or the .dtypes function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa06b5a58acce4c9165097b0670aee75/href">https://medium.com/media/fa06b5a58acce4c9165097b0670aee75/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db29610c523520044311d81e70c3bf11/href">https://medium.com/media/db29610c523520044311d81e70c3bf11/href</a></iframe><p>Next, dictate the feature and the datatype you want to convert to. If there are no errors, the datatypes you want to convert to is compatible and conversion is successful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be89e6d11ad6d9e1365ee6fa104b5791/href">https://medium.com/media/be89e6d11ad6d9e1365ee6fa104b5791/href</a></iframe><p>Use the .info() method or .dtypes function to check that the datatype conversion is successful.</p><h4>2.3.6 Feature Engineering</h4><p>Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data. Put simply, feature engineering turns your inputs into features the algorithm can understand and helps with your Data Modelling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9439ad8976cf4ceb55b92254241b379f/href">https://medium.com/media/9439ad8976cf4ceb55b92254241b379f/href</a></iframe><p>The code above will create a new feature column.</p><p><strong>Extra: using a function to create an engineered feature</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b46ce8b268281a48ff2ce2f0b921cf46/href">https://medium.com/media/b46ce8b268281a48ff2ce2f0b921cf46/href</a></iframe><p>Use the .apply() method to create your engineered feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d53ce6b5a2826a1abc6e786c6490f2e7/href">https://medium.com/media/d53ce6b5a2826a1abc6e786c6490f2e7/href</a></iframe><h3>2.4 Visualization</h3><p>Data visualization helps to encode data into visual objects (Lines, Points, Bars, etc). This helps you to understand your data better as well as communicate this information more efficiently to stakeholders.</p><p>Uni-variate Analysis refers to the analysis of only 1 variable at a time.</p><p><strong>2.4.1(a) Boxplot</strong></p><p>The orient argument gives you the flexibility to change the orientation of the Boxplot. In this example, the &quot;h&quot;(Horizontal) orientation is specified. Try changing it to&quot;v&quot;(Vertical)!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0de1f4590bd59db7d8132970efc0123b/href">https://medium.com/media/0de1f4590bd59db7d8132970efc0123b/href</a></iframe><p><strong>Understanding a Boxplot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*yzhvdtUox9q9l9jd.png" /></figure><p><strong>2.4.1(b) Distplot</strong></p><p>This will draw a histogram and fit a <a href="https://mathisonian.github.io/kde/">kernel density estimate (KDE)</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92e07fddb979ed47d6e977f58e84c7f4/href">https://medium.com/media/92e07fddb979ed47d6e977f58e84c7f4/href</a></iframe><p><strong>Understanding KDE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*bsFSoUrYhyqtNXdP.png" /></figure><p><strong>2.4.1(c) Violinplot</strong></p><p>A Violin Plot is used to visualize the distribution of the data and its probability density. It is the combination of a Boxplot and a KDE Plot that is rotated and placed on each side, to show the distribution shape of the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a70722f1bb95ab71486d7f85370621f6/href">https://medium.com/media/a70722f1bb95ab71486d7f85370621f6/href</a></iframe><p><strong>Understanding a Violinplot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*SlZoEUS-n5XWPtae.png" /></figure><p><strong>2.4.1 <em>Extra: Grouping graphs together</em></strong></p><p>You may want to group your graphs together for easier analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b0fbbd49c47d067cdd9cb20dd85f215/href">https://medium.com/media/6b0fbbd49c47d067cdd9cb20dd85f215/href</a></iframe><p>The plt.subplots method returns a figure object , f and a 2D-array of axes object, axes.</p><ul><li>f is the &quot;canvas&quot; you will be &quot;painting&quot; your graphs onto.</li><li>axes is a 2D-array dependent on what you have specified for the rows &amp; columns argument. In the example above, <em>axes = [[subplot_1, subplot_2, subplot_3], [subplot_4, subplot_5, subplot_6]]</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GLEv3Hr2TR522kJp.png" /></figure><h4>2.4.2 Using Matplotlib/Seaborn for Multi-variate Analysis</h4><p>It can also be useful to visualize a bivariate distribution of two variables. Multi-variate Analysis refers to the analysis of only multiple variables at the same time.</p><p>The easiest way to do this in seaborn is to just use the .jointplot() function. The jointplot plots the bivariate scatterplot and histograms.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0af82ac305ede42589295d496ffcaae3/href">https://medium.com/media/0af82ac305ede42589295d496ffcaae3/href</a></iframe><p><strong>2.4.2(a) Jointplot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oh4wKaKzCPcc8hKQ.png" /></figure><p><strong>2.4.2(b) Heatmap</strong></p><p>We can also use a heatmap to plot the correlations between 2 variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eaa2e8806855e4d34a79b0b2c2c2b74/href">https://medium.com/media/1eaa2e8806855e4d34a79b0b2c2c2b74/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TnmBo3NSLHXe0yhE.png" /></figure><h4>2.4.3 Analyzing Categories</h4><p><strong>2.4.3(a) Catplot</strong></p><p>After converting some of our features into categorical datatypes to categories (as we have learnt above in 2.3.5), we can also do some analysis on them!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5957eaf2d0949b3e421f8e50102fe0c3/href">https://medium.com/media/5957eaf2d0949b3e421f8e50102fe0c3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zJSNCVVaZPJG-Jwo.png" /></figure><h3>2.5 Data Modelling (Machine Learning)</h3><h4>2.5.1 What is Linear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*HPKafVhaW_PHkxqS.png" /></figure><p>Linear Regression is all about trying to find the best fit line for your datapoints. The intuition is to minimize the “Sum of Squared Errors” (SSE), which is the sum difference between actual value and predicted value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qVJGbzz2ISIlHsEl.png" /></figure><p>The goal is to eventually generalize the dataset and predict the dependent variable with reasonable accuracy given the independent variable.</p><h4>2.5.1 Splitting our dataset in Train and Test sets</h4><p>Before we begin Data Modelling, we have to split our dataset into train and test sets so we have a measure to evaluate our model’s performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c76b50cd158f6d531f7ef7cd671f4f2/href">https://medium.com/media/8c76b50cd158f6d531f7ef7cd671f4f2/href</a></iframe><p><strong>Explanation of code</strong></p><ol><li>We first reshape our X and y to get a 1D-array.</li><li>Next, we split our dataset into X_train, X_test, y_train and y_test with 20% of our dataset as the test set.</li><li>Lastly, we print out the shape of X_train, X_test, y_train and y_test.</li></ol><h4>2.5.3 Visual Representation of the Linear Regression Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sJ0YRygb_oHqqyze.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1526690f7c842d109cefe11fc8ed717e/href">https://medium.com/media/1526690f7c842d109cefe11fc8ed717e/href</a></iframe><p><strong>Explanation of code</strong></p><ol><li>We first create a LinearRegression Object linreg.</li><li>Then, using we fit our linreg object with our training set data - X_train and y_train.</li><li>Afterwards, we get the save the x-coordinates and y-coordinates of the linreg line into regline_x and regline_y respectively.</li><li>Lastly, we plot all the datapoints of the train dataset as well as the linreg best-fit line.</li></ol><h4>2.5.2 Prediction of Response based on the Predictor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GjunMITK-lsS13NY.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e7a4a9ebdbd2e11b8bb05338e06d3ad/href">https://medium.com/media/1e7a4a9ebdbd2e11b8bb05338e06d3ad/href</a></iframe><p><strong>Explanation of code</strong></p><ol><li>We first save the predicted y-coordinates from X_test into resale_price_pred.</li><li>Next, we plot all the datapoints in the test set.</li><li>Lastly, we plot the resale_price that we have predicted from X_test using our best-fit line.</li></ol><h3>3. Further Learning</h3><h4>3.1 Extension of today’s workshop:</h4><h4>Other interesting questions</h4><ul><li>What is the best/worse times of the year to sell your house? By how much do prices change?</li><li>How is the travel time from different locations to central area affecting the HDB resale price?</li></ul><h4>Interesting Datasets to consider</h4><ul><li><a href="https://www.kaggle.com/airbnb/seattle">Airbnb (Seattle) Open Data</a></li><li><a href="https://www.kaggle.com/ruvenguna/all-data-to-use">Singapore’s Pollution Levels</a></li></ul><h4>3.2 Setting up your Data Analytics Environment!</h4><h4>3.2.1 Anaconda Distribution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VpgweTryAXcnksKR.png" /></figure><p><a href="https://www.anaconda.com/distribution/#download-section">Anaconda</a> is one of several Python distributions. Python on it’s own is not going to be useful unless an IDE is installed. This is where Anaconda comes into picture.</p><p><strong>The following are some of the default applications/libraries available by default that i personally find useful:</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Project_Jupyter#Jupyter_Notebook">Jupyter Notebook</a> (Data Science Environment)</li><li><a href="https://en.wikipedia.org/wiki/Project_Jupyter#Jupyter_Lab">JupyterLab</a> (Simply put, Jupyter Notebook on the web)</li><li><a href="https://en.wikipedia.org/wiki/Rstudio">Rstudio</a> (For those who are less comfortable with programming)</li><li><a href="https://en.wikipedia.org/wiki/Visual_Studio_Code">Visual Studio Code</a> (One of the most powerful/easy to use code editors out there! Props to Microsoft! Or you can use <a href="https://vscodium.com/">VSCodium</a> for those who are worried of Telemetry data collection)</li><li>Tons of Datascience Libraries pre-installed!</li></ul><h4>3.2.2 Step-by-Step Setup guide — Guide by Datacamp</h4><p>Setup on <a href="https://www.datacamp.com/community/tutorials/installing-anaconda-windows">Windows</a><br>Setup on <a href="https://www.datacamp.com/community/tutorials/installing-anaconda-mac-os-x">Mac</a></p><h4>3.3 Get Rewarded??</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HjPB4WV8mltvUosi.png" /></figure><p><a href="https://www.kaggle.com/competitions">Kaggle</a> is where you can join Data Science competitions either alone or as a team and earn prize money. Although i would highly recommend to check out the <a href="https://www.kaggle.com/competitions?sortBy=recentlyCreated&amp;group=general&amp;page=1&amp;pageSize=20&amp;turbolinks%5BrestorationIdentifier%5D=1aa400b0-1c2b-410b-a880-aae48e7e1930&amp;category=gettingStarted">“Getting Started”</a> Category first.</p><p><em>Originally published at </em><a href="https://github.com/wilsonteng97/NTUOSS-PandasBasics"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed4a282d7710" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ntuoss/getting-in-data-science-with-pandas-ed4a282d7710">TGIFHacks #98 — Getting in Data Science with Pandas</a> was originally published in <a href="https://medium.com/ntuoss">NTUOSS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>