<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David Joy on Medium]]></title>
        <description><![CDATA[Stories by David Joy on Medium]]></description>
        <link>https://medium.com/@david.joy1588?source=rss-321fcac8b3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NzT3Vmr7ZQ7IGp1k</url>
            <title>Stories by David Joy on Medium</title>
            <link>https://medium.com/@david.joy1588?source=rss-321fcac8b3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:27:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@david.joy1588/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A/B Testing — Clearing Perspective]]></title>
            <link>https://medium.com/@david.joy1588/a-b-testing-clearing-perspective-bb28a9a4d5c7?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb28a9a4d5c7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chi-square-test]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 18:41:20 GMT</pubDate>
            <atom:updated>2019-04-04T18:44:32.537Z</atom:updated>
            <content:encoded><![CDATA[<h3>A/B Testing — Clearing Perspective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uRxE2XKaAovkWmiAHhI3aA.png" /></figure><p>Thinking about the problems in the context of real world scenarios. A/B testing is one way to determine based on observation and experimentation if there is an effect of change of different parameters of a particular entity such as website layout / product features etc on the adoption or conversion etc etc. This method is so popular as its based on observations from users that it has been very well adopted by companies such as Netflix, Facebook, Google etc. Google famouly once did an A/B test to determine the color Blue based on 41 different shades of Blue on the hyperlinks that increased there click rate or conversion rate. Netflix heavily conducts A/B testing to improve its user experience and conversion rate.</p><p>My goal in this blog is to address various steps to understand A/B testing and to address the statistics behind it. OfCourse, there are various A/B testing available such as</p><ul><li>Parametric Tests</li><li>Non Parametric Tests</li><li>Resampling Tests</li></ul><p>Parametric and Non Parametric essentially are the classical methods while, Resampling Tests include bootstrapping etc.</p><p>Some essential components of A/B testing is to know how to develop a Hypothesis and then to break it up into a Null Hypothesis and Alternate hypothesis.</p><p>I personally like the PICOT method for developing a hypothesis and then from the Hypothesis we need to develop a experiment which is out A/B test to validate or test our hypothesis.</p><p>Lets look at an example where we present different layouts to visitors of a website and see if their is a higher conversion rate.</p><p>The hypothesis written something like this based on the PICOT</p><p>- Null Hypothesis : The Visitors of website (P — population) who recieve Layout B (Treatment Group) will not have higher conversion rate as compared to the those who recieve Layout A (control Group) at the end of a visit<br>- Alternate Hypothesis : The Visitors of website (P — population) who recieve Layout B (Treatment Group) will have higher conversion rate as compared to the those who recieve Layout A (control Group) at the end of a visit</p><p>PICOT stands for → P — Population of Visitors , I — Intervention in the form of Layout A/B, C — Comparison — Treatment group vs Control group, O — outcome — Converstion rate , T — at what time — At the end of a visit.</p><p>Translating : let mean converstion rate of old page be Co and new page be Cn</p><p>H0 = Co — Cn &gt;=0<br> H1 = Co — Cn &lt;0</p><p>The above then forms our Hypothesis.</p><h3>T Test/Z Test for hypothesis testing</h3><p>With hypothesis testing we try to use a sample of data and try to hypothesize based on the mean of the sample the true mean of the population. Our null hypothesis is usually what we believe the population mean is equal to where as the alternate hypothesis is usually the mean being greater than or less than the population mean. If we don’t know if its greater than or equal to population mean then we just say its not equal to. The difference lies in how we do the T test to determine if the Null needs to be reject or not. Lets look at the below.</p><ul><li><em>H</em>1: βk &gt; <em>c, here we do right one tail test</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97tTsVNDbymImjnHR15a6A.png" /></figure><ul><li><em>H</em>1: βk &lt; <em>c, Here we do left one tail test</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-xVhZaUiVpQzLPibLuvWQ.png" /></figure><ul><li><em>H</em>1: βk ≠ <em>c , Here we use a paired test. So 5% significance level is broken on either side of the distribution.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmi_iHBI4AffEL52q9heJQ.png" /></figure><p>Now, We must also have an understanding of what is the difference between a Z statisitic and T statistic, also where to apply which one. Use the Z test when you have a sample with more than 30 data points , a T test when less than 30 data points. Also, Z test is usually done when we know the distribution is normal, when its not know and the data points are less than 30 we use the T test. Also, its important to note that the other assumptions of the Central Limit theoram are met.</p><p><a href="https://github.com/david7joy/A-B-Testing-Project/blob/master/A-B-Testing%20-%20EcommerceWebsiteData%20.ipynb">Check this link with some code on A/B testing on my github.</a></p><h3>Chi-square statistic for hypothesis testing</h3><p>This essentially helps us understand the goodness of fit i.e when we are looking at distributions. The chi-squared test is used to determine whether there is a significant difference between the expected frequencies and the observed frequencies in one or more categories. So Chi Sqr Test helps us answer questions such as Does the rate of success differ across two groups?</p><p><strong>Assumptions</strong></p><ul><li>Samples are taken at Random</li><li>Expected value/result/proportion is atleast equal to or greater than 5</li><li>Independant</li></ul><h3>T Test vs Chi-Sqr Test</h3><p>It is essential to understand what we are trying to test.</p><p>With T test the question we ask is <strong><em>“ Is the average Conversion rate higher or lower for treatment group as compared to the control group ? or Does the average value differ across two groups?“</em></strong></p><p>With the Chi-Sqr test we ask <strong><em>“ Does the conversion rate across two groups differ ?“</em></strong></p><h3>Conclusion</h3><p>At the end of the day A/B test have been found to be very reliable in finding how different variations help consumer converstion or click through rate etc. A very humble but useful data science technique. Ofcourse, Companies such as Google, Netflix , Facebook etc conduct extensive and aggressive A/B test on it users. One good resource I found was on the <a href="https://medium.com/netflix-techblog/its-all-a-bout-testing-the-netflix-experimentation-platform-4e1ca458c15">Netflix Blogs</a> about how it is a key integral part of their engineering.</p><p><a href="https://github.com/david7joy/A-B-Testing-Project/blob/master/A-B-Testing%20-%20EcommerceWebsiteData%20.ipynb">Check this link on A/B testing in python with both T test and Chi Sqr test on my github.</a> Hope this helps you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb28a9a4d5c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A bit of Kafka]]></title>
            <link>https://medium.com/@david.joy1588/a-bit-of-kafka-952cab07d945?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/952cab07d945</guid>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[streaming-analytics]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 06:46:15 GMT</pubDate>
            <atom:updated>2019-03-20T07:07:11.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>A bit of Kafka and its Awesomeness !</h3><p>Kafka is used for building real-time data pipelines and streaming apps. It is horizontally scalable, fault-tolerant, wicked fast, and runs in production in thousands of companies. It works essentially has producers, consumers and distributed fault tolerant cluster. The simplest way to explain Kafka is to look at it like messaging service, however, its just more than that. It is more capable. I personally feel its an essential block in the data pipeline architecture for any company in the modern era. Kafka was originally a project started at LinkedIn and then went on to become a top level apache project. The Kafka community is growing and its uses cases are surpisingly on the rise and continue to impress. Companies such as Walmart, Cisco, Netflix, Uber etc all heavily use Kafka in the data pipeline. It has become an essential element of there architecture.</p><h3><strong><em>Let’s look at some key ideas of Kafka and how it works.</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfSRxiARcdbRizUvTL-pXQ.png" /><figcaption>Kafka The Architecture</figcaption></figure><p>We have our producers sending in the data and our consumers pulling it out. But between those two, inside of the cluster, we have something called brokers. And a broker is a logical separation of tasks, and you can think of it where a broker could be on a different machine perhaps, so it distributes the load and provides multiple backups of your data. That is, of course, if you configure it that way. Now each broker handles one or more Kafka topics. Topics are things that you want to track it can be likes on a website or clicks on the website or customer information change. Each of these tasks can be set up as individual topics in Kafka and can be partitioned over multiple brokers which can be across various machines. This enables us from losing the data.</p><p>The partitions basically has a lead partition where all the writes happen and copies of the data is made across slave partitions or the replicas of that. A Topic is separate log in Kafka. These topics in the architecture are partitioned across multiple brokers,which allows them to be resilient. If one broker goes down or one hard disk fails, the topic can still be read, the previous broker which was handling only the Reads, now will start handling the Writes.</p><p><strong>The Anatomy of a Topic</strong></p><p>There are three partitions here. There is partition zero, one, and two and they start with the index of zero. So that’s important to know as we start to set things up and actually work with the data. And the way they work is that when a Write happens it does so first on the lead partition, this is partition zero. Now with partition zero what’s going to happen is after the data gets written there, it’s going to also be written to the other partitions so we have replicated copies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CydiDLuU1QJaZ7dPLZzTsw.png" /></figure><p>Now a consumer could look at any of these partitions and depending on their offset, which is the number of changes that they’ve processed or handled since their last Read from the topic, they may be redirected to a different partition. So there are different ways of strategizing about this so that way you’re balancing the load across your cluster effectively. We’ll dive into that a little bit more coming up but the anatomy is basically that you have a topic, which is a category of the thing that you want to keep track of separated by partitions across brokers to give you that resilient, sustainable system.So what is a broker? Well a broker is a logical separation of partitions of topics, it’s just containers or buckets. They handle many topics and they give you that resiliency. Let’s take a look at an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wh7bsbJwA2u0Bg1mqHRpQ.png" /></figure><p>Here we have three brokers and we have lead topics,and these topics here are of partition zero. And you can see that those topics also exist on the other brokers, meaning they’re evenly distributed across our cluster. And those are in green because they’re areplicated copy, they’re not they lead copies. Now if this is our cluster and let’s say broker three goes down. On broker three we have topics one, two, and three but only one of them is really the lead. So, if I fast forwarded and see what would happen the lead for topic three now has been moved over to broker one. So that way broker one is little bit overloadedbecause it’s handling writes for both topic one and topic three. And now broker two has adjusted its partition as well. So, when one of these goes down,the system continues to operate and it just automatically shuffles where the operations are occurring.</p><p><strong>Consumers</strong></p><p>First off, consumers are organized into consumer groups, and these groups, they have all the partitions of a topic that they’re reading from, divided among all the consumers. So, if there are 30 partitions and 30 consumers in the group, each one will have their own partition assigned to them. Now, as consumers come and go from the consumer group, the consumer group needs to be rebalanced. Now, this is handled by Zookeeper and there is a newer version of Kafka which has a Broker coordinator, but just know that there is essentially another part of the system that is monitoring these consumer groups, making sure that they don’t become overly bloated or that partitions are not being assigned appropriately. So, for the configuration, when you set up the consumer group, you need to add the consumer group ID, which is essentially the name or the identifier for the consumer group. There’s also the session timeout,with a default value of 30 seconds, but you can increase this to avoid rebalancing too often, and creating too much overhead. The other thing is the heartbeat, and the heartbeat is set up to let zookeeper or the broker coordinator know that the consumer is still there. If it stops, then it will rebalance because it knows that the consumer is no longer there, and it needs to reassign the partitions so that everything is in harmony on your cluster. Now, this heartbeat can be adjusted as well, using the interval configuration, and it just helps with throughput again, and it tries to reduce any overhead that may cause your cluster a little bit slowness, and we don’t want that. Remember, we want super low latency here when maximize the throughput flow of our system. And one of the key things about throughput is the autocommit. And the autocommit speaks to the offset of the consumer,and remember, each consumer will be reading from a different partition, so they’ll have different offsets, and that is the number of changes that they’ve read, so if a topic has five thousand changes, they may not have all read all five thousand at all the times, so what ends up happening is, you’ll have different levels of this, and the autocommit is every five seconds, where it logs essentially where it’s at, and that is because if the consumer were to go down and then come back online, there may be a number of messages that have occurred in between that time, and it knows exactly where it needs to pick up from, so that way it doesn’t lose any changes, and nothing gets mixed up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TLwQK5lsf2IHJZcnBUCLg.png" /></figure><p>So, if we take a look at a diagram here, trying to explain this, we have a couple of different servers, and we have different partitions of a topic, and the topic is then spread across multiple servers. So you have these different topics on these different servers and they are serving these different consumer groups. You have Consumer Group A and Consumer Group B. Now, you can see that the partitions are evenly distributed so that in Consumer Group A, it only has two consumers, so all four of the partitions on the multiple brokers are being assigned to each consumer. That way, it can read from either one of those. It knows that it can read from any of these different partitions. Now, in Consumer Group B, we have four consumers and four partitions, so each one only gets assigned one, so each consumer is only reading from one of the partitions. This way, if there is some sort of issues with the offset and it needs to switch, it knows where it left off again. So, the rebalancing when a consumer goes offline or leaves the group or comes back in the group, it doesn’t matter so much because it has that offset. It knows, it remembers exactly where it left off from. If we take a look at this example and again, we’ll run this in our terminal window here in a minute. We can run the console consumer, which comes with Kafka.We can set up the local host of where it’s running.We can tell it the topic, where we want to read from,and then it will actually print those messages out.So, if you watched the previous clip, where we set up the producer example, we entered three different messages, and here’s the example where we’re reading those and we’re telling it where to read them from, what is the offset. In this case, we’re passing in from beginning. And again, we’ll run this here in a minute so you can see it in action.</p><p><strong><em>Hardware Specs</em></strong></p><p>Memory — uses file system so need memory till it data can be written to disk. A machine with 64 gigs of RAM is a decent choice, but there are plenty of people using 32 gig machines out there as well. Less than 32 gigabytes of RAM tends to be counterproductive, meaning you need to have a lot of little machines instead of just having some medium sized machines. So, I would recommend starting with 32 gigabytes of memory and going up from there.</p><p>CPU doesnt need to be too intensive as most of the Kafka function is disk and memory. so a 24 core machine is fine.</p><p>Disk And Network —Fast disk and 1 to 10 Gigabyte ethernet.</p><p>Get medium sized machines with decent amount of nodes in the cluster.</p><p><strong><em>Adding and Removing Topics</em></strong></p><pre>bin/Kafka-topics.sh<br>--zookeeper zk_host:port/chroot<br>--create --topic my_topic_name<br>--partitions 20<br>--replication-factor 3<br>--config x=y</pre><pre><strong># add parititons</strong><br>bin/Kafka-topics.sh<br>--zookeeper zk_host:port/chroot<br>--alter --topic my_topic_name<br>--partitions 40</pre><pre><strong># Modifiying Topic</strong><br>bin/Kafka-topics.sh<br>--zookeeper zk_host:port/chroot<br>--alter --topic my_topic_name<br>--delete-config x</pre><pre><strong># topic deletion is disabled by default, to enable</strong><br>delete.topic.enable = true</pre><pre><strong># Delete Topic</strong><br>bin/Kafka-topics.sh<br>--zookeeper zk_host:port/chroot<br>--delete --topic my_topic_name</pre><pre><strong># Checking Consumer Position<br></strong>bin/Kafka-run-class.sh kafka.tools.ConsumerOffsetChecker<br>--zookeeper localhost:2181<br>--group test</pre><pre><strong># Configuring Consumer Groups</strong><br>bin/Kafka-consumer-groups.sh<br>--bootstrap-server broker1.9092<br>--describe<br>--group test-consumer-group</pre><p><strong><em>Monitoring in Kafka</em></strong></p><p>We can use kafka monitor open sourced by LinkedIn which is a great tool.</p><p><strong><em>Kakfa Auditing</em></strong></p><p>Auditing is another thing that you’re going to want to pay close attention to when running Kafka in a production environment. And, when we’re talking about auditing, what we’re talking about is verifying that all the messages are being handled properly, and making sure that they’re being delivered and they’re being processed and everything is in sync, and you’re not losing messages or losing data. There are three types of auditing that I’ll talk about here, but there are lots more options that you can explore. The first one is just the, what is called Kafka Audit. And this is essentially a methodology of creating an auditing system that you roll yourself. You roll your own. Now, the way that works is you have multiple data centers and you use mirror maker to mirror essentially the different messages going back and forth, and then you use a third data center to compare the results and see if what’s happening across those two data centers is in fact correct. If it in fact does match up.The second option I’ll talk about here, because that one can be really detailed and you can go really down the rabbit hole with it. So there’s other options out there, and one of them is from Uber. And this is because Uber uses Kafka extensively for a lot of their applications and their data. They have an interesting approach to how to make this stuff work in the enterprise, where you have one data center and you have applications that use a proxy client, so they use a proxy Kafka interface which then sends those messages across, then from there it goes into a regional Kafka cluster. This is where the chaperone service comes in and it starts to audit everything and find out when messages were timestamped and the order in which they actually occurred. Then from there they go off to a different data center where they’re aggregated up with other regional Kafka message streams. Again, the chaperone service is monitoring what’s happening there, really looking at the timestamps of when things occur. Because remember, one of the toughest parts about the streaming business is keeping all the messages in order so that way the operations that then happen based on the messages don’t fall out of sync. Then from there, from the aggregate Kafka cluster, it goes to the chaperone collector which is logged to a database on top of which is a web service that can do things like have websites showing you the health of the cluster and how the auditing and monitoring is going. So, Uber open-sourced this and you can look it up, it’s called Uber Chaperone. It’s a really interesting architecture and design, as well as some tools that may help you audit your Kafka cluster. The third one to mention is from a company called Confluent, and Confluent is sort of like a version of Kafka that has been made open-source as well, but with some commercial components, some added services that you can buy. And they have something called a control center, and this is essentially a series of charts and graphs and dashboards that allow you to monitor the health and the sustainability and durability and everything of your Kafka cluster. So, this is at confluent.io and you can check that out there. Now this company was founded by Jay Kreps,who was the guy at LinkedIn that originally created Kafka, so they definitely know what they’re talking about, and they definitely are advancing Kafkabeyond the Apache project itself. So, definitely something to consider and look at, especially if you’re an enterprise that needs something like training and support when you want to consider going down this route.</p><h3><strong>Installation and Startup</strong></h3><pre>$ brew install kakfa<br>$ brew install zookeeper<br>$ bin/zkServer start<br>$ bin/kafka-server-start /usr/local/etc/server.properties</pre><p><strong>Creating topics</strong></p><pre># Run built-in script to create new topic named &quot;test&quot; with 1 partition on 1 node</pre><pre>&gt; bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test</pre><pre># See the topic<br>&gt; bin/kafka-topics.sh --list --zookeeper localhost:2181</pre><p><strong>Sending and Receiving Messages</strong></p><pre># Run the producer in terminal and enter some messages<br>&gt; bin/kafka-console-producer.sh — broker-list localhost:9092 — topic test<br>message 1<br>message 2<br>message 3</pre><pre># In a new terminal window read the messages<br>&gt; bin/kafka-console-consumer.sh — bootstrap-server localhost:9092 — topic test — from-beginning<br>message 1<br>message 2<br>message 3</pre><p><strong>Setting up a Multi-Broker Cluster</strong></p><pre># Create config files for each new broker<br># use &#39;copy&#39; on Windows<br>&gt; cp config/server.properties config/server-1.properties<br>&gt; cp config/server.properties config/server-2.properties</pre><pre># Update the following properties in the new files<br>config/server-1.properties:<br>    broker.id=1<br>    listeners=PLAINTEXT://:9093<br>    log.dir=/tmp/kafka-logs-1</pre><pre>config/server-2.properties:<br>    broker.id=2<br>    listeners=PLAINTEXT://:9094<br>    log.dir=/tmp/kafka-logs-2</pre><pre># Start the two new nodes in separate termial windows<br># You should already have Zookeeper running<br>&gt; bin/kafka-server-start.sh config/server-1.properties &amp;<br>...<br>&gt; bin/kafka-server-start.sh config/server-2.properties &amp;<br>...</pre><pre># Create new topic replicated to all 3 nodes<br>&gt; bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 --partitions 1 --topic my-replicated-topic</pre><pre># See stats about our new topic<br>&gt; bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic<br>Topic:my-replicated-topic PartitionCount:1 ReplicationFactor:3 Configs:<br> Topic: my-replicated-topic Partition: 0 Leader: 1 Replicas: 1,2,0 Isr: 1,2,0</pre><pre># Compare this to our &#39;test&#39; topic<br>&gt; bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test<br>Topic:test PartitionCount:1 ReplicationFactor:1 Configs:<br> Topic: test Partition: 0 Leader: 0 Replicas: 0 Isr: 0</pre><p>Testing Fault Tolerance</p><pre># Send some messages to our replicated topic, then kill the producer<br>&gt; bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my-replicated-topic<br>...<br>my test message 1<br>my test message 2<br>^C</pre><pre># Read messages from topic<br>&gt; bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --from-beginning --topic my-replicated-topic<br>...<br>my test message 1<br>my test message 2<br>^C</pre><pre># Now kill Broker 1<br>&gt; ps aux | grep server-1.properties<br>7564 ttys002    0:15.91 /System/Library/Frameworks/JavaVM.framework/Versions/1.8/Home/bin/java...<br>&gt; kill -9 7564</pre><pre># Check which node is the leader for our topic now<br>&gt; bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic</pre><pre># Try reading the messages again<br>&gt; bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --from-beginning --topic my-replicated-topic<br>...<br>my test message 1<br>my test message 2<br>^C</pre><p>Major Vendors include cloudera, Hortonworks and Confluent. Another alternative is to use AWS Kinesis. Confluent is very high on recommendation list as its enterprise level and was started by the creators of Kafka.</p><p>I hope this introduction is useful and benefitial to you. I gathered most of this information from Ben Sullin’s Course on LinkedIn Learning. Please check out the training in the below link. It would be more useful and practical to follow the training.</p><p><a href="https://www.linkedin.com/learning/kafka-essential-training">Kafka Essential Training</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952cab07d945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Essentials]]></title>
            <link>https://medium.com/@david.joy1588/spark-essentials-33c0ab7509c6?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/33c0ab7509c6</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 21:44:18 GMT</pubDate>
            <atom:updated>2019-03-20T06:45:17.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Spark is a fast and general engine for large-scale data processing. It really was designed more specifically for data science, but has evolved to support even more use cases and including real-time stream event processing. There are four main reasons to use Spark: speed, ease of use, generality, and platform agnostic.</p><p>You can run Spark on top of Hadoop and all kinds of other platforms so we’ll take a look at that here in a second. Spark has an advanced Dag engine that can achieve up to a hundred times faster processing than traditional MapReduce jobs on Hadoop. This is largely due to how Spark distributes the <strong>execution across it’s cluster</strong> and performs many of its <strong>operations in memory.</strong></p><p>First, we have Spark Core, and this is the main component from which all the others are based. This is the foundation of the house, if we are thinking of a framework as a house. Now Spark Core includes task distribution, scheduling, and the input/output operations. So when we execute something in Spark, whether it be SQL, machine learning, a graph, or any of the other components,we essentially are using that one plus Spark Core to actually do and execute the functions that we’re calling.</p><p>Now Spark Streaming is the component that enables our jobs to process new data as it comes in. To be specific, Spark Streaming runs micro batches, which operate just like normal batch operations, just much more frequently on smaller datasets. This provides a streaming result to our user, although it isn’t true stream processing, like some of the other ways that people accomplish the same feat. This works using an Lambda architecture,in case you’re not familiar with that. And I only mention it because you’ll hear people talk about it a lot, but basically it’s a method of taking historical data to start and then as new data comes in you start aggregating that number, that count, the metric, or whatever it is that you’re looking to actually show to your user.</p><ol><li><strong>Read file and Files from from Directory</strong></li></ol><pre>logData = sc.textFile(logFile).cache() </pre><pre># cache to put in memory<br># textFile to read the file in location and make an RDD</pre><pre>files = sc.wholeTextFiles(path) <br># wholeTextFiles to read files from a path</pre><p><strong>2. Convert to DataFrame ( SparkDataframe)</strong></p><pre>filenames = files.toDF([&#39;name&#39;, &#39;data&#39;]) <br># This converts the data to spark data frame. </pre><pre>displat(filenames.select(&#39;name&#39;))<br># selects only column &#39;name&#39; from the data frame. </pre><p><strong>3. Work with CSV in Sparks</strong></p><pre># load as text<br>data = spark.read.csv(path)</pre><pre># read in file using csv format<br>df = spark.read.load(path,<br>                    format=&#39;com.databricks.spark.csv&#39;, <br>                    header=&#39;true&#39;,<br>                    inferSchema=&#39;true&#39;)</pre><pre>df.printSchema() # to get info of the data</pre><pre>df.select(&#39;Country&#39;).show() # to just see 1 column <br>df.select(&#39;Country&#39;).distinct().show() # to see distinct Countries<br>r1 = df.select(&#39;Country&#39;).distinct().orderby().show() # to get in order</pre><pre>r1.write.saveAsTable(&quot;product_sales_by_country&quot;) # to save the Table in spark </pre><p><strong>4. Spark SQL and its functions</strong></p><pre>CREATE TABLE  IF NOT EXISTS population_v_price<br>USING CSV<br>OPTIONS (path &quot;/databricks-datasets/samples/population-vs-price/data_geo.csv&quot;, header &quot;true&quot;, inferSchema &quot;true&quot;);</pre><pre>/* check results */<br>select * from population_v_price limit 100;</pre><p>We can do pretty much most of the ANSI SQL on Spark SQL.</p><p><strong>5. Machine learning with Spark</strong></p><pre># convenience for specifying schema<br>from pyspark.mllib.regression import LabeledPoint<br> <br>data = results.select(&quot;OrderMonthYear&quot;, &quot;SaleAmount&quot;)\<br>  .map(lambda r: LabeledPoint(r[1], [r[0]]))\<br>  .toDF()<br>  <br>display(data)</pre><pre># Import LinearRegression class<br>from pyspark.ml.regression import LinearRegression<br> <br># Define LinearRegression algorithm<br>lr = LinearRegression()<br> <br># Fit 2 models, using different regularization parameters<br>modelA = lr.fit(data, {lr.regParam:0.0})<br>modelB = lr.fit(data, {lr.regParam:100.0})</pre><pre># Make predictions<br>predictionsA = modelA.transform(data)<br>predictionsB = modelB.transform(data)</pre><pre>display(predictionsA)</pre><pre>from pyspark.ml.evaluation import RegressionEvaluator<br>evaluator = RegressionEvaluator(metricName=&quot;rmse&quot;)</pre><pre>RMSE = evaluator.evaluate(predictionsA)<br>print(&quot;ModelA: Root Mean Squared Error = &quot; + str(RMSE))</pre><pre>RMSE = evaluator.evaluate(predictionsB)<br>print(&quot;ModelB: Root Mean Squared Error = &quot; + str(RMSE))</pre><p><strong>6. Spark Streaming</strong></p><p>Spark uses Micro Batching , this is a method that Spark uses of achieving real-time data processing by chunking operations into really, really small batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fHAt9dNFh_S0O1j5cl4xQ.png" /><figcaption>Micro batching in spark</figcaption></figure><p>There are two components here that are particularly key for us, that is setting up the streaming context and then executing those jobsusing Spark MLlib or Spark SQL.</p><pre>from pyspark.sql.functions import *</pre><pre># Similar to definition of staticInputDF above, just using `readStream` instead of `read`<br>streamingInputDF = (<br>  spark<br>    .readStream                       <br>    .schema(salesSchema)              # Set the schema for our feed<br>    .option(&quot;maxFilesPerTrigger&quot;, 1)  # Treat a sequence of files as a stream by picking one file at a time<br>    .csv(path)<br>)</pre><pre># Same query as staticInputDF<br>streamingCountsDF = (                 <br>  streamingInputDF<br>    .select(&quot;ProductKey&quot;, &quot;SaleAmount&quot;)<br>    .groupBy(&quot;ProductKey&quot;)<br>    .sum()<br>)</pre><pre># Is this DF actually a streaming DF?<br>streamingCountsDF.isStreaming</pre><h3>Hope this helps !</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33c0ab7509c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Interview Prep]]></title>
            <link>https://medium.com/@david.joy1588/data-science-interview-prep-cf32c03f5780?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf32c03f5780</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Mon, 11 Feb 2019 07:10:39 GMT</pubDate>
            <atom:updated>2019-04-30T18:41:46.311Z</atom:updated>
            <content:encoded><![CDATA[<p>Level 0 — SQL and Python/R for Analytics</p><p>Need to knows — Group by , order, Joins — Left, right, inner, outer, cross</p><p>Rank over (order by ) , Partition by</p><p>union — all column names in both the tables should be same !!</p><p>Case when X = ‘Something’ then something else something end as something</p><p><strong>Python — loading in pandas</strong></p><p>Df.describe()</p><p>df[‘something’].count(),sort_values(),max(),min(),mean(),std(),groupie()</p><p>df.isnull().sum() or df.isna().sum()</p><p>df.columns() — Provides column names</p><p>df[‘Age’].hist() #creates historgram</p><p>pd.concat , pd.merge .. df.join(another dataframe)</p><p>The difference between concat and merge is that .. concat joins or appends dataframe across axis by column or row , axis = 0 or 1</p><p>0 is along the column, 1 is along the row whereas, Merge is the equivalent of join from SQL with how=’inner’ or ‘outer’ or ‘right’ .. on a particular column.</p><p>we can also do dataframe.join(anotherdataframe, inner=Join)</p><p><strong>#Parsing Logs</strong></p><p>Regular Expression : import re</p><p>re.search(“abc”,string)</p><p>re.finditer(“abc”,string) gives a list with span info</p><p>pattern = r’\d\d\d-\d\d\d-\d\d\d\d’</p><p>re.search(r’\d\d\d-\d\d\d-\d\d\d\d’,a)</p><p>re.match(pattern=pattern,string=a)<br>itr = re.finditer(pattern=pattern,string=a)<br>for i in itr:<br> print(i)</p><p>pattern = re.compile(r’\d\d\d-\d\d\d-\d\d\d\d’)<br>rm = pattern.finditer(a)<br>for a in rm:<br> print(a)</p><p><strong>Level 1 — Basic Regression</strong></p><ul><li>Linear Regression , Logistic Regression in python or R.</li><li>if using python then which packages to use — statsmodel.api, from sklearn import linear_model</li><li>linear_model consists of LinearRegression,LogisticRegression, call each package seperately and then fit Training values.</li><li>Results of fiting → with statsmodel.api — ols we get a table with coefficients and p values of significance. We can evaluate R2 and adjusted R2 with AIC and BIC. With the sklearn package we can get R2 and other values.</li></ul><p><strong>Level 2 — Evaluation Metrix</strong></p><ul><li>basic Cross Validation Score -&gt; Basically splitting the dataset into multiple split’s and running through the model to get scores for each split. ( works with both linear and logistic regression )</li><li>Cross Val with KFold → Same thing as above works with linear and logsitic regression.</li><li>Cross Val with Stratified KFold → Works with logistic regression.</li><li>Confusion matrix — Provides TP and TN , FP and FN in the form of a matrix of different classes can work with both binary and multi class.</li><li>Classification Table → provides precision and recall score.</li><li>Mean absolute error , scored error and Root Mean scored error for regression based model such as linearR, ridge regression, lasso etc.</li></ul><p><strong>Level 3 — Models to Handle Multicollinearity</strong></p><ul><li>Lasso and Ridge</li><li>Dimension Reduction — PCA</li></ul><p>Reference : <a href="https://medium.com/datadriveninvestor/l1-l2-regularization-7f1b4fe948f2">https://medium.com/datadriveninvestor/l1-l2-regularization-7f1b4fe948f2</a></p><p><strong>Level 4 — More advanced models</strong></p><ul><li><strong>Naive Bayes</strong></li><li><strong>SVM</strong></li><li><strong>RandomForest : </strong>is an ensemble based model available in the sklearn.ensemble. A Random Forest algorithm is a ensemble of various decision tree and its predictors. Once all the trees and predictors are calculated , the algorithm does voting to for final predictor. The key advantages are no overfitting and we can figure out key features. Although, its slower and are difficult to interpret.</li><li><strong>Bagging Classifier : </strong>This is basically Bootstrapping and Aggregating. The basic fundamental is to use subsamples across for a particular base class model. The difference with RandomForest is that it’s base is a decision tree whereas with Bagging we can use any estimator as a base class and can use sub samples for the same. We can run various Classifier’s in this fashion. It can either be a base class model or Bagging based classifier or RandomforestClassfier. However, how do we determine which classifer to eventually choose. We can do that by using a VotingClassifier. Voting is done in a hard or soft voting.</li><li><strong>Voting Classifier : </strong>Hard Voting — lets suppose we have 3 models and for one record, 2 models predict class 1 and 3rd model predicts class 0. With hard voting the class choses for this record would be 1. However, with Soft Voting we compute a percentage weight with each classifier. Weights are difficult to find in reality. To counter this we can use a linear optimization equation or neural net.</li><li><strong>Boosting : </strong>The overall idea of boosting is to add additional models to the overall ensemble model sequentially. With bagging, we averaged each individual model created. This time with each iteration of boosting, a new model is created and the new base-learner model is trained (updated) from the errors of the previous learners.The algorithm creates multiple weak models whose output is added together to get an overall prediction.</li><li><strong>Parameter Tuning</strong></li><li><strong>Regularization → </strong>L1 and L2 regularization — Ridge and Lasso are examples. Ridge makes B square and Lambda as penalty while Lasso does Absolute B and lambda penalty. It further benefits the model by making some beta values close to 0 or 0 in this make also doing feature selection.</li></ul><p><strong>Level 5 — Need for normalization</strong></p><p>Standardization → mean 0 and variance 1</p><p>Normalization → -1 to 1 or some scale.</p><p>It is done to optimize the models as well as improve performance. PCA,SVM with rbf kernal expect the data to be normalized.</p><p>Level 6 — <strong>Time Series analysis</strong></p><p>Moving Average — Basically average of the last n timeperiod is the next value. Example : Average of last 4 period or 5 period or last 6 periods etc.</p><p>Moving average is a good method to identify Trends and seasonality as well. We can also determine confidence internvals and try to detect analmoies.</p><p>Weighted Average — Basically weighted average based on weights provided for periods.</p><p>Example : weights [ .6,.3,.1] for recent 3 time periods.</p><p>Exponential Smoothing — Instead of weighting the last n values of the time series, we start weighting all available observations while exponentially decreasing the weights as we move further back in time.</p><p>Stationarity — Constant Mean and Variance and no autocorrelation between different points in the timeperiod.</p><p>We test Stationarity with the dickey fuler test — H0 — TS is non stationary. To make a time series stationary we can do differencing, remove trends and seasonality , try box cox</p><p><strong>Level 7— Deep Learning and other topics</strong></p><p>Data set : 1M or more : then training set 99% or 98%, dev set : .5% or 1% and Test set : .5 or 1%</p><p>Bias/Variance Tradeoff : Underfitting — High bias , Overfitting : High var.</p><p>Reference : <a href="https://towardsdatascience.com/understanding-the-bias-variance-tradeoff-165e6942b229">https://towardsdatascience.com/understanding-the-bias-variance-tradeoff-165e6942b229</a></p><p>Remember : Bias is to do with Training set and Varience is to do with Test set.</p><p>The best model to pick is one where dev set or training set error is close to the test set.</p><p>If there is high Bias or high error in Training : Then we can train a larger network or train longer.</p><p>If the high Varience or High dev set error : Then get more data for training or regularization.</p><p><strong>Regularization in Neural Network :</strong></p><p>It helps with reducing overfitting.</p><p>Data augmentation : Cheap way to regularize and reduce overfitting.</p><p>Early Stopping : Stopping when the training set and dev set error comes very close to each other.</p><p>L2 and L1 regularization : Making weight matrixes to be close to 0 which in a way handles or simplies the neural network.</p><p>Dropout Regularization : Basically make some of the hidden layer nuerons as 0. so during forward propagation the effect of some hidden units is not included.</p><p><strong>Normalization in Machine Learning :</strong></p><p>It is easier to optimize the cost function as by normalizing we are stretching the Parameter values [W] generated using cost function to a more deeper bowl and hence it will be easier to optimize. At the same time W1 for X1:0–1000 will be different from W2 for X2:0–1. So its easier as the W’s will be scaled properly.</p><p><strong>Vanishing Gradient Problem :</strong></p><p>Gradient Descent and Cost Function Basically</p><p>Computer Vision — CNN</p><p>NLP — NLTK Library</p><p>Sequence Model — RNN</p><p><strong><em>Note : Classification Algorithms</em> → </strong>Linear classifiers. Logistic regression. Naive Bayes classifier. Fisher’s linear discriminant, Support vector machines. Least squares support vector machines, Kernel estimation. k-nearest neighbor,Decision trees. Random forests , Neural Networks</p><p><a href="https://machinelearningmastery.com/metrics-evaluate-machine-learning-algorithms-python/">Metrics To Evaluate Machine Learning Algorithms in Python - Machine Learning Mastery</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf32c03f5780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Cloud Platform(GCP) for Data Scientist and Introduction to Big Query —Part 1]]></title>
            <link>https://medium.com/@david.joy1588/google-cloud-platform-gcp-for-data-scientist-and-introduction-to-big-query-part-1-4f04022ea1e9?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f04022ea1e9</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Mon, 21 Jan 2019 23:18:58 GMT</pubDate>
            <atom:updated>2019-01-21T23:18:58.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Ie1xfpPGkGKn8W3im8lr7g.png" /></figure><p>The Google cloud Platform aka GCP is a suite of cloud computing services. It provides IAAS,PAAS and Serverless computing enviroments. As ML and data science become a more integral part of Business today, companies are using Cloud based environments due to its scalability , performance and ease of use. With solutions ranging from AWS to GCP to Mircosoft Azure. Their are many solutions in each of these platforms.</p><p>As I continue to learn and grow my skills as a Data scientist I find its essential to explore the GCP BigQuery which is a data warehouse engine that makes life easier due to its usability and scalability. As a data scientist we work with data everyday, mostly doing data analytics or run complex ML models on the data we access from databases or warehouses. We end up mostling doing a lot read activities than write activites. The GCP BigQuery Platform is expected to be used as a write once and read many times database. However, before go deeper into it lets have a look at the other solutions on the GCP Platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeZOEbgHje2QWyMWb3IB7A.png" /><figcaption><strong>GCP Products and its comparison to other products</strong></figcaption></figure><h3>BigQuery Introduction and Key Ideas</h3><h4><strong><em>Projects and Datasets</em></strong></h4><p>GCP Projects define the parent container inside which all data resides in BigQuery. Different projects can have different BigQuery instances. Access is controlled individually or through project-level controls. Next comes the BigQuery dataset.</p><p>A BigQuery dataset is similar to the concept of databases in other RDBMS. Datasets govern the geographical location of data within the particular dataset. Locations supported include US, Europe, and Asia.Tables created within a dataset in one location cannot be joined with tables in other locations. Datasets also provide logical grouping of information similar to databases.</p><p>We can create different datasets for different applications like inventory, finance, etc , or for different purposes like development, QA, and production. Datasets contain table which in turn, store all the data.</p><p><strong><em>All tables used in a query should be from datasets within the same location.This limitation should be kept in mind while designing datasets and tables.</em></strong></p><p><strong>Loading into Big Query from GCP Storage :</strong></p><p>Can be done using the various Big Query Interfaces which include</p><ul><li>WebUI</li><li>Google Cloud Shell</li><li>REST API</li><li>Programming SDK’s in C#,Go, Java, Node.js,Python,Ruby,PHP — which allow insert, update and delete and run queries using the REST API Calls.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYfyucBmfiQORaasd5tCLg.png" /><figcaption>Web UI for BigQuery</figcaption></figure><p>Loading can be done by using a file upload feature from the system or from other cloud sources.</p><h4>Directly into the Database using GCP Cloud Shell using the code as below.</h4><pre><em>bq — location=US load — source_format=CSV — autodetect PatientData.normal_ranges gs://exercise-dj/normal_ranges.csv</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJ_XVRgDI82Tnp_q2L2qHw.png" /><figcaption>Compose Query opens the Query building section</figcaption></figure><p>One can use queries such as below in the New Query section to get the data.</p><pre>select name,substr(name, strpos(name,” “)) as last_name from `PatientData.patient_details` where STARTS_WITH(name, “Ben”)</pre><pre>select name,regexp_extract(name, r” .*”) as lastname,regexp_replace(name, r” “, “_”) as replacedname<br>from `PatientData.patient_details` where starts_with(name,”Ben”)</pre><pre>SELECT p1.patient_id, p1.name, p2.blood_sugar, p2.CHOLESTEROL,<br> p2.Blood_Pressure, p2.heart_rate<br>FROM `PatientData.patient_details` p1 INNER JOIN  `PatientData.test_results` p2 ON p1.patient_id=p2.patient_id <br>where p1.exercise_days=0</pre><pre>update `PatientData.normal_ranges` <br>set min=75<br>where measure=’BLOOD_SUGAR’</pre><pre>delete from `PatientData.normal_ranges` <br>where measure=&#39;HEART_RATE&#39;</pre><p>Note: Some of the features in BigQuery are only available with Standard SQL instead of Legacy SQL, Thus make sure to uncheck Legacy SQL when running a query in order to avoid errors.</p><h4><strong><em>Partitioning Tables</em></strong></h4><p>BigQuery allows partitions of data based on either time of ingestion or an explicit date or timestamp column. When a partition is created based on the ingestion time, BigQuery creates two pseudo columns called _<em>partitiondate</em> and <em>_partitiontime</em>. These columns can be further used in queries.</p><p>When partitioning is done based on an explicit column of date or time that exists in the table no pseudo columns are made. The partition is done on columns data and this improves the performance of the BigQuery as it focuses on lesser number of rows. It is recommended to use partitioning when using transaction based tables.</p><pre>select * from `PatientData.test_results_partitioned` where TEST_DATE=&quot;2018-06-18&quot;</pre><h4><strong>External Storage</strong></h4><p>Google BigQuery allows users to query data directly from other Google Cloud data sources, like Cloud storage or Bigtable. You can create a table that references an external source. No data is stored inside BigQuery. Rather, every time the data is queried, the query is executed against the external data source under results provider. This saves on storage costs but has an impact of performance on these queries.</p><p><strong>Saving as View</strong></p><p>We can also save the result of query as view using the the save view button on the query page.</p><pre>select p1.patient_id,p1.gender,p1.age,p1.drink,p1.smoke,<br>p2.blood_sugar,p2.cholesterol from [PatientData.patient_details] p1 inner join [PatientData.test_results] p2 on p1.patient_id=p2.patient_id</pre><p><strong>Labels In BigQuery</strong></p><p>When a BigQuery repository is used by multiple individuals and teams, and they end up creating too many data sets and tables, it becomes difficult to track why they are created and of what purpose.Sometimes it is important to group these resources for billing or other purposes. You can do the same by creating labels. Labels are name value paths that can be used to attach a piece of metadata to a resource like a data set, a table, or a view.</p><h4><strong>To Update the label run the below in GCP Cloud Shell</strong></h4><pre>bq update --set_label department:hospital PatientData<br>Dataset &#39;broken-window-XXXXX:PatientData&#39; successfully updated.</pre><h4><strong>To see the label type the below in GCP Cloud Shell</strong></h4><pre>bq show --format=pretty broken-window-XXXXX:PatientData</pre><h4><strong>To find all datasets in the project with a particular label</strong></h4><pre>bq ls --filter &quot;labels.department:hospital&quot; --project_id broken-window-XXXXX</pre><p><strong>Big Query with Python</strong></p><p>The big query package in python can be used to connect to the big query instance on google cloud and data can then be accessed using Standard SQL.</p><pre># import the google cloud client library<br>from google.cloud import bigquery</pre><pre># Create an instance for the client<br>client = bigquery.Client()</pre><pre>#creating a query job<br>query_job = client.query(&quot;&quot;&quot;<br>    SELECT<br>      CONCAT(<br>        &#39;https://stackoverflow.com/questions/&#39;,<br>        CAST(id as STRING)) as url,<br>      view_count<br>    FROM `bigquery-public-data.stackoverflow.posts_questions`<br>    WHERE tags like &#39;%google-bigquery%&#39;<br>    ORDER BY view_count DESC<br>    LIMIT 10&quot;&quot;&quot;)</pre><pre># results in a query<br>results = query_job.result()  # Waits for job to complete.</pre><p><strong>Best Practices in BigQuery</strong></p><p>It is essential to have right table design as design dictates how much would be the cost of using GCP as well as performance of the database and queries. Some of the best practices in BiqQuery are as below.</p><ul><li>Denormalization : This makes queries run faster. As its expected to be read many times and requires less writing, Performance is key. Thus, Denormalization should be used as much as possible.</li><li>Partitioning : using transaction date or data load date. This improves performance and allows to optimize queries reducing compute and cost of using GCP.</li><li>Expiring Tables : remove stray tables or not in use tables. Isolate temporary tables into separate datasets and set expiration times on temporary tables. Partitions can also be expired.</li><li>Compare costs to store : know which product works best for your use case. Choose between native tables vs external tables based on actual usage and performance requirements. If you have data you analyze on once and year store in Cloud storage and when its needs to be analyzed create external table in BigQuery rather than storing in BigQuery as a Native table. Remove after analyzing.</li><li>Speeding up Queries : Denormalize frequently joined tables, avoid self joins, avoid cartesian joins , minimze rows using filtering and use partition. Also, Native bigQuery tables are faster than External tables and thus for frequently queried use Native tables. Use the correct datatypes and avoid casting and conversion.</li><li>Monitoring and Logging : use StackDriver in GCP to monitor query performance and storage. Cloud audit logs also provides audit trail for access and usage along with filter and query features on the audit logs.</li></ul><p>Hope this blog helps and introduces you to BigQuery. Please comment or let me know if you have any query. I will be working on EDA using python and big query in Part 2. Once completed I will link that blog.</p><p>Sources :</p><p>You can use free trial with $300 credit to create a free GCP account with your gmail. Once that is done access BigQuery from BigData section.</p><p><a href="https://cloud.google.com/bigquery/docs/">https://cloud.google.com/bigquery/docs/</a></p><p><a href="https://www.linkedin.com/learning/data-science-on-google-cloud-platform-designing-data-warehouses/why-data-warehouses-are-important">https://www.linkedin.com/learning/data-science-on-google-cloud-platform-designing-data-warehouses/why-data-warehouses-are-important</a> , the training is what I did to learn BigQuery basics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f04022ea1e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Exploration into Churn Modeling — (Part 2)]]></title>
            <link>https://medium.com/@david.joy1588/an-exploration-into-churn-modeling-part-2-8d5eddd17a9f?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d5eddd17a9f</guid>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[modelling]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 08:35:04 GMT</pubDate>
            <atom:updated>2018-11-07T08:35:04.853Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Exploration into Churn Modeling — (Part 2)</h3><p>While my initial goal was to get into Data Science techniques such as Random Forest, Boosting etc during this part of the story, however I quickly realized that there were a number of data exploratory analysis techniques which I needed to conduct before I stepped into the modeling. I must confess this is something that has taken me ages to practice.</p><p>The key to becoming a good data scientist is sometimes not about the number of techniques you know or algorithms or the statistical excellence or knowing complex programming. It can sometimes come down to just understanding the data in front of you well and telling a story to the stakeholders that is digestable and clear. If one gets lost in the complexities of Data science then may be we loose track of what our goal as Data scientist is. Never the less, <strong><em>my point is Understand the data first so as to share a good story</em></strong>. Its like investigative journalism where you first get the facts right before you start your situational experiments.</p><p>We are going to continue using the <a href="https://community.watsonanalytics.com/wp-content/uploads/2015/03/WA_Fn-UseC_-Telco-Customer-Churn.csv?cm_mc_uid=51304980933215218170416&amp;cm_mc_sid_50200000=92178841521817041648&amp;cm_mc_sid_52640000=98592221521817041652">same data set</a> that we used in <a href="https://medium.com/@david.joy1588/an-exploration-into-churn-modelling-part1-311529444c91">part 1</a>. We will focus on some key Data wrangling and exploratory analysis techniques that is useful and essential. We can say it’s something like preprocessing before we get into the actual modeling bit where we predict who or why they may churn? My set of exploratory analysis comes from<a href="http://www.personal.psu.edu/jxb14/M554/articles/Hair%20et%20al%202010%20--%20Chapter%202.pdf"><em> Hair et al. (2013), chapter ‘Examining your data’.</em></a> I read this paper and its a must read. The paper puts in some good tips and steps we can follow for understanding our data. So lets look at few of these step by step.</p><ol><li><strong>Understanding the Data</strong></li></ol><p>Well, its essential to get to understand the data before we do anything. I usually follow the below steps/checks :</p><ul><li>load data as a Dataframe</li><li>Check size of Dataframe to understand rows and columns</li><li>Check missing data across columns</li><li>If missing data then decide to either remove it or decide on the right strategy to impute … <em>Recommendation is if less than 5% data is missing in a column just remove those row records, if more than 75% then just don’t use those columns.</em></li><li>Analyze the predictive column, in our case its <em>‘Churn’</em> Column from our data.</li></ul><p>I checked the data and couldn’t find any missing data in the dataset. I ran some quick checks as above to see the data and quality. The predictive column looks like is a 1/0 so we would be predicting discrete variable. There are many models for predicting discrete variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hugGj8FqWrYrH4q0ma-PLw.png" /><figcaption>Churn Variable analysis using a simple bar chart.</figcaption></figure><p>2. <strong>Exploratory Data Analysis</strong></p><p>There is no single formula for any of this it always depends on the data. However, the key is to understand what is essential. For those who know how to make charts there are endless possibilities but just making charts is useless. <em>Telling a story using the charts/plots is more important.</em></p><p><strong>Lets take a look at some simple examples.</strong></p><p>I began by looking at some key columns that would be essential to understand churn, obviously I want to know when someone churned as well as how much money do I make those who churn vs those who don’t. Essentially what I am trying to do is understand behaviour of those who churn vs those who don’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*QfF7RVuYg6e7608JJ44tHA.png" /><figcaption>fig 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*XzuNLbzrGbQiFnclYzFppQ.png" /><figcaption>fig 2</figcaption></figure><p>Fig 1 helps visualize that almost as many folks churn in the first 6 months, its pretty much the same as the others who churn after 6 months. Fig 2 simply shows that that people with lower than $40 monthly charge have low churns, however, its not too different from the other groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*-sJsPbRKjQvLB937O2DodQ.png" /><figcaption>Percentage breakdown of Churn vs Non Churn, about 25% Churn across 5 years.</figcaption></figure><p>If we look at the below chart we see that churn rate is high amongst consumers with month to month contract. Low for both one year or two year contracts which is good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*is9JI6IuP-yxCQ7Dkcocrw.png" /><figcaption>Contract Type vs Churn</figcaption></figure><p>Well, Stakeholders would love to know what can be done here. There can be conversations about <em>“what can be done for the customers so that they move to a longer contract ?”</em> etc</p><p>Just for fun, I also tried to figure out if there was a difference in how different genders churned. The below chart shows the same, and thankfully seems like churn is kinda similar for both gender type. So I save myself an ANOVA for now. There are other variables too which we can check for churn. You can find that in <a href="https://github.com/david7joy/ChurnModelling/blob/master/Churn%20Modelling%20Part%202.ipynb">code.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*ZPy--5v5vbHD5NbIF_4NxQ.png" /></figure><p>I also wanted to check how do the distribution looks for both churned customers and non churned customers for various tenure groups. So , the <strong>histogram</strong> steps in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yU3pktQ9PNRZnOhPcjTmNg.png" /></figure><p>Again, it points to the same insight that we found before, that many customers leave early on and also many are taking a low tenure product. We also saw month -to -month contracts have higher churn. You see how we are connecting the dots here.</p><p>ok.I will stop with the charts here, no more charts ! What we have understood so far from our data exploratory analysis is :</p><ul><li>Most churn happens in the first 6 months</li><li>There is no difference in churn between Men or Women.</li><li>Those with a month-to-month contract churn a lot , like really lot.</li><li>Those with low monthly charge seem to stick around more than those with a higher monthly charge.</li><li>etc.. etc ..</li></ul><p><strong><em>Key Point 1 : We can make hundreds of chart, however, its essentially to build and use important charts for telling your story.</em></strong></p><p><strong><em>Key Point 2: Come with some key insights from the exploratory analysis and keep a note of it as you progress.</em></strong></p><p>3. <strong>Checking correlations and important factors</strong></p><p>Since our data has a lot of categorical variables, I first created dummy variables for the same and then did a simple correlation matrix to understand if there is any correlation between various variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKu1glRj6CtRqOAnETzwaw.png" /></figure><p>This corr plot didn’t really provide me any good insights. I just added it because its step I always do. We will look at other ways to figure which variables look important when the time comes in part 3.</p><p><strong>Note : Correlation is not causation. :)</strong></p><p>You can find the code <a href="https://github.com/david7joy/ChurnModelling/blob/master/Churn%20Modelling%20Part%202.ipynb">here</a> for this notebook. I created some of the charts using plotly however, I was using the free account and the limit on my charts is 25 so you may not be able to see the charts in the code , however you can copy the code and look at it on your own.</p><p>Alright so these are some essential steps before we step into part 3 which is creating various models to predict churn.</p><p>Also there are other techniques too which we can try such as ANOVA, PCA for reduction , feature engineering etc to see if there is any difference in various groups, to reduce dimensions and to handle multicollinearity and to figure out key variables, however, I am leaving it for now. I will do a seperate article for those techniques.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d5eddd17a9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Exploration into Churn Modelling (Part1)]]></title>
            <link>https://medium.com/@david.joy1588/an-exploration-into-churn-modelling-part1-311529444c91?source=rss-321fcac8b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/311529444c91</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[David Joy]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 08:27:40 GMT</pubDate>
            <atom:updated>2018-11-01T05:27:44.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Exploration into Churn Modeling (Part1)</h3><p>As a Data scientist , I have been trying to learn new techniques that i could use for different business problems that are out there. “Churn” is one of key KPI’s that many business try to minimize, while at the same time gaining new customers and retaining customers remains priority. This particular “Churn” problem thus becomes essential for any business.</p><p>There many techniques that exist to address this , 2 of the most common and popular ones are Survival Analysis and Machine learning based Techniques. Both these techniques are different and vary in their methodologies in churn modelling. Machine learning techniques do perform better and can handle complexities in data which Survival Analysis cannot. Survival analysis on the other hand is easy to implement and address specific questions such as the time a customer will churn. Having said that I am not saying that one method is better than the other. There is <a href="https://www.kdnuggets.com/2017/03/datascience-building-predictive-churn-model.html">no silver bullet methodology</a> for predicting which customers will churn.It dependent on the type of business, the type of service etc and the questions one as a Data Scientist is trying to solve.</p><p>I will be exploring both Survival analysis and Machine learning techniques using python and will use the IBM Watson Telco Data set that has been so generously provided.</p><h4>Survival Analysis</h4><p>This is generally defined as methods for analyzing data where the outcome variable is the time until the occurrence of an event of interest or it tries to predict time-to-event. The event can be death, occurrence of a disease, marriage, divorce, etc basically <em>“an event of interest”.</em></p><p>The advantages of Survival analysis is that it :</p><p>•Models <strong>time to failure or event</strong></p><p>•Is able to account for <strong>censoring ( right, left or between)</strong></p><p>• <strong>Compares survival </strong>between 2+ groups,segments or achetypes</p><ul><li>Assess <strong>relationship between covariates and survival time</strong></li></ul><h3>Kaplan-Meier Method</h3><p>This works well for small data sets. Since we are using python, we can use Cam Davidson-Pilon’s <a href="https://github.com/CamDavidsonPilon/lifelines">lifelines</a> library to get started.This will help us estimate the<em> ‘Survival function, S(t) that defines the probability of surviving longer than time t’ .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKRSdXpfbbPPfu3HCmYYJA.png" /><figcaption>Customers with one phone line have a steeper survival curve, orange line is one phone line while blue is multiple lines.</figcaption></figure><p>We can observe that approx 25% customers churn by 23 weeks who have single phone line whereas it takes 43 weeks for multiple phone line customers to churn. Thats pretty much an 18 weeks of revenue difference. The plot essentially provides the survival function across the timeline/tenure. Check the code on my github <a href="https://github.com/david7joy/ChurnModelling">link</a>.</p><p>For rigorous testing of differences, lifelines comes with a statistics library. The logrank_testfunction compares whether the “death” generation process of the two populations are equal. I calculated the Hazard Ratio and we can understand that the risk of churn for One line Customers is 3.14 times higher than Multiple line Customers.</p><blockquote><em>Note: If your using lets say another tool such as SAS, you can use ‘PROC LIFETEST’ for small data sets or ‘PROC LIFETABLE’ for large data sets. This will help us estimate the ‘Survival function’</em></blockquote><p>Part 2 → work in progress !! It will cover Machine learning techniques for churn modelling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311529444c91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>