<?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 Stacy Li on Medium]]></title>
        <description><![CDATA[Stories by Stacy Li on Medium]]></description>
        <link>https://medium.com/@stacyli0720?source=rss-3f589870d0fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gQRVsEKz_7x97XT7ho4OBw.jpeg</url>
            <title>Stories by Stacy Li on Medium</title>
            <link>https://medium.com/@stacyli0720?source=rss-3f589870d0fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:53:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stacyli0720/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[From Executor to Architect: How I Use Claude Code to Multiply Myself as a Data Scientist]]></title>
            <link>https://medium.com/@stacyli0720/from-executor-to-architect-how-i-use-claude-code-to-multiply-myself-as-a-data-scientist-57823379657d?source=rss-3f589870d0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/57823379657d</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[airdrop]]></category>
            <dc:creator><![CDATA[Stacy Li]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 01:49:24 GMT</pubDate>
            <atom:updated>2026-03-23T01:49:24.247Z</atom:updated>
            <content:encoded><![CDATA[<p>A month ago, I set myself a challenge: how much of my day-to-day work as a Data Scientist could Claude Code take over?</p><p>The answer surprised me. Not because it replaced me — but because it fundamentally changed <em>what I do.</em></p><h4>The old model: DS as executor</h4><p>Before Claude Code, my work looked like this: I’d spend Monday morning reviewing the past week, identifying what remained undone, and picking 3 priorities. Each morning, I’d plan my day around the gaps between meetings. Then I’d execute — context-switching between data pulls, analysis, slide decks, and writing updates — one task at a time, serially, like a single-threaded process.</p><p>The bottleneck was me.</p><h4>The new model: DS as system architect</h4><p>What shifted isn’t the work itself — it’s my relationship to it. I no longer execute tasks. I design the system that executes them.</p><p>Below is my current system of work with Claude Code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PugAZOqZpKrf2gdsYe795A.png" /></figure><p><strong>Context as infrastructure.</strong> I used to carefully curate what context I gave an AI — handpicking relevant details. I’ve completely inverted that approach. Now I dump everything I can find through MCP/copy-and-paste: Slack threads, 1:1 notes, tickets, docs, past conversations with Claude Code. The key insight is that as models have gotten smarter, the cost of irrelevant context has dropped to near zero — Claude figures out what matters. My context files (CLAUDE.md, project_context.md) are now living infrastructure, continuously updated by a note organization skill.</p><p><strong>Planning as dispatch.</strong> My morning routine now starts with a task manager skill that ingests my tickets, the past 24 hours of Slack, my 1:1 docs, and recent chat history with Claude Code— and surfaces a prioritized view of what needs attention. From there, I review with Claude Code and dispatch: some tasks go to agents, some stay with me. The criterion for staying with me is simple: does this require human judgment, relationship knowledge, or creative framing that Claude can’t yet replicate?</p><p><strong>Skills as institutional knowledge.</strong> For recurring task types — data analysis, experiment readouts, weekly updates, presentation decks — I’ve codified my own process into skills. Each skill encodes not just the steps but the <em>principles</em> behind them: what makes a good experiment readout, what a senior IC’s analysis should communicate. Running an analysis now means curating a context file and invoking a skill. The quality standard is mine; the execution is delegated.</p><p><strong>Quality gates, not blind trust.</strong> The biggest operational lesson: build review into the architecture, not as an afterthought. I run an independent review agent with explicit criteria — calibrated to my standard of “what good looks like” — before any work goes out. Human-in-the-loop is a checkpoint, not a fallback.</p><h4>What this actually looks like in practice</h4><p>Two examples capture the leverage better than anything else.</p><p>The first is scale. When I needed to review LinkedIn member profiles at scale, I realized I could spin up multiple agents working simultaneously — four hours of manual work collapsed to twenty minutes. The task didn’t get smarter. The architecture did.</p><p>The second is depth. I was recently asked to lead a strategic deep-dive — the kind of analysis that normally takes a week of focused work. Instead of diving straight in, I spent one day doing something different: codifying my own analytical process. How do I frame a strategic question? What sources do I triangulate? What makes a finding credible versus superficial? I wrote all of it down as a skill. Then I ran the analysis. What would have taken a week took two days — and next time, it’ll be faster still, because the process is now infrastructure, not tribal knowledge locked in my head.</p><p>Together, these two examples point at something important: the leverage isn’t just about running tasks faster. It’s about making your own expertise transferable — to agents, to teammates, to your future self.</p><h4>What I’m still learning</h4><p>The DS role isn’t disappearing. It’s concentrating. The craft is now in how you design the pipeline: which skills to build, what quality standards to encode, where human judgment is irreplaceable, and how to create feedback loops that make agents better over time.</p><p>The executor is being automated. The architect isn’t.</p><h4>A wishlist for Claude Code</h4><p>The biggest friction in my current workflow is managing multiple agents simultaneously. Right now I’m juggling several terminal windows, manually checking each one — finished? stuck? waiting on me? The context-switching overhead is real, and the waiting feels opaque.</p><p>My vision is something I’d call a <strong>central agent desk</strong>: a single view showing every agent’s state at a glance, organized by what needs my attention — running, waiting for input, blocked, done. Each agent shows what it’s working on, how far along it is, and <em>why</em> it’s stuck if it is. No more tab-switching to find out. Below is a prototype of this idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCbnfWwYUJAyPL_Mw77S9g.png" /></figure><h4>A note of gratitude</h4><p>None of this would have been possible without a manager who gives real room to experiment. Having the trust and latitude to explore, break things, and build something genuinely new — rather than just execute against a predefined roadmap — is rare. I’m grateful for it, and it’s a big part of why these past month have felt energizing rather than exhausting.</p><p><em>If you’re curious to go deeper, I’ll be writing a follow-up that walks through the specific skills my team and I have built — the ones that have done the most to shift us from execution to architecture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57823379657d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Scientist’s Guide to New Product Launch]]></title>
            <link>https://medium.com/@stacyli0720/a-data-scientists-guide-to-new-product-launch-4905370d4f65?source=rss-3f589870d0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4905370d4f65</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[product-launch]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Stacy Li]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 17:28:08 GMT</pubDate>
            <atom:updated>2024-03-01T17:28:08.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ROUg0lZHt1ctqAYe" /><figcaption>Photo by <a href="https://unsplash.com/@xteemu?utm_source=medium&amp;utm_medium=referral">Teemu Paananen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why This Article?</h3><p>This article is for Product Analytics Data Scientists who aspire to help new products/features to grow from 0 to 1 and for product leaders who are interested in adopting a data-driven strategy to launch your new product and iterate at a faster speed.</p><p>Over the past 2 years at LinkedIn, I’ve been involved in three significant new product launches as a Data Scientist, watching their development from a mere idea, to a minimum viable product launch, and ultimately a fully-realized product serving millions of LinkedIn members. Throughout this journey, I didn’t find many helpful resources outlining the value data and Data Scientists can add to new product launches so I decided to summarize what I learned to share.</p><p>My goal is to share the insights I’ve gathered, particularly beneficial for companies with an existing customer base looking to expand their value offering with new products. For startups just beginning to scale, data strategies may become more relevant as your customer base grows to a size that can’t be handled by a single Excel Spreadsheet :)</p><h3>What Will I Cover?</h3><p>I liken the role of data to a compass for pilgrims navigating through the desert. Venturing across the desert without a map can be a daunting experience. While data won’t entirely eliminate the challenges of building a product, it does help alleviate anxiety by ensuring you’re headed in the right direction.</p><p>I will describe three key product stages where data can add values in building a successful product:</p><ul><li>Product Ideation</li><li>Before Product Launch</li><li>Post-launch Iteration</li></ul><h3>Product Ideation</h3><p>All products start with two fundamental questions: 1) the user problem — WHO we help to solve what particular challenge they face; 2) WHY us: why is our team better-positioned to tackle this user problem vs. any other company/team. A clearly-defined problem statement rallies the team before we embark on the journey to discover HOW (the solution).</p><p>As exciting as it sounds, this stage often involves lots of ambiguity and debates. User research and focus groups play an important role at this initial stage, testing out ideas at small scale before building anything real. Data typically adds more value in the later stage after we’ve launched the product, but it can help test our hypothesis at this stage; it allows us to gauge the size of our market and observe the user behavior to validate whether the pain point does exist. You might have a great idea but ended up discovering that it appeals to only a very small market segment.</p><p>Data can also drive the generation of hypotheses. A famous example is Instagram’s pivot, which all started by an observation that a significant number of photographers uploaded photos to the platform.</p><p>To give a concrete example, before we launched <a href="https://techcrunch.com/2024/01/17/linkedin-rolls-out-new-job-search-features-to-make-it-easier-to-find-relevant-opportunities/?guccounter=1&amp;guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&amp;guce_referrer_sig=AQAAAAn62DNb2cASR6UtlH0B-WdZtF9DVfWplw_kLGhOBiTYsUI20zmyjqVc9063mcg_OfodZPXo9ZVZmwxwWIoKPNS1DlxstQYkBZm6v5jGk3X-2rKrioa30tQxrm1lYHsduauWfVXx7H-pjG3o-KH_MfEWn5Eo8p-rZsWyC3t8Y6es">Job Collection</a>, our hypothesis was that some LinkedIn members are casual job seekers. This means they are not actively seeking but open to the right opportunities. To understand casual seekers on LinkedIn, we conducted an analysis to understand the size of the population and what they do today. The result helped validate that it’s a big enough problem to solve as well as inform the type of collections to provide.</p><h3>Before Product Launch</h3><p>Congrats! If you have come to this stage, that means you have a product that is ready for the market test. Most product ideas get killed at the ideation stage. Before the product launch, there are a couple checklist items to ensure data-driven strategies.</p><p><strong>Define Success Measurement</strong></p><ul><li>Define success metrics</li><li>Tracking</li><li>Data ETLs to operationalize the metrics</li></ul><p><strong>Develop Launch Strategy and Experiment Setup</strong></p><ul><li>Define target audience and rollout schedule</li><li>A/B test setup</li></ul><h4>Define Success Measurement</h4><p><em>Success Metrics</em></p><p>“If you can’t measure it, you can’t improve it” is a famous quote from the management guru Peter Drucker. It’s also true for your new product. If you have defined a clear problem statement, this step is about translating the goal into a measurable set of metrics. Typically, you will need a single true north to measure the overall success of the product as well as a set of signpost metrics to help you diagnose the performance of each sub-component of your product (e.g. which funnel steps members drop).</p><p>The true north metric should be able to tie back to the overall success of your business.</p><p><em>Tracking</em></p><p>Now that we define success metrics, how do we make sure the metrics show up in the dashboards every morning after product launch. Tracking is the foundational step to ensure we have the right data — Data Scientists work with app engineers to identify the data points (e.g, user impressions, actions, conversational data etc) to collect, define the tracking data schemas, and ensure the tracking events are firing correctly.</p><p><em>Data ETLs to operationalize the metrics</em></p><p>Tracking data typically comes in the streaming events that is not easily digestible for reporting tools. To go from raw tracking to clean metrics, we need to add a middle layer to Extract, Transform and Load the data (ETL). In some companies, the step is owned by Data Engineering but the goal is to load the raw tracking data and transform them based on the business logic to calculate business metrics and save in a clean table to connect to downstream applications like a dashboarding tool or experimentation platform.</p><h4>Develop Launch Strategy and Experiment Setup.</h4><p><em>Define target audience and rollout schedule</em></p><p>Ramping a product is exciting but we also need to be careful. To ensure our product meets our quality standards from the outset, it might be prudent to initiate a phased launch, starting with a select group of users. This approach allows us to gather valuable feedback and make necessary adjustments, thereby enhancing user experience as we gradually expand our user base. Some suggestions for designing the ramp strategy.</p><ul><li>Pick the MVP audience</li></ul><p>Consider which country, language and platform you are initially ramping your product up to. It should be the audience you believe the feature will work the best and core audience your company is most familiar with.</p><ul><li>Start small and ramp up carefully</li></ul><p>We want to ramp the product at a small percentage first to make sure all major bugs are cleared up and it doesn’t heavily cannibalize other product features before we continue to ramp up.</p><p><em>A/B test setup</em></p><p>Experimentation (A/B testing) is the gold standard for measuring the impact of a new feature, by randomly assigning some users to receive the features and others to a control condition without it. It sounds simple but there could be lots of complexities involved. To name a few -</p><ul><li>Members come in and out of the experiments. Think about if you are ramping this new product to your paid users, but paid users are joining and churning every day. How do you handle them in the experiment?</li><li>Isolate Go-to-Market and product features’ impact. Along with new product launches, companies typically send out GTM to share the news including emails, notification, pop-up screen etc. How do you decouple the impact of GTM and the product features’ impact on your product engagement?</li><li>Understand the long-term and cross-ramp impact. One round of A/B tests can help us understand the impact of each launch at one time but what you want to understand is the overall impact of multiple product iterations over time even when the macroeconomic conditions change.</li></ul><h3>Post-ramp Launch</h3><p>Hurray! Your team has come a long way to get the product in front of users. Now what — it’s time for the real data power comes in to understand the Product-Market Fit and help fuel the growth of the product. Post-ramp, data are valuable sources to</p><ul><li>Help the team understand the market reaction and user feedback</li><li>Conduct Deep-dive analysis to guide product direction</li></ul><p><strong>Understand the Market Reaction</strong></p><p>We keep our fingers crossed and wait for the few days of data to come in. In the first few weeks, we typically focus on understanding the adoption of the product and also any abnormal data points that may indicate a bug needing to be fixed. Data Scientists work as a raven to collect all the quantitative feedback and sometimes qualitative feedback, digest it and share the key takeaways from the team. The goal is to answer “Is the product working properly?”, “Do the users like this product?”.</p><p><strong>Deep-dive analysis to guide product direction</strong></p><p>If the initial market reaction is positive and the decision is made to invest more resources, we will conduct more deep-dive analysis to help fuel the growth of the product. I found a few angles helpful:</p><ul><li>Understand the usage funnel from Awareness → Activation → Engagement → Conversion →Retention</li><li>Understand the retention: retention is the key for most of the usage products and it’s an indication that people find it valuable and keep coming.</li><li>Identify and understand your power users: if your product retains users, that means something is enticing them to come back. It might be or might not be the intended user case you designed for them. Further data analysis, combined with UXR can help shed some light on the value drivers that make them stay.</li></ul><p>Of course, this only scratches the surface of how to use data to guide the product direction. I will start another series to delve deeper into this topic.</p><h3>In Closing</h3><p>In summary, this guide takes you through the journey of launching a new product, focusing on areas data science can add value. If you find this article helpful, <a href="https://www.linkedin.com/in/stacylixiang/">follow</a> me on LinkedIn! Last but not least, thanks to Bonnie for helping to review this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4905370d4f65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Turn your Analysis into Actionable Results]]></title>
            <link>https://medium.com/@stacyli0720/how-to-turn-your-analysis-into-actionable-results-9d3768b15d36?source=rss-3f589870d0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3768b15d36</guid>
            <category><![CDATA[influence]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Stacy Li]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 12:52:18 GMT</pubDate>
            <atom:updated>2023-03-30T12:52:18.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*nzfGbztUOxfiSJIX" /><figcaption>Source: <a href="https://unsplash.com/photos/Lks7vei-eAg">Unsplash</a></figcaption></figure><h4><strong>The Struggle</strong></h4><blockquote>After spending a full week analyzing the data, you emerge from your office with a sense of satisfaction and accomplishment. Despite the fatigue, you can’t help feel excited about the possibility that the analysis has opened up. You continue to spend several days crafting a very polished deck and can’t wait to share with everyone on the team.</blockquote><blockquote>However, your excitement and confidence quickly turn into frustration when you meet with your shareholders. Although they acknowledge the effort and work put into the analysis, it’s obvious that the findings didn’t trigger any significant interest or inspiration for them. As a result, no tangible action is taken after the meeting.</blockquote><p>This is a common struggle for data analysts/data scientists as most of us deliver the impact by influencing others. Today we will discuss how to land your insights in a DS/DA-led analysis using the “co-creation” model. By closely collaborating with your stakeholders on an analysis, you can increase your chances of turning insights into actions. This model can not only be used to land insights, but also applies to any promoting any project.</p><h4><strong>Start with An Open Discussion</strong></h4><p>When you have gained early insights from the initial analysis, it’s important to reach out to your key stakeholders right away. In my context, it’s usually IC Product Manager I closely work with. Don’t wait until the analysis is complete. Frame the chat into an open discussion by saying something like “I recently had an interesting insight and I would like to chat with you about it and hear your thoughts”. This approach usually leads to an engaging and productive discussions as you are not trying to push any specific action onto your stakeholders like in a formal presentation.</p><h4>Co-create the Analysis Together</h4><p>After having a conversation with your stakeholders, there may be some follow-up questions. We can continue to work on the key questions that arise from the discussion to make the analysis more complete. This also shows your partner that you value their inputs, making them feel that this analysis is the result of co-creation between you and them. Once you and the stakeholders have reached a consensus and are both excited about the action items, you can leverage their influence to secure resources from the senior management. When your stakeholders are invested in the analysis, they will often share the insights with their superiors, making it easier to obtain the resources necessary to move forward with the project.</p><h4>Showcase Your Work</h4><p>After finalizing a few key insights, it’s important to actively seek out opportunities to share with senior management. For example, at broader team weekly meetings. I recently shared an analysis I did at a weekly meeting and the lead PM was particularly interested. As a result, they even convened a meeting with all leads to discuss the insights further. By sharing your analysis with senior management and highlighting key insights, you increase your changes of securing their support and get the resources you need to implement actionable solutions.</p><h4>Final thoughts</h4><p>In summary, it’s crucial closely involve your PM / business partners throughout the process. Identify key individuals and opportunities to co-create an analysis with them. I hope learning my process helps you develop this invaluable skill sooner rather than later. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3768b15d36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practice to Calculate and Interpret Model Feature Importance]]></title>
            <link>https://medium.com/data-science/best-practice-to-calculate-and-interpret-model-feature-importance-14f0e11ee660?source=rss-3f589870d0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f0e11ee660</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[feature-importance]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[Stacy Li]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 19:55:37 GMT</pubDate>
            <atom:updated>2022-07-21T13:04:41.392Z</atom:updated>
            <content:encoded><![CDATA[<h4>With an example of Random Forest model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGHkpxzlnzwfR6yBG1JgWw.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/w7ZyuGYNpRQ">Unsplash</a> (Credit to Kevin Ku)</figcaption></figure><p>In machine learning, most of the time you want a model that is not only accurate but also interpretable. One example is customer churn prediction — in addition to knowing who will churn, it’s equally important to understand which variables are critical in predicting churn to help improve our service and product.</p><p>Popular machine learning packages such as Scikit-learn offer default calculations of feature importances for model interpretation. However, oftentimes we can’t trust those default calculations. In this article, we are going to use the famous <a href="https://www.kaggle.com/c/titanic/data">Titanic data from Kaggle</a> and a Random Forest model to illustrate:</p><ul><li>Why you need a <strong>robust</strong> model and <strong>permutation importance</strong> <strong>scores</strong> to properly calculate feature importances.</li><li>Why you need to understand the <strong>features’ correlation</strong> to properly interpret the feature importances.</li></ul><p>The practice described in this article can also be generalized to other models.</p><h3>Best Practice to Calculate Feature Importances</h3><h4>The trouble with Default Feature Importance</h4><p>We are going to use an example to show the <strong>problem with the default impurity-based feature importances</strong> provided in Scikit-learn for Random Forest. The default feature importance is calculated based on the mean decrease in impurity (or Gini importance), which measures how effective each feature is at reducing uncertainty. See <a href="https://towardsdatascience.com/the-mathematics-of-decision-trees-random-forest-and-feature-importance-in-scikit-learn-and-spark-f2861df67e3">this great article</a> for a more detailed explanation of the math behind the feature importance calculation.</p><p>Let’s download the famous Titanic dataset from <a href="https://www.kaggle.com/c/titanic/data">Kaggle</a>. The data set has passenger information for 1309 passengers on Titanic and whether they survived. Here is a brief description of the columns included.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*YOJaoQIBR2dzenIWusxlSg.png" /></figure><p>First, we load the data and separate it into a predictor set and a response set. In the predictor set, we add two random variables random_cat and random_num. Since they are randomly generated, both of the variables should have a very low feature importance score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebc7ecbe7ad838ffdd74091477cbb3b6/href">https://medium.com/media/ebc7ecbe7ad838ffdd74091477cbb3b6/href</a></iframe><p>Second, we do some simple cleaning and transformation of the data. This is not the focus of this article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5028a0513b6f54ebafd76ded7d55150a/href">https://medium.com/media/5028a0513b6f54ebafd76ded7d55150a/href</a></iframe><p>Third, we build a simple random forest model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941490a8a880f419cd9a22d5f9193190/href">https://medium.com/media/941490a8a880f419cd9a22d5f9193190/href</a></iframe><pre>RF train accuracy: 1.000.</pre><pre>RF test accuracy: 0.814</pre><p>The model is slightly overfitting on the training data but still has decent performance on the testing set. Let’s use this model for now to illustrate some pitfalls of the default feature importance calculation. Let’s take a look at the default feature importances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/117629339c8d54a8045521bd34e66282/href">https://medium.com/media/117629339c8d54a8045521bd34e66282/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*RjpWU1ivU0p-IvWow2hphQ.png" /></figure><p>From the default feature importances, we notice that:</p><ul><li>The random_num has a higher importance score in comparison with random_cat, which confirms that <strong>impurity-based importances are biased towards high-cardinality and numerical features</strong>.</li><li>Non-predictive random_num variable is ranked as one of the most important features, which doesn’t make sense. This reflects the <strong>default feature importances are not accurate when you have an overfitting model</strong>. When a model overfits, it picks up too much noise from the training set to make generalized predictions on the test set. When this happens, the feature importances are not reliable as they are calculated based on the training set. More generally, <strong>it only makes sense to look at the feature importances when you have a model that can decently predict.</strong></li></ul><h4>Permutation Importance to Rescue</h4><p>Then how do we appropriately calculate the feature importances? One way is to use permutation importance scores. It’s computed with the following steps:</p><ol><li>Train a baseline model and record the score (we use accuracy in this example) on the validation set.</li><li>Re-shuffle values for one feature, use the model to predict again, and calculate scores on the validation set. The feature importance for the feature is the difference between the baseline in 1 and the permutation score in 2.</li><li>Repeat the process for all features.</li></ol><p>Here we leverage the permutation_importance function added to the Scikit-learn package in 2019. When calling the function, we set the n_repeats = 20 which means for each variable, we randomly shuffle 20 times and calculate the decrease in accuracy to create the box plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/142100b4e96f5ce4dc4ceb82977b5228/href">https://medium.com/media/142100b4e96f5ce4dc4ceb82977b5228/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSKQFh7DR5PG37phLEKKyw.png" /></figure><p>We see that sex and pclass show as the most important features and random_cat and random_num no longer have high importance scores based on the permutation importances on the test set. The box plot shows the distribution of the decrease in accuracy score with N repeat permutation (N = 20 in our case).</p><p>Let’s also compute the permutation importances on the training set. This shows that random_num and random_cat get a significantly higher importance ranking than when computed on the test set and the rankings of features look very different from the testing set. As noted before, it’s due to the overfitting of the model.</p><p>You may wonder why Scikit-learn still includes the default feature importance given it’s not accurate. Breiman and Cutler, the inventors of RFs, indicated that this method of “adding up the Gini decreases for each variable over all trees in the forest gives a fast variable importance that is often very consistent with the permutation importance measure.” So the default is meant to be a proxy for permutation importances. However, as Strobl et al pointed out in <a href="https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-8-25">Bias in random forest variable importance measures</a> that “the variable importance measures of Breiman’s original Random Forest method … are not reliable in situations where potential predictor variables vary in their scale of measurement or their number of categories.”</p><h4>A Robust Model is a Prerequisite for Accurate Importance Scores</h4><p>We’ve seen when a mode is overfitting, the feature importances generated from the training and prediction set could be very different. Let’s apply some level of regularization by setting min_samples_leaf = 20 instead of 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e0cc093845fd593fbe5047191be060f/href">https://medium.com/media/4e0cc093845fd593fbe5047191be060f/href</a></iframe><pre>RF train accuracy: 0.810</pre><pre>RF test accuracy: 0.832</pre><p>Now let’s look at feature importances again. After fixing the overfit, the feature importances calculated on the training and the testing set look much similar to each other. This gives us more confidence that a robust model gives accurate model importances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oszHnWX0yEwLGUIWokcYg.png" /></figure><p>An alternative way is to calculate <strong>drop-column importance</strong>. It’s the most accurate way to calculate the feature importances. The idea is to calculate the model performance with all predictors and drop a single predictor and see the reduction in the performance. The more important the feature is, the larger the decrease we see in the model performance.</p><p>Given the high computation cost of drop-column importance (we need to retrain a model for each variable), we generally prefer permutation importance scores. But it’s an excellent way to validate our permutation importances. The importance values could be different between the two strategies, but the order of the feature importances should be roughly the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a763a42fcbcc353646f026c07886e30/href">https://medium.com/media/3a763a42fcbcc353646f026c07886e30/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*AJkAzE9b5flyUmZcie74ag.png" /></figure><p>The rankings of the features are similar to permutation features although the magnitudes are different.</p><h3>Best Practice to Interpret Feature Importances</h3><h4>The Challenge of Feature Correlation</h4><p>After we have a robust model and correctly implement the right strategy to calculate feature importances, we can move forward to the interpretation part.</p><p>At this stage, correlation is the biggest challenge for us to interpret the feature importances. The assumption we make so far considers each feature individually. If all features are independent and not correlated in any way, it would be easy to interpret. However, if two or more features are collinear, it would affect the feature importance result.</p><p>To illustrate this, let’s use an extreme example and duplicate the column sex to retrain the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4628e50e8ab07137e1b0138cfe1f6ef6/href">https://medium.com/media/4628e50e8ab07137e1b0138cfe1f6ef6/href</a></iframe><pre>RF train accuracy: 0.794<br>RF test accuracy: 0.802</pre><p>The model performance slightly decreases as we added a feature that didn’t add any information.</p><p>We see now the importance of the sex features are now distributed between two duplicated sex columns. What happens if we add a bit of noise to the duplicated column?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*8smbm5kQIVavXlC2H0mv2A.png" /></figure><p>Let’s try adding random noise ranging from 0–1 to the sex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6020a1f7414a70bfd7fa3a87dc2d5b26/href">https://medium.com/media/6020a1f7414a70bfd7fa3a87dc2d5b26/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*gG4fAa_3miG0PqsOIEMAiw.png" /></figure><p>sex_noisy is now the most important variable. What happens if we increase the magnitude of noise added? Let’s increase the range of the random variable to 0–3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*c-kbYbclIIMmpT0dNmn5Bg.png" /></figure><p>Now we can see with more noise added, that sex_noisy now no longer ranks as the top predictor and sex is back to the top. The conclusion is that permutation importances computed on a random forest model <strong>spread importance across collinear variables</strong>. The amount of sharing appears to be a function of how much noise there is between the two.</p><h4>Dealing with Collinear Features</h4><p>Let’s take a look at the correlation between features. We use feature_corr_matrix from the rfpimp package, which gives us Spearman’s correlation. The difference between Spearman’s correlation and standard Pearson’s correlation is that Spearman’s correlation first converts two variables to rank values and then runs Pearson correlation on ranked variables. It doesn’t assume a linear relationship between variables.</p><pre>feature_corr_matrix(X_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*yGzaemMR30BA8oeUZAhVzw.png" /></figure><pre>from rfpimp import plot_corr_heatmap<br>viz = plot_corr_heatmap(X_train, figsize=(7,5))<br>viz.view()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*OOmwoC8PeGHGcKacQ344VA.png" /></figure><p>pclass is highly correlated with fare, which is not too surprising as class of cabin depends on how much money you pay for it. It happens quite often in business that we use multiple features that are correlated with each other in the prediction model. From the previous example, we see that when two or multiple variables are collinear, the importances computed are shared across collinear variables based on the information-to-noise ratio.</p><p><strong>Strategy 1: Combine Collinear Feature</strong></p><p>One way to tackle this is to combine features that are highly collinear with each other to form a feature family and we can say this feature family together ranks as the X most important. To do that, we will use the rfpimp package that allows us to shuffle two variables at one time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2e19810774c99d99a52288ff95b0431/href">https://medium.com/media/e2e19810774c99d99a52288ff95b0431/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*OLJUJV2boP-pDgeWJxVMjA.png" /></figure><p><strong>Strategy 2: Remove Highly Collinear Variable</strong></p><p>If a feature is dependent on other features, that means the features can be accurately predicted using all other features as independent variables. The higher the model’s R² is, the more dependent feature is, and the more confident we are that removing the variable won’t sacrifice the accuracy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4c04f330d94306c13641aae992d098/href">https://medium.com/media/ed4c04f330d94306c13641aae992d098/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*-Lj6RuZQdSgL_IgHRRoPyQ.png" /></figure><p>The first column dependence shows the dependence score. A feature that is completely predictable using other features would have a value close to 1. In this case, we can probably drop one of the pclass and fare without affecting much accuracy.</p><h3>At the End</h3><p>Once we 1)have a robust model and implement the right strategy to calculate permutation importance and 2)deal with feature correlation, we can start crafting our message to share with stakeholders.</p><p>For the common question people ask “Is feature 1 10x more importance than feature 2?”, you may understand at this moment that we have the confidence to make the argument only when all the features are independent or have very low correlation. But in the real world, that’s rarely the case. The recommended strategy is to assign features to the High, Medium, and Low impact tiers, without focusing too much on the exact magnitude. If we need to show the relative comparison between features, try to group collinear features (or drop them) to feature familiar and interpret based on the group to make the argument more accurate.</p><p>You can find the code in this article on <a href="https://github.com/luoyuweidu1/medium-articles/blob/main/Best%20Practice%20for%20Feature%20Importance.ipynb">my Github</a>.</p><h3>Reference</h3><p>[1] <a href="https://explained.ai/rf-importance/">Beware Default Random Forest Importances</a></p><p>[2]<a href="https://scikit-learn.org/stable/auto_examples/inspection/plot_permutation_importance.html">Permutation Importance vs. Random Forest Importance (MDI)</a></p><p>[3]<a href="https://github.com/parrt/random-forest-importances">Feature Importances for Scikit-Learn Machine Learning Models</a></p><p>[4]<a href="https://towardsdatascience.com/the-mathematics-of-decision-trees-random-forest-and-feature-importance-in-scikit-learn-and-spark-f2861df67e3">The Mathematics of Decision Tree, Random Forest Feature Importance in Scikit-learn and Spark</a></p><p>[5]<a href="https://towardsdatascience.com/explaining-feature-importance-by-example-of-a-random-forest-d9166011959e">Explaining Feature Importance by example of a Random Forest</a></p><p><em>All images unless otherwise noted are by the author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f0e11ee660" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/best-practice-to-calculate-and-interpret-model-feature-importance-14f0e11ee660">Best Practice to Calculate and Interpret Model Feature Importance</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[Boston Airbnb Listing Price Analysis]]></title>
            <link>https://medium.com/@stacyli0720/boston-airbnb-listing-price-analysis-392ffc2212e2?source=rss-3f589870d0fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/392ffc2212e2</guid>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Stacy Li]]></dc:creator>
            <pubDate>Sun, 14 Jun 2020 15:10:08 GMT</pubDate>
            <atom:updated>2020-06-14T15:10:08.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UL5TG5wDNDtyl9Ft.jpg" /></figure><h3>Introduction</h3><p>Airbnb is an online platform that allows homeowners to rent out their properties to earn extra money. It has now become a popular alternative to hotels as you can always find something that meets your budgets and it’s a good opportunity to make new friends. I love using Airbnb, especially when I travelled to exotic places and wanted an authentic sense of how local people live.</p><p>On Airbnb every property is unique, so the price of listings also vary greatly. I am curious about <strong>what is influencing the price of Airbnb listings. </strong>My intuition tells me neighborhoods play an important part as places near tourist attractions are usually more expensive . The capacity of property may be another factor because renting an entire apartment is more expensive than a shared room. I can easily name a few other candidates but as a data science the best way to answer this question is to see why data suggests. Therefore, I used <a href="https://www.kaggle.com/airbnb/boston">Airbnb Boston listings data from InsideAirbnb</a> to take a closer look at this question. The article will follow structure below:</p><ol><li>Overview of data</li><li>Data Cleaning</li><li>Data Exploration</li><li>Regression Modeling</li><li>Conclusions</li></ol><h4>Overview of Data</h4><p>The listing data has in total 3,585 observations and 95 columns. Each entry is a unique listing with attributes for the property, listing and host etc.</p><h4>Data Cleaning</h4><p>The first step is to drop columns that are not helpful:</p><ul><li>Urls or id — 12 columns</li><li>Have 100% missing rate or only have one distinct value — 14 columns</li><li>Text columns that require NLP to parse into features — 15 columns</li><li>Weekly price and monthly price since we are only interested in daily price — 2 columns</li><li>Have too many levels such as zip code — 4 columns</li></ul><p>This step removes a total of 47 columns and there are now 48 columns left. As a second step, we transform columns to the right data types including</p><ul><li>Convert columns in dollar values to integer</li><li>Convert columns in text percentage to float</li><li>Convert date string to date format and calculate the days difference to the date when the data was scraped</li><li>Convert binary columns to boolean format</li></ul><p>Next, we clean up amenities column, which is in JSON format to a list of binary columns to indicate whether a listing has certain amenity. After three steps of cleaning and transformation. The data has</p><pre>Number of columns with numeric values: 32<br>Number of columns with boolean values: 51<br>Number of columns with categorical values: 7</pre><p>Let’s now take a look at columns with missing values:</p><pre>security_deposit                    0.625662<br>cleaning_fee                        0.308787<br>review_scores_accuracy              0.229568<br>review_scores_location              0.229289<br>review_scores_value                 0.229010<br>review_scores_checkin               0.228731<br>review_scores_communication         0.228173<br>review_scores_cleanliness           0.228173<br>review_scores_rating                0.226778<br>days_since_first_review             0.210879<br>days_since_last_review              0.210879<br>reviews_per_month                   0.210879<br>host_response_time                  0.131381<br>host_response_rate                  0.131381<br>host_acceptance_rate                0.131381<br>bathrooms                           0.003905<br>bedrooms                            0.002789<br>beds                                0.002510<br>property_type                       0.000837<br>city                                0.000558</pre><p>There are 20 columns with at least one missing value and 12 columns with more than 20% missing values.</p><p>security_deposit and cleaning_fee are two columns with most missing values. They are missing because not every host requires security deposits and cleaning fees for their listings. So we set it to zero when it’s missing.</p><p>Another group of missing columns is review related columns. They are missing when the listing doesn’t have any review. We have a column that tracks number of reviews. <em>Number of reviews</em> is equal to zero whenever <em>review_scores_rating</em> is missing. Since <em>number of reviews</em> already capture the effect of missing reviews. We impute review_scores related feature with median.</p><h4>Data Exploration</h4><p>Explore Y variable — daily listing price</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*vAZ4dqbgO6wv3W9pCW3onQ.png" /></figure><p>We noticed some rental lists with extremely high price, which will throw off our model if we include. So let’s cap all the prices at 600.</p><p>Explore numerical variables:</p><p>Let’s first look at the correlation coefficient of each numerical variable with price.</p><pre>host_acceptance_rate             -0.157856<br>reviews_per_month                -0.148823<br>number_of_reviews                -0.111558<br>maximum_nights                   -0.006762<br>review_scores_value               0.000508<br>host_response_rate                0.000767<br>minimum_nights                    0.003263<br>review_scores_checkin             0.008297<br>review_scores_communication       0.015336<br>extra_people                      0.032293<br>review_scores_accuracy            0.051115<br>availability_365                  0.052005<br>days_since_first_review           0.070423<br>days_since_last_review            0.081618<br>review_scores_rating              0.095481<br>days_since_first_host             0.112185<br>availability_90                   0.143429<br>review_scores_cleanliness         0.143675<br>availability_60                   0.162602<br>review_scores_location            0.182837<br>availability_30                   0.185354<br>security_deposit                  0.197648<br>calculated_host_listings_count    0.232421<br>host_total_listings_count         0.244607<br>host_listings_count               0.244607<br>guests_included                   0.284972<br>bathrooms                         0.297528<br>cleaning_fee                      0.408446<br>beds                              0.470732<br>bedrooms                          0.489509<br>accommodates                      0.565760<br>price                             1.000000</pre><p>We can tell features with positive correlation with price tend to be size-related features such as how many people can the place accommodates, number of bedrooms and beds.It’s also surprising that acceptance rate and reviews per month are negatively correlated with price. My hypothesis is that home owners who set a lower price tend be less selective of guest profile and cheaper listings attract more guests as well so have more reviews in general.</p><p>Explore Numerical Variables:</p><p>Next, let’s pick a few variables to visualize as examples. Full exploration can be found <a href="https://github.com/luoyuweidu/Boston-Airbnb-Listing-Price-Study/blob/master/Airbnb-Boston.ipynb">here</a></p><pre>#feature related to size of the property<br>f, axes = plt.subplots(2,3, figsize=(20,7))<br>sns.set(style=&quot;whitegrid&quot;, palette=&quot;muted&quot;)<br>sns.boxplot(y=&#39;price&#39;, x=&#39;bedrooms&#39;, data = listings_merged, ax = axes[0][0])<br>sns.boxplot(y=&#39;price&#39;, x=&#39;bathrooms&#39;, data = listings_merged, ax = axes[0][1])<br>sns.boxplot(y=&#39;price&#39;, x=&#39;beds&#39;, data = listings_merged, ax = axes[0][2])<br>sns.boxplot(y=&#39;price&#39;, x=&#39;accommodates&#39;, data = listings_merged, ax = axes[1][0])<br>sns.boxplot(y=&#39;price&#39;, x=&#39;guests_included&#39;, data = listings_merged, ax = axes[1][1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbRpbWidLw3Qmhjco21DZw.png" /></figure><p>Price is in general positively correlated with number of bedrooms, bathrooms, beds, accommodates and guests.</p><p>Explore categorical variables:</p><p>Write a function to show the relationship between price and categorical var.</p><pre>def plot_cat_feature(variable, data = listings_merged):<br>    &quot;&quot;&quot;<br>    INPUT <br>    variable - name of categorical var to visualize<br>    data - dataframe that contain X and Y to visualize <br>    <br>    OUTPUT <br>    a boxplot visualization <br>    &quot;&quot;&quot;<br>    plt.figure(figsize=(20,5))<br>    sort_order = listings_merged\<br>                .groupby(variable)[&#39;price&#39;]\<br>                .median()\<br>                .sort_values(ascending=False)\<br>                .index<br>    sns.boxplot(y=&#39;price&#39;, x=variable, data = data, order = sort_order)<br>    ax = plt.gca()<br>    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha=&#39;right&#39;);</pre><pre>plot_cat_feature(&#39;neighbourhood_cleansed&#39;, listings_merged)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GPVDzGldvJM8VvFN4c1mw.png" /></figure><p>Prices see great variation in different neighborhoods.</p><pre>neighborhoods.plot_cat_feature(&#39;city&#39;, listings_merged)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tx0UnqQDBfBfHpXcLNrXrw.png" /></figure><p>The city variable is not very clean. Let’s drop it since we already have neighborhood.</p><h4>Regression Modeling</h4><p>To prepare data for regression, we need to convert categorical variables into dummies and create training and testing set</p><pre>from sklearn.cross_validation import train_test_split</pre><pre>#create dummy columns from categorical variables<br>category_dummies = pd.get_dummies(listings_merged.select_dtypes(include = [&#39;object&#39;]))</pre><pre>listings_final = pd.concat([listings_merged.select_dtypes(exclude = [&#39;object&#39;]),category_dummies],axis = 1)</pre><pre>X = listings_final.drop(&#39;price&#39;, axis=&#39;columns&#39;)<br>Y = listings_final[&#39;price&#39;]</pre><pre>#split training and testing test <br>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state = 31)</pre><pre>print(&#39;Training Set Size:&#39;, X_train.shape)<br>print(&#39;Training Set Size:&#39;, X_test.shape)</pre><pre>Training Set Size: (2509, 136)<br>Training Set Size: (1076, 136)</pre><p>It’s easier to create a function to fit regression model so we can reuse it later. In this case, we use Lasso model since the dataset has 136 columns and only 2509 rows of training. Using lasso can help us avoid overfitting and drop useless predictor</p><pre>from sklearn.linear_model import Lasso<br>def get_lasso_model_result(X_train, X_test, y_train, y_test, alpha, normalize = True):<br>    &quot;&quot;&quot;<br>    INPUT<br>    X_train - predictors from training set <br>    X_test - predictors from testing set<br>    alpha - alpha parameter for lasso model,<br>    normalize - if normalize input data<br>    <br>    OUTPUT<br>    A list of rmse and r^2 from training and testing set as well as featured ended up in model for a given alpha.<br>    <br>    This function is to build a lasso model for each given parameter and record the model evaluation metrics <br>    as well as number of features used in a list<br>    <br>    &quot;&quot;&quot;<br>    <br>    #build a lasso model with given parameters<br>    lasso = Lasso(alpha=alpha, max_iter=10e5, normalize = normalize)<br>    lasso.fit(X_train, y_train)<br>    <br>    #prediction<br>    y_train_pred = lasso.predict(X_train)<br>    y_test_pred = lasso.predict(X_test)<br>    <br>    #RMSE<br>    mse_train = sklearn.metrics.mean_squared_error(y_train, y_train_pred)<br>    mse_test = sklearn.metrics.mean_squared_error(y_test, y_test_pred)<br>    root_train_mse = mse_train**(1/2)<br>    root_test_mse = mse_test**(1/2)<br>    <br>    #R^2<br>    r_squared_train = sklearn.metrics.r2_score(y_train, y_train_pred)<br>    r_squared_test = sklearn.metrics.r2_score(y_test, y_test_pred)<br>    <br>    <br>    #number of features used <br>    coeff_used = np.sum(lasso.coef_!=0)<br>    <br>    return [root_train_mse, root_test_mse, r_squared_train, r_squared_test, coeff_used]</pre><p>Let’s try different alpha value to see which one works the best.</p><pre>alpha_range = [0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1]<br>results = dict()</pre><pre>for alpha in alpha_range:<br> results[str(alpha)] = get_lasso_model_result(X_train, X_test, y_train, y_test, alpha, True)</pre><pre>plt.figure(figsize=(14, 4))</pre><pre>#plot rmse plot<br>plt.subplot(121)<br>plt.title(&#39;RMSE by alpha&#39;)<br>plt.plot([key for key, value in results.items()], [value[0] for key, value in results.items()])<br>plt.plot([key for key, value in results.items()], [value[1] for key, value in results.items()])</pre><pre>#plot r^2 plot<br>plt.subplot(122)<br>plt.title(&#39;R^2 by alpha&#39;)<br>plt.plot([key for key, value in results.items()], [value[2] for key, value in results.items()])<br>plt.plot([key for key, value in results.items()], [value[3] for key, value in results.items()])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*z1XuY4ZI89oRTCgZ0BXCow.png" /></figure><pre>Optimal Alpha for the model is: 0.01<br>Optimal RMSE for the testing set is: 0.604582555123<br>Number of features in optimal model: 104</pre><p>Let’s fit the model again with the optimal alpha value.</p><pre>lasso = Lasso(alpha=0.01, max_iter=10e5, normalize = True)<br>lasso.fit(X_train, y_train)<br>coefs = sorted(list(zip(listings_final.drop(&#39;price&#39;, axis=&#39;columns&#39;).columns,lasso.coef_)), key=lambda x:x[1], reverse = True)</pre><pre>coefs = sorted(list(zip(listings_final.drop(&#39;price&#39;, axis=&#39;columns&#39;).columns,lasso.coef_)), key=lambda x:x[1], reverse = True)</pre><pre>coefs_df = pd.DataFrame(coefs, columns = [‘cariable’,’coefs’])<br>coefs_df[‘abs_coefs’] = np.abs(coefs_df[‘coefs’])</pre><p>Now let’s look at top 10 predictors with largest absolute coefficients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*HC14kvzgZ1NQyHA_A_Huwg.png" /></figure><p>Now answers to our questions become clearer. From the absolute coefficients of the lasso model, we can tell property type, room type, neighborhood and amenities are the top predictors. Although strict cancellation policy also shows up as top predictor, it seems to be the result of high price of listing. Hosts need to endure greater loss if expensive listings get cancelled.</p><p>It’s surprising to me that RVs tend to have a lower price than normal listings and I didn’t even know you can rent a boat on Airbnb.</p><p>In terms of amenities, Washer/Dryer is the only one that made it to the top 10 list. Listings with washer/dryer on average are $91 more expensive than the listing without them. Washer/Dryer certainly add value to the listing themselves but I think it’s also because washer/dryer are more likely to exist in new apartments or houses, which are usually more expensive.</p><p>South Boston Waterfront is the most expensive neighborhood, followed by Back Bay, Beacon Hill and Bay Village.</p><p>Entire home/apt also tends to have a higher price, which makes a lot of sense.</p><p><strong>I’m also interested in price variation by neighborhood. </strong>Let’s take a detailed look at the coefficient by neighborhood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HC11kgTjpNAGImHl5wo-w.png" /></figure><p>We can well neighborhoods near downtown and Boston harbor area have the most expensive listings while city that are farther away from city center such as Rosilindale, West Roxbury and Mattapan have the cheapest listings.</p><p><strong>Another question I have in mind is which amenities are adding the most value to the listing? </strong>Let’s take a detailed look at the coefficient by amenities as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjKjn02bti-xPIykF9zykg.png" /></figure><p>Top 5 amenities that add value to the listings are Washer/Dryer, Doorman, AC, WIFI and indoor fireplace. Top 5 amenities with negative effect on the listing prices are Other pets(s), free parking on the street, kitchen, hangers, and free parking on premises. These are an interesting case. Sometimes what a host chooses to list as an amenity is a signal about the “class” of the listing. One example is hanger. We usually just assume every listing has hangers; hosts who choose to list them as a “feature” anyway bring up the shade of not having such a rather basic necessity, which actually signals a lower price.</p><h3>Conclusion</h3><p>In this article, we explored factors that influence Boston Airbnb prices by using regression model and data visualization.</p><ol><li>We used Lasso Regression to model the Airbnb price and revealed the most important factors by looking at normalized coefficient. The results shows that <strong>property type, room type, neighborhood and amenities </strong>are the top predictors.</li><li>We also took a detailed look at price variation by neighborhood, which shows that <strong>neighborhoods near downtown and Boston harbor area have the most expensive listings</strong> while city that are farther away from city center such as Rosilindale, West Roxbury and Mattapan have the cheapest listings. A listing in South Bay on average can be $100 more than one in Rosilindale.</li><li>Lastly, we looked which amenities are adding the most values to the listings. Top 5 amenities that add value to the listings are Washer/Dryer, Doorman, AC, WIFI and indoor fireplace.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=392ffc2212e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>