<?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 Andrei G on Medium]]></title>
        <description><![CDATA[Stories by Andrei G on Medium]]></description>
        <link>https://medium.com/@andreigalanchuk?source=rss-e340d8809fcd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b0bQZeRAfymhD2rQuHT8uQ@2x.jpeg</url>
            <title>Stories by Andrei G on Medium</title>
            <link>https://medium.com/@andreigalanchuk?source=rss-e340d8809fcd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:28:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreigalanchuk/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[We don’t need more productivity hacks, we need people]]></title>
            <link>https://medium.com/@andreigalanchuk/we-dont-need-more-productivity-hacks-we-need-people-1ec7ee5e82da?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec7ee5e82da</guid>
            <category><![CDATA[success]]></category>
            <category><![CDATA[ideas]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 07:09:58 GMT</pubDate>
            <atom:updated>2021-08-19T07:09:58.810Z</atom:updated>
            <content:encoded><![CDATA[<p>The best motivation comes from the people next to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*TeZLf1tpReP-cWH5XFcDNA.png" /></figure><p>I think we can all relate to the desire of achieving a better life. That’s something that makes us people the same in some way. And we can all agree that achieving a better life is not easy. Getting the degree we want, getting the job we want, starting the business we want, having the social circle we want. The list goes on and it requires a lot of consistent effort to accomplish.</p><p>Achievement will always be a by-product of strategy, discipline, consistency and probably a bit of luck. So it’s no wonder why “top 10 productivity hacks” type content is so popular. We can see it here on medium, we can see it on youtube, instagram etc. It just doesn’t get old. Such hacks certainly have their place. They often help us complete tasks faster and smoother. But will all these hacks and tools around, shouldn’t we all be millionaires with a six pack?</p><p>Achieving goals is much more than productivity. People are not machines that put in a constant input and get a consistent output. We have mood changes, relationship problems, traffic jams, stomachaches, insomnia, anxiety, just to name a few. Obviously, we cannot put in the same amount of effort and dedication on a continuous basis. To top if off, we are living in a very distracting environment that takes away from our discipline, focus and dedication. Scrolling instagram for no good reason, watching too many titktoks, twitter battles that go nowhere, netflix series that are just too captivating. Does it ring a bell?</p><p>Our environments play a much bigger role for what we do than what we give it credit for. Making progress and achieving goals has become much more challenging in an environment full of distractions. And the productivity hacks we read about will often fail to help us. We know we shouldn’t be eating all those chocolates during our diets, yet we do it. We know we shouldn’t skip our workouts so frequently, yet we do it. We know we should call more prospects to sell our product, yet we avoid it. Why?</p><p>I don’t have an answer and I am not trying to get one. Human behavior and decision making is too complex to unravel in a blog post. All I know is that staying consistent in the pursuit of achieving our goals is a big challenge for most of us. And it doesn’t have to do with lack of discipline or work ethic. It has to do with the constant distractions in our way.</p><p>I noticed that talking to someone (usually my sister) about my progress towards certain goals makes me more committed. I get the discipline and dedication that I do not get from the productivity hacks/tools. I believe this has to do with the social factor of connecting with another person and trying to lift each other up, trying to help each other to achieve our goals. In such moments, we feel like we are in the same boat, even though our stories and struggles are different. When we talk to someone, we feel accountable towards that person. It sure doesn’t feel good to tell that person that you are slacking, that you gave up on your pursuit, does it? On the contrary, you are motivated to show up and deliver results because someone else out there is believing in you and wants you to succeed. That accountability in conjunction with sharing our journeys make such conversations so valuable when it comes to pursuing our goals.</p><p>This is my invitation to all the hustlers and dreamers out there. I know you are all giving your best, trying to get that good life. And you will benefit from sharing your story and evolution with someone who can do the same with you. You will have an actual human supporting you, listening to you, keeping you accountable giving you that little boost that we all need. It’s only together that we can push each other until we get to the finish line.</p><p>Thanks for reading! If you want to connect with me, you can do so on <a href="https://www.linkedin.com/in/andreigalanchuk/">Linkedin</a> and <a href="https://www.instagram.com/andrei.galanchuk/">Instagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec7ee5e82da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Am Giving An Education Experience, Not Education]]></title>
            <link>https://medium.com/swlh/i-am-giving-an-education-experience-not-education-8c06b9f9f073?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c06b9f9f073</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[teaching]]></category>
            <category><![CDATA[innovation]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 16:57:27 GMT</pubDate>
            <atom:updated>2019-10-21T16:57:27.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Sk-rWNmEh03fo6_cvDBUg.jpeg" /></figure><p>The views about the current education needs from a current teacher.</p><p>For the past five years I have worked as a teacher. I found this passion at the ripe age of 21 and never looked back. I started teaching private lessons during my university years and then I started working as an IB Teacher of Math and Economics at the International School Of Bucharest. I have been teaching hundreds of students so far, for thousands of hours. I believe I can pronounce my opinion regarding the education needs and inefficiencies that I witness on a daily basis.</p><p>For the sake of keeping a direction of my post, I will discuss only the marketplace of school education, i.e. K-12. <strong>The reason for the title of my post “I am giving an education experience, not education” is that the lessons I create and the interactions I build with my students are based on this philosophy.</strong> I am not in the classroom to give information to students. Google does that better. I am there to make sure the information is consumed within a positive experience. To draw an analogy, think of yourself going to a restaurant you like. You don’t go there to eat your steak only, right? You go there to enjoy the experience of eating that steak in that restaurant. <strong>It is the dining experience that matters, not the dinner itself.</strong></p><p>A similar logic applies to a lesson in a classroom. The lesson itself must be an experience that depends on the energy of the teacher, the clarity of the content, the good vibes in the room and the practice that everyone gets to do. This is far more than just telling them what to study. And it is far harder too. I have been amazed by how much students are willing to work when the environment in the classroom is full of positive energy. <strong>I personally aim to make every student of mine happy.</strong> I want them to succeed while being happy and developing themselves as human beings. I do not want them to suffer from stress. I do not want them to have depression because of school. <strong>I believe real progress can only happen with passion and good energy.</strong></p><p>There is a huge misconception within the education sector that students only care about a high GPA. That they only need to graduate and then they can take care of their lives. I couldn’t disagree more. Students are developing themselves during the school years. <strong>They are craving to see passion and find their own passions. </strong>They want to see applications in the real world of the things they learn. They want to see enthusiasm. They want to enjoy their time at school. Learning should never be a chore. <strong>If students are missing excitement, then the teacher should wonder why.</strong></p><p>I am writing this message to invite other teachers to consider their approach to teaching. <strong>I am writing this message for other teachers to prioritize students’ happiness, not just their grades.</strong> I truly believe that one of the most important professions in the world is that of a teacher. A teacher has the capacity to shape students and build the future generation. Build the future engineers, doctors, entrepreneurs and change makers. Creating an education experience that students look forward to should be the aim of every teacher. Making sure that students say “thank you” after the lesson should be the aim of every teacher. I personally thank all my students for the effort they put in the lesson. And believe you me, they like being appreciated like that. <strong>Believe you me, that they reward me back with engagement and hard work in the room.</strong></p><p>I appreciate you for reading this. My name is Andrei Galanchuk and I want to improve the education experience of every student in the world. If you would like to get in touch with me, we can connect on <a href="https://www.linkedin.com/in/andreigalanchuk/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c06b9f9f073" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/i-am-giving-an-education-experience-not-education-8c06b9f9f073">I Am Giving An Education Experience, Not Education</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Attempt Of Entrepreneurship At 22]]></title>
            <link>https://medium.com/swlh/my-first-attempt-of-entrepreneurship-at-22-77e61a777a3c?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e61a777a3c</guid>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 09:12:15 GMT</pubDate>
            <atom:updated>2019-03-27T09:12:15.356Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLq72HiRBDdVXRojZyMBI2nYlU2tQy9SKH&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDmjUQamwSGo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDmjUQamwSGo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/419f5d6a04d63d7b140622d282661872/href">https://medium.com/media/419f5d6a04d63d7b140622d282661872/href</a></iframe><p>I really thought this was going to work. I was 22. And I had a desire to make a good change to the education sector. I believe I had the skills too. But something didn’t click. This is what happened.</p><p>It was September 2016. And I had just started to make Youtube videos. I was making education videos in the Khan Academy style for some courses at my former university. My idea was to provide such content customized to the problems that students are trying to solve. <strong>That means explaining assignment questions and exam questions in video format.</strong> Students can watch that as much as they want, whenever they want. Pretty useful, I would say. And so did the students. Students loved it. And they asked me to do more of it. I made hundreds of videos for quantitative courses at the Erasmus University. Mathematics, statistics, microeconomics, econometrics.</p><p>This is where my business idea appeared. <strong>I would start an education video company that makes customized webcasts to university courses across the world.</strong> We would focus primarily on solving problems, and not theory. And we would do it for quantitative courses only, since they are the hardest. I would spend two months getting in touch with all the universities in Europe. Absolutely all of them. I would have skype calls with directors and project coordinators of economics programs at all these universities.</p><p>“Yes Andrei, I like the idea. Very innovative. You’re definitely on to something.”</p><p>That’s what they said first.</p><p>“We consulted with our professors and we decided not to continue with this. Good luck with your business.”</p><p>That’s what they said second. I’ve been rejected by all the university executives that I contacted. I could not implement what I wanted. I couldn’t believe it. Students liked it so much. It was obviously a great product.</p><p>The problem was the barriers between me and the end-consumers. Universities are businesses. There are many stakeholders involved. Hence, I had to go through all these gatekeepers in order to serve my users, the students. Since this is a type of customized product that I wanted to offer, I could not think of an app that scales, or a business model that does not involve a partnership with universities. And this is where my entrepreneurship pursuit stopped.</p><p>I am glad I did that at 22. I am glad I took myself a couple of months to try to build a company. I am glad I did not go for a corporate job right out of college. This is an experience that I took with me and I know it will serve me when I try my second company. That’s right. My entrepreneurship pursuit is not over. I still believe I can pull it off. To every one reading: if you consider tasting the startup life, taste it. You can get your job later. <strong>Embrace risk and do something our of the ordinary.</strong> It is something that you will look back with pride.</p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +437,678 people.</h4><h4>Subscribe to receive <a href="https://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e61a777a3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/my-first-attempt-of-entrepreneurship-at-22-77e61a777a3c">My First Attempt Of Entrepreneurship At 22</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Studying Data Science Full-Time Next To A Full-Time Job]]></title>
            <link>https://medium.com/swlh/studying-data-science-full-time-next-to-a-full-time-job-27c37f9f5933?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c37f9f5933</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[hustle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 20:17:20 GMT</pubDate>
            <atom:updated>2019-03-25T20:17:20.660Z</atom:updated>
            <content:encoded><![CDATA[<p>This was a little crazy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Zyqk3loV5X-CQdpWR84IPQ.jpeg" /><figcaption>I am writing this from Bucharest, Romania.</figcaption></figure><p>I’ve recently gone through some challenging six months, that involved 70 hour workweeks with pretty much no days off. I would like to share some lessons learned and encourage people that are considering to change careers to do so. It is absolutely possible to develop new skills in your after-work hours. You just need to be properly prepared.</p><p>I am currently an IB Math and Business Teacher and I put around 40 hours per week in my job. That involves creating class work, creating exams and checking them, checking home work and maintaining regular contact with the parents of my students. In the past six months I completed a degree in Data Science offered by the tech education company Udacity. My target is simple: I want to get in the machine learning space, and eventually in the AI space. I had to study around 4 hours per day, 7 days per week. Roughly speaking, my studying took me 30 hours weekly. This was the first time I put so many working hours in a week. This is what I learned.</p><h4>It is super hard.</h4><p>I believe that it is necessary to appreciate the level of sacrifice you have to go through. It was specifically hard for me because I don’t have a technical background. I have a BS Economics and a good math background. However, I had to build my coding from zero. Moreover, when you have to solve and explain math problems all day, your brain does not want numbers again. Well, coding does not make it easier. Hence you must rely on strong will power to push another 4 hours of studying at night after your day job.</p><h4>You will feel like quitting at least once.</h4><p>I know I did. Three months into my program I felt like not going on. I just thought my progress was too slow. However, you must be empathetic to your personal situation. If you have to work, you will obviously be more tired than someone who does not have to work. If you are not a computer scientist, you will obviously need more time to put into your coding. Accept your level and push forward.</p><h4>Enrolling in a paid program matters.</h4><p>I think that paying for your program is essential. The reason is simple. Money puts pressure on us. When you know that you paid money to complete this degree, then you want your money’s worth. I paid $2000 for this program. I did it on purpose. Otherwise, if I did some free online courses, I would not have sacrificed so much to complete them. Plus, I got to build a solid portfolio of projects. Plus, I got a credential of completing the program.</p><h4>Taking a nap before studying matters.</h4><p>This one made a difference. I used to sleep for an hour after work. This way I could reset my mind for what’s coming. Otherwise, I just couldn’t be focused enough. You want quality hours of studying. There is no point to lie to yourself that you are ‘working’ when you’re looking at the clock every 20 minutes. Chill a bit, and then fire.</p><h4>Do not take too many days off.</h4><p>Resting matters. But so does momentum. I am a big believer in creating momentum in anything you do in life. That means starting something and not stopping. I only took a day off when I truly needed it. Only when I felt like my thinking was blocked. That’s normal. Brains get tired too. However, I once slipped and didn’t study for 3 or 4 days straight. That was not good. I had just lost my rhythm. Because these were new skills to me, I had to consistently hone them. And I encourage every beginner in the tech field to stay on your craft without breaks until you get to some level of proficiency.</p><blockquote>Make every minute count.</blockquote><p>If you feel like you’re still not putting in enough hours into your studying, audit your day. Instead of spending the entire hour of lunch break, you can eat for thirty minutes and use the other thirty minutes for yourself. If you’re on youtube for an hour every night, cut it to thirty minutes only. You save the other thirty. By ‘stealing’ time from here and there, you can end up with another 1–2 hours at your disposal.</p><h4>Customize everything I said to your personal situation.</h4><p>I should probably say that the person writing this article is a single 25 year-old guy. Hence I do not have a wife and kids to take care of. However, if you do have a family, then things change. And that is something that is absolutely personal. How many hours can you put after work? How can you balance all of this with your family time? I will not dare to say anything about this because I have not lived it myself. I prefer to speak from experience only.</p><p>Thank you very much for reading. Hope it was worth your time. Stay blessed :)</p><p>P.S. We can connect on <a href="https://www.linkedin.com/in/andreigalanchuk/"><strong>Linkedin</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c37f9f5933" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/studying-data-science-full-time-next-to-a-full-time-job-27c37f9f5933">Studying Data Science Full-Time Next To A Full-Time Job</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doing meaningful work with Machine Learning — Classify Disaster Messages]]></title>
            <link>https://medium.com/data-science/doing-meaningful-work-with-machine-learning-classify-disaster-messages-436bfe9ec42?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/436bfe9ec42</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Thu, 31 Jan 2019 23:07:49 GMT</pubDate>
            <atom:updated>2019-02-04T21:20:37.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Doing meaningful work with Machine Learning — Classify Disaster Messages</h3><h4>Build models to help disaster organizations save people’s lives.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yfs8GpTY8-JaTxScxGY1ZA.jpeg" /><figcaption>I’m writing this post at 1am in Bucharest, Romania.</figcaption></figure><p>Hello there again! Welcome to my fourth piece of content about Machine Learning. I’ve recently done a project that I believe to be socially meaningful. I’ll give a brief overview what this is all about and I’ll dive into the code right after :)</p><blockquote>In this project I apply data engineering skills to create an API (application programming interface) that classifies disaster messages from various sources (Twitter, text messages) into 36 categories. This classification problem is a type of supervised machine learning because the model learns to classify the outcome based on learning from the data given to it. I.e. what is the message related to: water, food, shelter, money etc.? The reason is that when disaster happens, there are millions of messages sent and tweeted to inform about it. However, disasters are taken care of different organizations. Food provision might be offered by a certain organization, while putting down fires would be taken care of a different organization. Hence,the utility of this application would be to categorize these messages into various types so that it can be understood what type of aid is necessary for a specific disaster.</blockquote><h4>Project Structure</h4><p>There are three parts of the project:</p><ol><li><strong>ETL Pipeline</strong><br><em>Extract, transform and load </em>the data. This is concerned with processing the data. Namely I loaded, merged and cleaned the messages and categories dataset. I stored into an SQLite database so that the model can use it in the next step to train.</li><li><strong>ML Pipeline</strong> <br>The <em>machine learning</em> pipeline is concerned with training the model and testing it. The pipeline includes a text processing part because it deals with text sources as mentioned in the beginning. I also used GridSearchCV to tune the model further and save it as a pickle file.</li><li><strong>Flask Web App</strong><br>The run.py process_data and train_classifier are basically the ETL pipeline and ML pipeline included in the terminal work space to make the app work.</li></ol><h4>ETL Pipeline</h4><p>In the first part of the project, my purpose is to extract the data that I need, make the necessary transformations so that I can use it later in my algorithm building. Once I had a look at the two data sets that I need: the categories and messages , I merged the two data sets using the common id.</p><pre><em># merge data sets</em> <br>df = messages.merge(categories, on = [‘id’]) <br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*u7aZC3efnOxV8osLFYHBQg.jpeg" /></figure><p>I then split the categories into separate category columns, and gave each column its separate category name.</p><pre><em># create a dataframe of the 36 individual category columns</em><br>categories = df[&#39;categories&#39;].str.split(&#39;;&#39;, expand = <strong>True</strong>)</pre><pre>row = categories.head(1)</pre><pre>category_colnames = row.applymap(<strong>lambda</strong> x: x[:-2]).iloc[0, :].tolist()</pre><pre><em># rename the columns of `categories`</em><br>categories.columns = category_colnames<br>categories.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*HO87TL9GSQibmluzc5eGow.jpeg" /></figure><p>Because models use numbers as inputs, I converted the category values to just numbers 0 or 1.</p><pre><strong>for</strong> column <strong>in</strong> categories:<br>    <em># set each value to be the last character of the string</em><br>    categories[column] = categories[column].astype(str).str[-1]<br>    <br>    <em># convert column from string to numeric</em><br>    categories[column] = categories[column].astype(int)<br>categories.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*peM1TsIB8SNbUMCbI4CLZA.jpeg" /></figure><p>After transforming the category columns, I made changes to the data frame. I replaced the original category column with the new category columns.</p><pre><em># drop the original categories column from `df`</em><br>df.drop(&#39;categories&#39;, axis = 1, inplace = <strong>True</strong>)</pre><pre><em># concatenate the original dataframe with the new `categories` dataframe</em> df = pd.concat([df, categories], axis = 1) </pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*OM41L2r2EWq7r-fDbEjumw.jpeg" /></figure><p>After checking for duplicates in my data, I got rid of them.</p><pre><em># check number of duplicates</em><br>df[df.duplicated].shape</pre><pre>(170, 40)</pre><pre><em># drop duplicates</em> <br>df.drop_duplicates(inplace = <strong>True</strong>)</pre><pre><em># check number of duplicates</em> <br>df[df.duplicated].count()</pre><p>I finally saved the clean data set into a SQLite database.</p><pre><em># Save the clean dataset into a sqlite database.</em><br>engine = create_engine(&#39;sqlite:///disaster.db&#39;)<br>df.to_sql(&#39;messages_disaster&#39;, engine, index=<strong>False</strong>)</pre><h4>ML Pipeline</h4><p>In the second part of the project I created the machine learning pipeline that was used to classify the disaster messages into different categories. The reason for being called a ‘pipeline’ is because this modeling tool is composed of several steps that processes inputs to generate the outputs. In this case namely, I used <em>tokenization</em> to process text data.</p><pre><em># load data from database</em><br>engine = create_engine(&#39;sqlite:///disaster.db&#39;)<br>df = pd.read_sql_table(&#39;messages_disaster&#39;, con = engine)</pre><pre>X = df[&#39;message&#39;]  <br>Y = df.drop([&#39;message&#39;, &#39;genre&#39;, &#39;id&#39;, &#39;original&#39;], axis = 1)</pre><pre><em># Tokenization function to process text data.</em><br><strong>def</strong> tokenize(text):<br>    tokens = word_tokenize(text)<br>    lemmatizer = WordNetLemmatizer()<br>    clean_tokens = []<br>    <strong>for</strong> tok <strong>in</strong> clean_tokens:<br>        clean_tok = lemmatizer.lemmatize(tok).lower().strip()<br>        clean_tokens.append(clean_tok)<br>    <strong>return</strong> clean_tokens</pre><p>The machine learning pipeline will take the message column as input and output classification on the 36 categories in the data set. This is a problem of <em>Natural Language Processing; </em>i.e. processing text to extract meaning from the message. Isn’t that amazing?</p><pre>pipeline = Pipeline([<br>    (&#39;vect&#39;, CountVectorizer()),<br>    (&#39;tfidf&#39;, TfidfTransformer()),<br>    (&#39;clf&#39;, MultiOutputClassifier(RandomForestClassifier()))<br>])</pre><p>Just like with all other ML models, we must have training and testing sets. The reason is that we do not want our model to do super well on the training set, while not being able to classify our categories properly when it sees new data. Hence we must use only a subset of our data to train it and see how it performs on the testing set.</p><pre><em># Split data into train and test tests.</em><br>X_train, X_test, y_train, y_test = train_test_split(X,Y, test_size = 0.2, random_state = 45)</pre><pre><em># Train the model.</em><br>pipeline.fit(X_train, y_train)</pre><p>When it comes to testing my model, I want to have some objectives measures of performance. Namely I will look at the <em>f1 score</em>, <em>precision and recall.</em></p><pre><em># Test the model and print the classification report for each of the 36 categories.</em><br><strong>def</strong> performance(model, X_test, y_test):<br>    y_pred = model.predict(X_test)<br>    <strong>for</strong> i, col <strong>in</strong> enumerate(y_test):<br>        print(col)<br>        print(classification_report(y_test[col], y_pred[:, i]))</pre><pre>performance(pipeline, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*VSShbmEKL1W9fjzKxErnuw.jpeg" /><figcaption>just a snapshot</figcaption></figure><p>When building models, it’s always a good idea to seek improvement. Try to adjust the parameters of the model to get better results. This is what I am attempting here. It’s the same process, but with a different pipeline.</p><pre><em># Improve the pipeline.</em><br>pipeline2 = Pipeline([<br>    (&#39;vect&#39;, CountVectorizer()),<br>    (&#39;best&#39;, TruncatedSVD()),<br>    (&#39;tfidf&#39;, TfidfTransformer()),<br>    (&#39;clf&#39;, MultiOutputClassifier(AdaBoostClassifier()))<br>])</pre><pre><em># Train the adjusted pipeline.</em> <br>pipeline2.fit(X_train, y_train)</pre><pre># Check the performance of the adjusted model.<br>performance(pipeline2, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*fcMfPIlfyxnrtuX5kbaM4Q.jpeg" /></figure><p>I went one step further and used a different set of parameters with a certain range of values. With the help of <em>GridSearchCV</em>, the model chooses the best parameters.</p><pre>parameters2 = { <br>              &#39;tfidf__use_idf&#39;: (<strong>True</strong>, <strong>False</strong>), <br>              &#39;clf__estimator__n_estimators&#39;: [50, 100],<br>              &#39;clf__estimator__learning_rate&#39;: [1,2] }</pre><pre>cv2 = GridSearchCV(pipeline2, param_grid=parameters2)</pre><pre>cv2.fit(X_train, y_train)</pre><pre>performance(cv2, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*_zTraOfIWJjc9SW33fN0jA.jpeg" /></figure><h4><strong>Build the API</strong></h4><p>Finally I concluded this project with making an API that takes in a disaster message and classifies it into the most likely disaster categories. This way, we can help disaster organizations to understand better what type of catastrophe happened and which sort of aid is necessary.</p><h4><strong>Closing Words</strong></h4><p>If you made it this far, thank you very much for reading! Hope this gives you an idea of how useful machine learning can be. And how wide the range of its applications is. We can literally save lives of people by knowing how to process text data and implement models. And speaking of models, here’s the full project on my <a href="https://github.com/andreigalanciuc/RECOMMENDATION-SYSTEM-WITH-IBM"><strong>github</strong></a>.</p><p>Wish you all the very best and stay blessed :)</p><p><strong>P.S. Let’s connect on</strong><a href="https://www.linkedin.com/in/andreigalanchuk/"><strong> Linkedin</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436bfe9ec42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/doing-meaningful-work-with-machine-learning-classify-disaster-messages-436bfe9ec42">Doing meaningful work with Machine Learning — Classify Disaster Messages</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Unsupervised Machine Learning To Find Potential Buyers of Your Products]]></title>
            <link>https://medium.com/data-science/use-unsupervised-machine-learning-to-find-potential-buyers-of-your-products-cd75edaeefc7?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd75edaeefc7</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Mon, 31 Dec 2018 22:03:33 GMT</pubDate>
            <atom:updated>2022-09-26T16:20:14.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let the algorithm learn by itself…</h4><h4>What Is Unsupervised Machine Learning</h4><p>Welcome to my third post about Data Science! In my previous post I discussed how I used supervised machine learning to find donors for a charity. Recall that in supervised machine learning you have input variables (X) and an output variable (Y ) and you use an algorithm to learn the mapping function from the input to the output. <strong>In contrast, in unsupervised machine learning you only have input data (X) and no corresponding output variables.</strong> The goal for unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data. These are called unsupervised learning because unlike supervised learning above there is no correct answers and there is no teacher. Algorithms are left to their own devises to discover and present the interesting structure in the data.</p><blockquote>Unsupervised learning problems can be further grouped into clustering and association problems. <em>Clustering</em>: A clustering problem is where you want to discover the inherent groupings in the data, such as grouping customers by purchasing behavior. <em>Association</em>: An association rule learning problem is where you want to discover rules that describe large portions of your data, such as people that buy X also tend to buy Y.</blockquote><h4>Project Highlights</h4><p>In the project I will describe here I used real financial data from Bertelsmann Arvato Analytics for a mail-order sales company in Germany. My task was to identify the segments of the population that form the core of the user base of this company. In other words, I dealt with a clustering problem.</p><p>In the upcoming paragraphs I will elaborate the steps I took to accomplish my target. Just like in most machine learning problems, no matter how complex your algorithms are, the data must be cleaned first. So here we go :)</p><h4>Data Processing</h4><p>There are four data sets relevant for this case:</p><ul><li>Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).</li><li>Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).</li><li>Data_Dictionary.md: Detailed information file about the features in the provided datasets.</li><li>AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columns</li></ul><p>Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. I used this data to cluster the general population into groups with similar demographic properties. The purpose is to see how the people in the customers data set fit into these created clusters.</p><p>Let’s have a look at what features we will work with.</p><pre><em># Load in the general demographics data.</em><br>azdias = pd.read_csv(&#39;Udacity_AZDIAS_Subset.csv&#39;, sep = &#39;;&#39;)<br><br><em># Load in the feature summary file.</em><br>feat_info = pd.read_csv(&#39;AZDIAS_Feature_Summary.csv&#39;, sep = &#39;;&#39;)</pre><pre>print(feat_info)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*7sdZcDX5sDzzlt3zOmtLbA.jpeg" /></figure><p>In the dictionary file all these features are described in more detail. I.e. their meaning in English is provided, as well as what the different levels of the features mean.</p><p>Notice that in the fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. I converted data that matches a &#39;missing&#39; or &#39;unknown&#39; value code into a numpy NaN value.</p><pre><em># turn missing_or_unknown to list </em><br>feat_info[&#39;missing_or_unknown&#39;] = feat_info[&#39;missing_or_unknown&#39;].apply(<strong>lambda</strong> x: x[1:-1].split(&#39;,&#39;))<br><br><em># Identify missing or unknown data values and convert them to NaNs.</em><br><strong>for</strong> attrib, missing_values <strong>in</strong> zip(feat_info[&#39;attribute&#39;], feat_info[&#39;missing_or_unknown&#39;]):<br>    <strong>if</strong> missing_values[0] != &#39;&#39;:<br>        <strong>for</strong> value <strong>in</strong> missing_values:<br>            <strong>if</strong> value.isnumeric() <strong>or</strong> value.lstrip(&#39;-&#39;).isnumeric():<br>                value = int(value)<br>            azdias.loc[azdias[attrib] == value, attrib] = np.nan</pre><p><strong>Assess Missing Data in Each Column</strong></p><pre><em># Perform an assessment of how much missing data there is in each column of the</em><br><em># dataset.</em><br>missing_data = pd.Series(azdias.isnull().sum() / len(azdias))<br>missing_data.plot(kind=&#39;barh&#39;, figsize=(10, 20))</pre><pre>missing_data[missing_data &gt; 0.2].index.tolist()</pre><pre>[&#39;AGER_TYP&#39;,<br> &#39;GEBURTSJAHR&#39;,<br> &#39;TITEL_KZ&#39;,<br> &#39;ALTER_HH&#39;,<br> &#39;KK_KUNDENTYP&#39;,<br> &#39;KBA05_BAUMAX&#39;]</pre><pre><em># Remove the outlier columns from the dataset. (You&#39;ll perform other data engineering tasks such as re-encoding and imputation later.)</em></pre><pre>azdias = azdias.drop([&#39;AGER_TYP&#39;,&#39;GEBURTSJAHR&#39;,&#39;TITEL_KZ&#39;,&#39;ALTER_HH&#39;,&#39;KK_KUNDENTYP&#39;,&#39;KBA05_BAUMAX&#39;], axis = 1)</pre><p>I have assessed the missing data using a bar plot. I have classified as outliers the columns that have more than 20% as missing values. As a result I found 6 such columns which I dropped. Other outliers standing out are the PLZ8 features with 13% missing values; and the KBA05 features with 15% missing values.</p><p><strong>Assess Missing Data in Each Row</strong></p><p>Just like in the case of assessing missing data in columns, I looked for outlier rows with missing data. I set the threshold as 10 missing values per row and divided the data into two groups: rows with high number of missing values (i.e. above 10), and rows with low number of missing values (i.e. lower than 10). I compared the distributions of several non-missing features between these two groups. The purpose was to understand whether I should treat these data points in a specific way.</p><pre><em># How much data is missing in each row of the dataset?</em><br>missing_data_rows = azdias.isnull().sum(axis = 1)</pre><pre>missing_data_rows_low = azdias[azdias.isnull().sum(axis=1) &lt; 10].reset_index(drop=<strong>True</strong>)<br><br>missing_data_rows_high = azdias[azdias.isnull().sum(axis = 1) &gt;= 10].reset_index(drop=<strong>True</strong>)</pre><pre><strong>def</strong> countplot(columns, num):<br>    fig, axs = plt.subplots(num, 2, figsize=(15, 15))<br>    fig.subplots_adjust(hspace =2 , wspace=.2)<br>    axs = axs.ravel()<br>    <br>    <strong>for</strong> i <strong>in</strong> range(num):<br>        <br>        sns.countplot(missing_data_rows_low[columns[i]], ax=axs[i*2])<br>        axs[i*2].set_title(&#39;missing_data_rows_low&#39;)<br>        sns.countplot(missing_data_rows_high[columns[i]], ax=axs[i*2+1])<br>        axs[i*2+1].set_title(&#39;missing_data_rows_high&#39;)<br>        <br>countplot(missing_data_rows_high.columns, 3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*pHyzmygEf5K9UE6KTjSI2Q.png" /></figure><p>For some of the features I checked, there seems to be a different distribution between the rows with many missing values and few missing values. This implies that the data is qualitatively different between the rows with high number of missing values and low number of missing values. The group of rows with low number of missing data will be considered for further analysis, whereas the group of rows with high number of missing data will be considered as an additional cluster in the end.</p><p><strong>Data Wrangling</strong></p><pre><strong>def</strong> clean_data(df):<br>    <em>&quot;&quot;&quot;</em><br><em>    Perform feature trimming, re-encoding, and engineering for demographics</em><br><em>    data</em><br><em>    </em><br><em>    INPUT: Demographics DataFrame</em><br><em>    OUTPUT: Trimmed and cleaned demographics DataFrame</em><br><em>    &quot;&quot;&quot;</em><br>    <br>    <em># Put in code here to execute all main cleaning steps:</em><br>    <em># convert missing value codes into NaNs, ...</em><br>    <br>    df_copy = df.copy()<br><br><em># Identify missing or unknown data values and convert them to NaNs.</em><br>    <strong>for</strong> col_name <strong>in</strong> df.columns:<br>        df_copy[col_name] = df_copy[col_name].map(<strong>lambda</strong> x: np.nan <strong>if</strong> str(x) <strong>in</strong> feat_info.loc[col_name].missing_or_unknown <strong>else</strong> x)<br>        <br>    <em># remove selected columns and rows, ...</em><br>    c_removed =[&#39;AGER_TYP&#39;,&#39;GEBURTSJAHR&#39;,&#39;TITEL_KZ&#39;,&#39;ALTER_HH&#39;,&#39;KK_KUNDENTYP&#39;,&#39;KBA05_BAUMAX&#39;]<br>    <br>    <strong>for</strong> c <strong>in</strong> c_removed:<br>        df_copy.drop(c, axis=1, inplace=<strong>True</strong>)<br>        <br>    df_copy = df_copy[df_copy.isnull().sum(axis=1) &lt; 10].reset_index(drop=<strong>True</strong>)<br>    <br>    <strong>for</strong> col <strong>in</strong> df_copy.columns:<br>        df_copy[col] = df_copy[col].fillna(df_copy[col].mode()[0])<br>        <br>    <br>    <em># select, re-encode, and engineer column values.</em><br>    multi_level = []<br>    <strong>for</strong> column <strong>in</strong> df_copy.columns:<br>        <strong>if</strong> feat_info.loc[column].type == &#39;categorical&#39; <strong>and</strong> len(df_copy[column].unique()) &gt; 2:<br>            multi_level.append(column)<br>            <br>    <strong>for</strong> col <strong>in</strong> multi_level:<br>        df_copy.drop(col, axis=1, inplace=<strong>True</strong>)<br>    <br>    df_copy[&#39;decade&#39;] = df_copy[&#39;PRAEGENDE_JUGENDJAHRE&#39;].apply(create_interval_decade)<br>    df_copy[&#39;movement&#39;] = df_copy[&#39;PRAEGENDE_JUGENDJAHRE&#39;].apply(create_binary_movement)<br>    df_copy.drop(&#39;PRAEGENDE_JUGENDJAHRE&#39;, axis=1, inplace=<strong>True</strong>)<br>    <br>    df_copy[&#39;wealth&#39;] = df_copy[&#39;CAMEO_INTL_2015&#39;].apply(wealth)<br>    df_copy[&#39;life_stage&#39;] = df_copy[&#39;CAMEO_INTL_2015&#39;].apply(life_stage)<br>    df_copy.drop(&#39;CAMEO_INTL_2015&#39;, axis=1, inplace=<strong>True</strong>)<br>    <br>    df_copy = pd.get_dummies(data=df_copy, columns=[&#39;OST_WEST_KZ&#39;])<br>    <br>    mixed = [&#39;LP_LEBENSPHASE_FEIN&#39;,&#39;LP_LEBENSPHASE_GROB&#39;,&#39;WOHNLAGE&#39;,&#39;PLZ8_BAUMAX&#39;]<br>    <br>    <strong>for</strong> c <strong>in</strong> mixed:<br>        df_copy.drop(c, axis=1, inplace=<strong>True</strong>)<br>    <br>     <em># Return the cleaned dataframe.</em><br>    <strong>return</strong> df_copy</pre><p>I made a cleaning data function that I could apply on both the general population demographics data and on the customer demographics data.</p><h4>Principal Component Analysis</h4><p>PCA is one of the most used unsupervised machine learning tools. <strong>Principal components</strong> are linear combinations of the original features in a data set that aim to retain the most information in the original data. Principal Component Analysis is a common method for extracting new “latent features” from our data set, based on existing features. Think of a <em>principal component</em> in the same way that you think about a <em>latent feature</em>.</p><p>When we have data sets with hundreds or thousands of features, we must reduce the number of dimensions in order to effectively build a model. There are two approaches to do this:</p><p>a) <em>Feature Selection: </em>Feature Selection involves finding a <strong>subset</strong> of the original features of your data that you determine are most relevant and useful.</p><p>b) <em>Feature Extraction: </em>Feature Extraction involves extracting, or constructing, new features called <strong>latent features</strong>.</p><h4>Feature Transformation</h4><p>I performed <em>feature scaling</em> so that the principal component vectors are not influenced by the natural differences in scale for features.</p><pre><em># Fill the Nan values with the mode of that respective column.</em></pre><pre><strong>for</strong> col <strong>in</strong> missing_data_rows_low.columns:<br>        missing_data_rows_low[col] = missing_data_rows_low[col].fillna(missing_data_rows_low[col].mode()[0])</pre><pre><em># Apply feature scaling to the general population demographics data.</em></pre><pre>normalizer = StandardScaler()<br>missing_data_rows_low[missing_data_rows_low.columns] = normalizer.fit_transform(missing_data_rows_low[missing_data_rows_low.columns])</pre><pre>missing_data_rows_low.head()</pre><p><strong>Dimensionality Reduction</strong></p><pre><em># Apply PCA to the data.</em><br><br>pca = PCA()<br>missing_data_rows_low_pca = pca.fit_transform(missing_data_rows_low)</pre><pre><em># Investigate the variance accounted for by each principal component.</em></pre><pre><strong>def</strong> scree_plot(pca):<br>    <em>&#39;&#39;&#39;</em><br><em>    Creates a scree plot associated with the principal components </em><br><em>    </em><br><em>    INPUT: pca - the result of instantian of PCA in scikit learn</em><br><em>            </em><br><em>    OUTPUT:</em><br><em>            None</em><br><em>    &#39;&#39;&#39;</em><br>    num_components = len(pca.explained_variance_ratio_)<br>    ind = np.arange(num_components)<br>    vals = pca.explained_variance_ratio_<br> <br>    plt.figure(figsize=(10, 6))<br>    ax = plt.subplot(111)<br>    cumvals = np.cumsum(vals)<br>    ax.bar(ind, vals)<br>    ax.plot(ind, cumvals)<br> <br>    ax.xaxis.set_tick_params(width=0)<br>    ax.yaxis.set_tick_params(width=2, length=12)<br> <br>    ax.set_xlabel(&quot;Principal Component&quot;)<br>    ax.set_ylabel(&quot;Variance Explained (%)&quot;)<br>    plt.title(&#39;Explained Variance Per Principal Component&#39;)<br>    <br><br>scree_plot(pca)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*47jmvUvjoqiW6SxQOElgxQ.jpeg" /></figure><pre><em># Re-apply PCA to the data while selecting for number of components to retain.</em><br><br>pca = PCA(n_components=41)<br>missing_data_rows_low_pca = pca.fit_transform(missing_data_rows_low)</pre><p>Based on the PCA plot, the variance explained becomes extremely low after 41 components and it does not change afterwards. So I did the PCA again with 41 components.</p><p>Each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.</p><h4>Apply Clustering to the General Population</h4><pre><strong>def</strong> get_kmeans_score(data, center):<br>    <em>&#39;&#39;&#39;</em><br><em>    returns the kmeans score regarding SSE for points to centers</em><br><em>    INPUT:</em><br><em>        data - the dataset you want to fit kmeans to</em><br><em>        center - the number of centers you want (the k value)</em><br><em>    OUTPUT:</em><br><em>        score - the SSE score for the kmeans model fit to the data</em><br><em>    &#39;&#39;&#39;</em><br>    <em>#instantiate kmeans</em><br>    kmeans = KMeans(n_clusters=center)<br><br>    <em># Then fit the model to your data using the fit method</em><br>    model = kmeans.fit(data)<br>    <br>    <em># Obtain a score related to the model fit</em><br>    score = np.abs(model.score(data))<br>    <br>    <strong>return</strong> score</pre><pre><em># Over a number of different cluster counts...</em><br><em># run k-means clustering on the data and...</em><br><em># compute the average within-cluster distances.</em></pre><pre>scores = []<br>centers = list(range(1,30,3))<br><br><strong>for</strong> center <strong>in</strong> centers:<br>    scores.append(get_kmeans_score(missing_data_rows_low_pca, center))</pre><pre><em># Investigate the change in within-cluster distance across number of clusters.</em><br><em># HINT: Use matplotlib&#39;s plot function to visualize this relationship.</em></pre><pre>plt.plot(centers, scores, linestyle=&#39;--&#39;, marker=&#39;o&#39;, color=&#39;b&#39;);<br>plt.xlabel(&#39;K&#39;);<br>plt.ylabel(&#39;SSE&#39;);<br>plt.title(&#39;SSE vs. K&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*Awub7m1KptJstkMr-cxYhA.png" /></figure><pre><em># Re-fit the k-means model with the selected number of clusters and obtain</em><br><em># cluster predictions for the general population demographics data.</em><br><br><em># Re-fit the k-means model with the selected number of clusters and obtain</em><br><em># cluster predictions for the general population demographics data.</em><br><br>kmeans = KMeans(n_clusters=22)<br>model_general = kmeans.fit(missing_data_rows_low_pca)</pre><pre>predict_general = model_general.predict(missing_data_rows_low_pca)</pre><p>Based on the plot, we can see that 22 seems to be a sufficient number of clusters. Afterwards the rate of change is SSE is extremely low.</p><h4>Compare Customer Data to Demographics Data</h4><p>After clustering the population demographics data, we apply the same data cleaning steps and clustering to the customers demographic data. The purpose is to see which is the strong customer base for the company.</p><p>If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster’s centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*jti_BMOsej_ABb8zIKbQvA.png" /></figure><p><strong>Analyze a cluster where the customer data is over represented</strong></p><pre><em># What kinds of people are part of a cluster that is overrepresented in the</em><br><em># customer data compared to the general population?</em><br>over = normalizer.inverse_transform(pca.inverse_transform(customers_clean_pca[np.where(predict_customers==11)])).round()<br>df_over = pd.DataFrame(data = over, columns = customers_clean.columns)<br>df_over.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*I6z9JHX-twhOVAKJed93Dg.png" /></figure><p>This segment is composed of individuals in the age between 46 and 60+ that are not financial minimalists. I.e. they are probably people in retirement or close to it, that are eager to consume goods and services.</p><p><strong>Analyze a cluster where the customer data is under represented</strong></p><pre><em># What kinds of people are part of a cluster that is underrepresented in the</em><br><em># customer data compared to the general population?</em><br>under = normalizer.inverse_transform(pca.inverse_transform(customers_clean_pca[np.where(predict_customers==16)])).round()<br>df_under = pd.DataFrame(data=under, columns=customers_clean.columns)<br>df_under.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*VL3ClWngntHhry6A0qKs1A.png" /></figure><p>This segment is composed of people in the younger age group (up to 45 years old), with a larger proportion of unemployed people.</p><h4>Project Conclusion</h4><p>Recall in the data processing step that we determined the group of rows with high number of missing data will be considered as an additional cluster in the end. The cluster 22 in the above group is this last added cluster. we can see that there is quite a difference between population percentages and customer percentages in most clusters. In the majority of the clusters, it is the general population that is over represented. For instance, in cluster 11 where the customers segment is over represented; it is composed of individuals in the age between 46 and 60+ that are not financial minimalists. I.e. they are probably people in retirement or close to it, that are eager to consume goods and services. So it makes sense to consider it a customer group. On the other side, in cluster 16, the customer segment is under represented. This segment is composed of people in the younger age group (up to 45 years old), with a larger proportion of unemployed people. Since they are mostly unemployed, they most likely live off social security. Hence they wouldn’t have large disposable to spend on products marketed to them.</p><h4>Closing Words</h4><p>If you made it to the end, thank you very much for reading :) I know these posts are long and include many code snippets, but I really think that ignoring the technical aspect of machine learning is not feasible to show how algorithms work. This project was rewarding for me because it included real-world financial data with a real-world business objective.</p><p>I hope this gives you an understand of how unsupervised machine learning can be applied in business and marketing. If you want to go through all the code I wrote, you can visit my project on my <a href="https://github.com/andreigalanciuc/UNSUPERVISED-MACHINE-LEARNING/blob/master/Identify_Customer_Segments%20(1).ipynb">github</a>.</p><p>Follow me on LinkedIn: <a href="https://www.linkedin.com/in/andreigalanchuk/">https://www.linkedin.com/in/andreigalanchuk/</a></p><p>God bless you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd75edaeefc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/use-unsupervised-machine-learning-to-find-potential-buyers-of-your-products-cd75edaeefc7">Use Unsupervised Machine Learning To Find Potential Buyers of Your Products</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Find Donors For Charity With Machine Learning Models]]></title>
            <link>https://medium.com/data-science/lets-find-donors-for-charity-with-machine-learning-models-7ad1da9f5538?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ad1da9f5538</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 12:48:00 GMT</pubDate>
            <atom:updated>2022-09-26T16:20:09.110Z</atom:updated>
            <content:encoded><![CDATA[<h4>An application of Supervised Learning Algorithms</h4><p>Welcome to my second medium post about Data Science. I will write here about a project I’ve done using Machine Learning algorithms. I will explain what I did without relying heavily on technical language, but I will show snippets of my code. Code matters :)</p><p>The project is a hypothetical case study where I had to identify potential donors to a charity that offers funding to people willing to study machine learning in Silicon Valley. This charity, named CharitML found that every donor was making more than $50,000 annually. My task was to use machine learning algorithms to help this charity identify potential donors in the entire region of California.</p><blockquote>For the purposes of this project, I used supervised machine learning. Supervised learning is where you have input variables (X) and an output variable (Y ) and you use an algorithm to learn the mapping function from the input to the output. I will describe the steps I took to get from a messy data set to a good working model.</blockquote><h4>Data Processing</h4><p>It’s always good to start with exploring the data. Basically, look for the total number of observations, total number of features, missing values, which features should be encoded etc. And most importantly, look for the characteristics specific to the problem you are solving. In this case I was interested in how many people make more and less than $50,000 annually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*gZG3x2TYsSMbIBJ2YCVzDQ.jpeg" /><figcaption>There are 13 features.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*zUfQoelIjq7a7VAeEscZhQ.jpeg" /></figure><p><strong><em>Transforming Skewed Continuous Features</em></strong></p><p>A data set may sometimes contain at least one feature whose values tend to lie near a single number, but will also have a non-trivial number of vastly larger or smaller values than that single number. Algorithms can be sensitive to such distributions of values and can under perform if the range is not properly normalized. With our data set two features fit this description: ‘capital-gain&#39; and &#39;capital-loss&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Bm6QnRyB4E3s4k0__poW5A.jpeg" /></figure><p><strong><em>Normalizing Numerical Features</em></strong></p><p>It is often good practice to perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature’s distribution (such as &#39;capital-gain&#39; or &#39;capital-loss&#39; above); however, normalization ensures that each feature is treated equally when applying supervised learners. The features will range between the values of 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*r4j6Ma8PVFXgGiJuCdzVqw.jpeg" /></figure><p><strong><em>Encoding the data</em></strong></p><p>Typically, learning algorithms expect inputs to be numeric, which requires that non-numeric features (called <em>categorical variables</em>) be converted. One popular way to convert categorical variables is by using the <strong>one-hot encoding</strong> scheme. One-hot encoding creates a <em>“dummy” </em>variable for each possible category of each non-numeric feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*vV0o3M5cD7AGTek2prtBSQ.jpeg" /></figure><p><strong><em>Shuffle and Split Data</em></strong></p><p>Now all <em>categorical variables</em> have been converted into numerical features, and all numerical features have been normalized. As always, we will now split the data (both features and their labels) into training and test sets. 80% of the data will be used for training and 20% for testing.</p><h4>Model Metrics</h4><p>Before I get into the different models I tested for this project, I will elaborate on how we judge the quality of a model. What do we look at when deciding which model to choose? There is always going to be a trade-off between how well we want the model to predict and how computationally expensive it is; or how long it takes to train it.</p><p>The three main metrics of model performance are: accuracy, precision and recall.</p><p><strong>Accuracy </strong>measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points).</p><p><strong>Precision </strong>tells us what proportion of messages we classified as spam, actually were spam. It is a ratio of true positives(words classified as spam, and which are actually spam) to all positives(all words classified as spam, irrespective of whether that was the correct classification).</p><p><strong>Recall(sensitivity)</strong> tells us what proportion of messages that actually were spam were classified by us as spam. It is a ratio of true positives(words classified as spam, and which are actually spam) to all the words that were actually spam.</p><p>The different measures matter in varying degrees in different problems. Hence we should know which metric matters for us more. For instance identifying someone that <em>does not</em> make more than $50,000 as someone who does would be detrimental to CharityML, since they are looking to find individuals willing to donate. Therefore, a model’s ability to <strong><em>precisely</em></strong> predict those that make more than $50,000 is <em>more important </em>than the model’s ability to <strong><em>recall</em></strong> those individuals.</p><p>We can use <strong>F-beta score</strong> as a metric that considers both precision and recall:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*tPI_1P_CtAGvK3sYyhHzDg.jpeg" /></figure><p><strong><em>Naive Baseline Predictor</em></strong></p><p>If we chose a model that always predicted an individual made more than $50,000, what would that model’s accuracy and F-score be on this data set? We want to know how a model without training would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*nLOzrmWKwLFgeHoW-ehhXw.jpeg" /></figure><h4>SUPERVISED LEARNING MODELS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*oRoLCi_am39e-sFQg8jeXg.png" /><figcaption>This is not an exhaustive list</figcaption></figure><p>Out of these options, I tried and tested three of them: <em>SVM, ADABOOST and Random Forrest.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*cl0XknpSb0jQdFuHWjgADA.jpeg" /></figure><p>The <strong>Adaboost</strong> model is best suitable for our problem. The <em>F score</em> on the testing data set is the highest for Adaboost. Besides that, there is not a big difference in F-scores between the training and testing sets like with RandomForest. This matters because we do not want our model to overfit on the training set and return us an inflated F score. The accuracy score and F score are highest for Adaboost at all training set sizes. The training and testing times are very low, which means that the model is <em>computationally fast</em>. The iterative aspect of the model makes it handle well a high number of attributes like in our case. Hence it is a good choice.</p><p><strong><em>How ADABOOST Works</em></strong></p><p><strong>Adaboost</strong>, short for <em>adaptive boosting</em> is an ensemble algorithm. The <strong>Adaboost</strong> algorithm uses iterative training to give an accurate model. It starts with a weak learner which is the initial classification of the data. Namely, the classification is done with <em>decision stumps</em>. This means that the classification is done just with a line that separates the data. It is called <em>‘weak’</em> because the data is not classified very well yet. But due to the further iterations, the model makes the learners focus on the <em>misclassified points</em>. To be more precise, in the first step the weak learner separates the data and all the points are weighted equally. If there are misclassified points, in the second iteration the weak learner tries to capture most of these previous errors and it assigns them higher weights. The essence is that the model focuses on the errors by weighing them more. This iterative process continues as long as we assign it to do it. As a result, with every iteration, the model captures better and better the data. The weak learners are combined and they are assigned weights respective to their performance. Predictions are made by calculating the weighted average of the weak classifiers. The final learner is a strong learner combined from the weak ones.</p><h4>Model Tuning</h4><p>We can improve the chosen model further by using Grid Search. The idea is to use different values for some parameters like number of estimators or learning rate, in order to achieve better performance metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Ns4jP5Bp4--6QJFDwINZVQ.jpeg" /><figcaption>Hope you’re not tired of these yet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*c4f2_1qnI8Ig3TzHQdmJVA.jpeg" /></figure><p>We can see that the optimized model performed better than the unoptimized model. The accuracy score increased from 0.8576 to 0.8651, and the F-score increased from 0.7246 to 0.7396. Remember that the Naive Predictor gave us an accuracy score of 0.2478 and F-score of 0.2917, which is not surprising because the naive model doesn’t do any training on the data.</p><h4>Feature Extraction</h4><p>Out of the 13 features in this data set, I was curious to see which ones have the highest predictive power. And what would happen if we used only those in our model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*R4X_MmeUyye0-oAa42dYQw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*WnapMhLTReKeQ2_Ck-8_EA.jpeg" /></figure><p>In the reduced model both the accuracy and F-score decreased. Less features in this case made the model generalize a bit worse, compared to the full model. However the reduction in scores is not high. In return training time is faster because the model contains less features. Hence, if training time was a factor, this trade off would make sense because we would not lose much in terms of performance.</p><p><strong><em>Summary</em></strong></p><p>So what did we do? We got a data set and we set a target to classify people that make more than $50,000 annually. We cleaned the data, normalized and converted the necessary variables into numerical features so that we can use them in our models. We shuffled and split our data into training and testing sets. We set a baseline predictor and built three other models. We chose the ADABOOST model as the best choice. We tuned it further and made it slightly better. We tried to use the model with only the five main features but it performed slightly worse.</p><h4>Final Words</h4><p>This was it :) If you made it through here, I want to say a big thank you. I hope this was a good and clear application of supervised machine learning. It is a powerful tool in data science; something that I am currently studying and want to master. Feel free to comment below if you have questions and you can always have a look at this project, including many others on my <a href="https://github.com/andreigalanciuc/MACHINE-LEARNING-FINDING-DONORS/blob/master/finding_donors_final.ipynb">github</a>.</p><p>Follow me on LinkedIn: <a href="https://www.linkedin.com/in/andreigalanchuk/">https://www.linkedin.com/in/andreigalanchuk/</a></p><p>God bless you all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad1da9f5538" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/lets-find-donors-for-charity-with-machine-learning-models-7ad1da9f5538">Let’s Find Donors For Charity With Machine Learning Models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[People in tech aren’t necessarily computer science grads]]></title>
            <link>https://medium.com/@andreigalanchuk/people-in-tech-arent-necessarily-computer-science-grads-dee8c4a099a4?source=rss-e340d8809fcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dee8c4a099a4</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrei G]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 17:01:46 GMT</pubDate>
            <atom:updated>2019-01-01T17:13:39.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JtsBUQJzwZNu2sj6YuS6fA.jpeg" /><figcaption>I think it’s a beautiful view; but unrelated to my post :)</figcaption></figure><h4><strong>This is my first post related to tech, specifically data science.</strong></h4><p>I am currently studying Data Science online at <a href="https://medium.com/u/2929690a28fb">Udacity</a> and I decided to write posts about I do; things like researching a data set or making machine learning algorithms. Hopefully this makes me understand this field better and improve my own writing skills.</p><h4>What this post is about..</h4><p>I chose a data set from Kaggle to look at some things related to the tech field. Namely I took the “<a href="https://medium.com/u/d53dd768d047">Stack Overflow</a> 2018 Survey”. For the record I am not a tech major. I am currently a Math Teacher, and my education is a Bsc Economics. For this reason I wanted to see how important formal education is to break into the tech sector and what common majors people have there.</p><h4><strong>Data set</strong></h4><p>There were 48788 respondents in this survey in 2018. These are some of the 129 questions in the survey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*PSqqUmBGi332JVztTsGV7A.jpeg" /><figcaption>Survey</figcaption></figure><h4>How well can Formal Education predict Salary?</h4><p>To answer this question, I wanted to calculate how much variation in salaries can be explained by Formal Education. The statistical tool for that is know as r squared.</p><p>There was some data cleaning and data engineering that I had to do first. I dropped the rows with missing salaries from the data set; and I encoded the <em>Formal Education </em>variable. When it comes to categorical variables (i.e. not numbers like 15, or 789, but rather groups, or categories, like bachelor degree, doctoral degree etc.), they must be encoded to be treated quantitatively, as either 1 or 0.</p><p>Once the data is ready to be processed, I trained the regression on 70% of the data and I tested it on the other 30% of the data. Whenever it comes to models, even as simple as linear regressions, we want to have training and testing sets. The reason is that we do not want the model to fit extremely well on the training set, but fail to predict on other sets. We want the model to capture the overall trend.</p><p>To my surprise, the r squared value for this model was extremely low, close to 0. This tells us that Formal Education is useless in predicting Salary. In the context of this data set at least, formal education was not a good predictor of salaries at all. This might not sound so strange, when we think that the people in tech break in using non-traditional ways. Many rely on online education, others attend bootcamps, or they get experience via internships.</p><h4>What is the most common undergrad major?</h4><p>I wanted to see what people studied in university to work as developers, or software engineers, or data scientists etc. I was expecting to see primarily computer science and math graduates. Again, to my surprise the results were different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*C-7fgPfPttTWahczwZTLOQ.jpeg" /></figure><p>As we can see, the majority of degrees are from natural sciences (physics, biology etc.). Computer science accounted only for 8.5% of the majors researched here. This should give hope to aspiring data scientists or other tech career candidates who do not have a technical background. I still believe a technical background is the best foundation for such jobs, but these skills can still be learnt.</p><h4>What are the ambitions of tech people within five years?</h4><p>I was curious to see why people choose such careers. Do these jobs feel enough, or do they want something different in the near future? A brief analysis follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*AG1awWbWJT14yOeHuGvDPA.jpeg" /></figure><p>The majority of respondents would like to work in a more specialized technical role than currently, followed by a desire to be the founders of their own companies. The second result is not surprising to me: wanting to found a company. With the insane success stories of tech companies like Facebook, Google, Spotify etc., people realize that there is a big opportunity in tech entrepreneurship. So many employees in this field are probably getting experience in these companies, with the hope of making their own company one day.</p><h4>Thank you for reading!</h4><p>If you made it this far, thank you! If you decide to clap on this post, I will definitely appreciate it :) You can see the notebook with code for this project <a href="https://github.com/andreigalanciuc/STACKOVERFLOW-2018-SURVEY">here</a>.</p><p>Follow me on LinkedIn: <a href="https://www.linkedin.com/in/andreigalanchuk/">https://www.linkedin.com/in/andreigalanchuk/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dee8c4a099a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>