<?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 Gustaf Halvardsson on Medium]]></title>
        <description><![CDATA[Stories by Gustaf Halvardsson on Medium]]></description>
        <link>https://medium.com/@gustaf.halvardsson?source=rss-4cd4e8d2b9b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PsPEMlAiLCpXWlXJ9nScBA@2x.jpeg</url>
            <title>Stories by Gustaf Halvardsson on Medium</title>
            <link>https://medium.com/@gustaf.halvardsson?source=rss-4cd4e8d2b9b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:16:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gustaf.halvardsson/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[Applying Transformers to Score Potentially Successful Startups]]></title>
            <link>https://medium.com/motherbrain/applying-transformers-to-score-potentially-successful-startups-7893284efb01?source=rss-4cd4e8d2b9b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7893284efb01</guid>
            <category><![CDATA[timeseries-classification]]></category>
            <category><![CDATA[venture-capital]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[gated-recurrent-unit]]></category>
            <dc:creator><![CDATA[Gustaf Halvardsson]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 12:19:23 GMT</pubDate>
            <atom:updated>2023-09-04T20:09:04.718Z</atom:updated>
            <content:encoded><![CDATA[<h4>An experimental study promoting the use of fine-grained multivariate time series</h4><p>As investment firms aim to invest in promising companies, they constantly face the critical task of estimating the chance of success for these. In Venture Capital, this task is often referred to as Startup Success Prediction (SSP).</p><blockquote>“Finding the most promising, likely-to-succeed startups for early-stage investment is the holy grail of data-driven Venture Capital. We work with this continuously at EQT Ventures and Motherbrain, but using models for it is difficult: startup data is sparse and noisy, and the rare successes can only be proven years after the initial funding rounds. Additionally, the definition of success changes over time. For a prediction model to be resistant, it needs to identify the constant, underlying signals that stand the test of time and universally define successful early-stage companies.”</blockquote><p><em>– Anton Ask Åström, Analytics Lead, EQT Ventures</em></p><h3>Startup success prediction as a Deep Learning problem</h3><p>Traditionally, Venture Capital firms have mostly relied on analytical, statistical, or manual methods for sourcing new startup deals, but recently Deep Learning (DL) has been increasingly utilized for this task. One reason is the complexity of the task requires making predictions based on incomplete information — mostly due to startups lacking a lot of public information in their early stages.</p><p>Additionally, the correlations and signals indicating success may exist in dramatically different configurations, depending on the startup in focus. Therefore, a DL-based method needs to be able to successfully model complex correlations amongst the input features and often correlations between numerous different input features to compensate for the data shortage. These DL-based methods are also able to sift through magnitudes more data compared to their non-DL alternatives.</p><p>Adding more complexity to the SSP problem is the importance of time. A performant method should be <em>phase-agnostic</em> meaning it finds a potentially successful startup <em>regardless</em> of which phase the startup is in at the time of evaluation. Therefore, even if the successful startup has just been founded, or is just in the process of entering a growth phase, it should be correctly identified.</p><p>To summarize, SSP as a DL problem has the following three challenges:</p><ol><li>Sparse and noisy data from many different data sources.</li><li>Requires strong representation learning capability on complex and diversified data.</li><li>Identifying startups needs to be done in a phase-agnostic way.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gnq01i2ZTZkYSLje" /><figcaption>A proposed general pipeline overview for SSP. The labels are binary (0/1) and provided by investment professionals on a per-company basis. The professionals will in turn receive scores for other unlabeled companies through the DL model.</figcaption></figure><h3>The considerations around using temporal features</h3><p>Capturing the temporal correlations between different features is important for the SSP problem. Therefore, many existing methods utilize specifically time series — a sequence of values. With time series data, the prediction can be potentially guided by the time, order, and frequency of these sequential values, which is an important characteristic of SSP.</p><p>In the past, statistical methods have been surprisingly dominant within the field of Time Series Classification, and it is only recently that DL-based methods such as the Convolutional Neural Network (CNN), Long Short-Term Memory (LSTM), or Gated Recurrent Unit (GRU) have been catching up in terms of performance. This can be observed specifically within the context of <em>multivariate</em> time series classification, where the complexity of the problem increases. Unlike <em>univariate</em> time series classification, the model needs to capture patterns across multiple time series, and in return hopefully yield improved performance. A univariate structure could also be extended to include <em>multiple</em> time series features separately, a common solution if the time series features that are available do not have the same frequency.</p><p>Another consideration for SSP is the choice of evaluation strategy. We previously mentioned the challenge of correctly identifying startups regardless of the phase in their lifecycle. To address this, one can opt for an <a href="https://arxiv.org/abs/2210.14195">investor-centric data split strategy</a> — replacing the traditional random sampling strategy. Concretely, we extrapolate a single sample into multiple samples (each representing the company at different stages in time), and build the evaluation dataset on only the most recent samples. As a result, the model is expected to act phase-agnostically while it also better resembles the real-world usage of the model by investment professionals.</p><h3>Transformer for time series classification</h3><p>In a <a href="https://dl.acm.org/doi/10.1145/3447548.3467401">paper from 2021</a>, the authors presented a Transformer-based method and architecture, called the TST, for multivariate time series classification. The architecture showed promising results on public time series datasets, even outperforming state-of-the-art statistical and DL-based methods. However, the TST had yet to be adapted and tested on real-world data with all the accompanying challenges, specifically within the investment domain.</p><p>This is where we at Motherbrain saw the potential to improve our existing scoring models. By focusing solely on time series features from a variety of data sources — and the labels from our in-house investment professionals — the TST architecture was modified and implemented to potentially further improve our scoring models.</p><h3>Performance comparison</h3><p>When trained and evaluated on the labeled EQT dataset, several interesting results emerged. Firstly, a Univariate GRU model was implemented where each time series feature was given a <em>separate </em>GRU block. Additionally, a Multivariate GRU was implemented, where all features share one common GRU block. This was done to help determine if any improvements observed were due to the Transformer, or just the introduction of multivariate learning itself.</p><p>In our testing, the TST model showed a <strong>12% increase</strong> in test performance (from 0.81 to 0.92 AUC) compared to the Multivariate GRU and as much as a <strong>47% increase</strong> (0.62 AUC) compared to the Univariate GRU. The model was also tested on two public datasets from the public UCR archive (<a href="https://www.timeseriesclassification.com/description.php?Dataset=EthanolConcentration">Ethanol</a> and <a href="http://www.timeseriesclassification.com/description.php?Dataset=PEMS-SF">PEMS-SF</a> datasets). The purpose was to gain even more insights into how the model performs for different datasets. The TST once again showed <strong>the highest average accuracy across these datasets</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ahOAO0_POJzm57h-" /><figcaption>Performance of the different architectures across the three different datasets. PEMS could not be measured for the Univariate GRU since it would be computationally infeasible.</figcaption></figure><p><strong>Training Times<br></strong>Additionally, the cost of increased training times for TST was limited. While the GRU is the simplest architecture computationally, only a 4x increase in training times was observed for TST compared to the Multivariate GRU. Furthermore, for the Univariate GRU, the <strong>TST even <em>decreased</em> its training times by over 15x. </strong>Furthermore<strong>, </strong>the multi-head attention mechanism of the Transformer allows the network to parallelize its computations on modern GPUs to decrease its training times and therefore makes it possible to train models on dramatically larger datasets.</p><p><strong>Training Stability</strong><br>While the Transformer is known to be potentially difficult and unstable to train, we did not encounter these issues. In fact, the <strong>TST was the most stable out of all four models</strong>, delivering the lowest standard deviation amongst different training runs.</p><h3>Other potential benefits</h3><p>Besides achieving higher prediction performance, the Transformer can bring other potential advantages to the table as well.</p><p><strong>Better explainability</strong><br>The attention mechanism inherently produces a weighted matrix of how its weights are distributed along the input sequence. Therefore, one can gain insights, on an instance level, into what parts of the sequence the model focuses on, and in turn, achieve a higher explainability of the model as a whole.</p><p><strong>Embeddings utilization</strong><br>Through its use of the Encoder-Decoder architecture, it inherently uses embeddings and is therefore more effectively integrated with, for example, a language model to achieve a multimodal architecture. Additionally, the embeddings learned by the model can be used for other downstream tasks.</p><p><strong>Unsupervised learning capability</strong><br>A large contribution of the original TST paper was the introduction of an unsupervised masked learning routine. By masking parts of the time series sequences, and training the network to predict the masked part, the model will theoretically learn a more effective representation before being fine-tuned on labeled data. While not thoroughly tested yet by us, this approach could drive the most potential, since it would allow the model to train on the considerably more abundant and cheaper unlabeled data.</p><h3>Final words</h3><p>By its nature, SSP is a complex problem that requires sifting through massive, but sparse, amounts of data to find the startups in the world that show real potential. We at EQT have long seen the potential in aiding this through our data-driven platform Motherbrain and its scoring models.</p><p>The TST we explored shows the promise of Transformer-based models for SSP in the future where the results suggest it to be a performant alternative to the GRU architecture for multivariate time series classification in the investment domain. The architecture can also easily be generalized to work in other investment contexts such as the Growth and Private Equity funds and therefore provide some exciting future possibilities.</p><p>You can read more about the full project and its details <a href="https://www.diva-portal.org/smash/record.jsf?dswid=-1739&amp;pid=diva2%3A1757497&amp;c=3&amp;searchType=SIMPLE&amp;language=en&amp;query=gustaf+halvardsson&amp;af=%5B%5D&amp;aq=%5B%5B%5D%5D&amp;aq2=%5B%5B%5D%5D&amp;aqe=%5B%5D&amp;noOfRows=50&amp;sortOrder=author_sort_asc&amp;sortOrder2=title_sort_asc&amp;onlyFullText=false&amp;sf=all">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7893284efb01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motherbrain/applying-transformers-to-score-potentially-successful-startups-7893284efb01">Applying Transformers to Score Potentially Successful Startups</a> was originally published in <a href="https://medium.com/motherbrain">Motherbrain</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Science approach to Stockholms Apartment Prices]]></title>
            <link>https://medium.com/data-science/a-data-science-approach-to-stockholms-apartment-prices-part-2-13e51772b528?source=rss-4cd4e8d2b9b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e51772b528</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[se-apartment-project]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[stockholm]]></category>
            <dc:creator><![CDATA[Gustaf Halvardsson]]></dc:creator>
            <pubDate>Sun, 22 Dec 2019 10:36:54 GMT</pubDate>
            <atom:updated>2020-01-23T18:28:57.863Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://medium.com/tag/se-apartment-project">SE Apartment Project</a></h4><h4>Turning data into insights and predictors with Machine Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMcXpx3Bj1Jb_1l7GtBfRg.png" /></figure><h3>The goal of this story and a recap of the last story.</h3><p>In <a href="https://medium.com/@gustaf.halvardsson/a-data-science-approach-to-stockholms-apartment-prices-part-1-dcee0212596d">the previous story</a>, we explored how we could acquire and clean data. While the cleaning and filtering took a lot longer than expected, we ended up with a sparkly clean dataset. To jock your memory, we now have this as our dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f0K6OEV-XC6LE3Ql.png" /><figcaption>Sample of 5 out of 14 171 apartment listings with 9 different features.</figcaption></figure><h3><strong>Splitting the data for validation.</strong></h3><p>We have roughly 14 000 entries in our dataset which will serve great to train our ML-model. To train our model, we need a lot of data, so-called <em>training</em> <em>data</em>. But to check the performance of our model we will also require data, so-called, <em>validation data. </em>Here the balance is important since if we have too few lines of training data, our model will not be able to train on enough data and be accurate. On the flip side, if we do not have enough lines of validation data we can’t be as certain of our model&#39;s accuracy when we later test it. <em>Note: We could also use Cross-Validation but because we have a good amount of data, the gain would be minimal.</em></p><p>For these reasons I chose to do a 3/4 split of the data, meaning 75% of lines go towards training and 25% towards validation.</p><h3>Building the Machine Learning Model.</h3><p>The first step to training my Machine Learning (ML) model is considering the features I should include which is also important. From intuition and previous knowledge of apartments I decided to choose: <strong>‘Date<em>‘, Size’, ‘NearbyPOIs’, ‘Rooms’, ‘Latitude’, </em></strong>and<strong><em> ‘Longitude’. </em></strong>Choosing the correct features to include and exclude will be very important for our model&#39;s performance so we will return to tune this later. But let&#39;s start with this and see where we end up.</p><h3><strong>How to model it</strong></h3><p>This problem will be a regression-task and is probably very prone to overfitting. Therefore I ultimately decided to use a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html"><strong><em>Random Forest Tree Regressor</em></strong></a>. Because it’s an <em>ensemble</em> method (a method that uses the average of different evaluations) it works very well to counter overfitting and usually produces a very good result with little tuning of its hyperparameters.</p><p>Because it’s a decision-tree model, we also do not need to normalize the data to avoid that certain features take more precedence than others.</p><p>We now train the model with our training-data and let&#39;s test it against the validation data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*3huzHqsi3itRFtS7yAUYkw.png" /><figcaption>I wrote a function that calculates the accuracy in <a href="https://en.wikipedia.org/wiki/Mean_absolute_error">Mean Absolute Error</a> or <a href="https://en.wikipedia.org/wiki/Mean_absolute_percentage_error">Mean Absolute Error Percentage</a>. Follow the links if you want to learn more but the short story for both measurements is that the closer to 0, the better.</figcaption></figure><p>Hmm not exactly a great predictor for apartment pricing. What this means is that <strong>our model&#39;s predictions will be, on average, 24% or over 1 000 000 million SEK off</strong>. We can definitely improve this. So how do we optimize this?</p><h3>Feature Engineering and Optimizations</h3><p>I plotted the correlations of the features to discover which features are best to include using our trained model and its features.</p><pre>feat_importances = pd.Series(trainedModel.feature_importances_, <em>index</em>=trainFeatures.columns)<br>feat_importances.nlargest(numOfFeatures).plot(<em>kind</em>=&#39;barh&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fo96oUqhQv6R3ExQS-BKrw.png" /><figcaption>Which feature that has the biggest impact on the price. The higher the value, the bigger the impact. This means Size affects the pricing the most.</figcaption></figure><p>I ultimately decided to choose: <strong><em>‘Size’, ‘NearbyPOIs’, ‘Latitude’, </em></strong>and<strong><em> ‘Longitude’ </em></strong>because they had the biggest impact on the Price which you can see in the graph here.</p><p>I left out Rent since where a situation where we know the Rent but not the Price, or vice-versa, did not seem necessary to include.</p><p>There are a ton of optimizations to be made that I used in this instance, but that is out-of-scope for this article. However, after these optimizations, we ended up with the following performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*nGmKjt6dfFTHAzeaKgJ14w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Evd5zpHfk7B8IXLczn_3Yw.png" /><figcaption>Shows how close the predictions were to actual pricing (in SEK). X-Axis: What the prediction model predicted the price would be. Y-Axis: Actual Price for the apartment. Each dot represents one apartment listing and the red line is the linear fit of all predictions.</figcaption></figure><p>Much better, <strong>where our model can predict the sale price, on average 390 000 SEK or 8.4 % within the actual price.</strong></p><p>Something interest to note here is that for this accuracy, we only use 4 features: <em>‘Size’, ‘NearbyPOIs’, ‘Latitude’ </em>and<em> ‘Longitude’ </em>to get this good of an accuracy. Since NearbyPOIs, Latitude, and Longitude all come from the Adress, <strong>we only in reality need 2 features.</strong> Why is this impressive?<strong> It means our model only needs apartments Size and Adress to have an accuracy of 91.6%.</strong></p><p><strong><em>Why don&#39;t we just give the model all of the features?</em> <em>The more the better, right?</em></strong><em><br></em>No, doing this usually causes overfitting — where the model learns the training data too well, meaning noise and outliers is also included in its predictions, rather than learning a general formula, which is what we are looking for.</p><h3>Conclusion: Turning Data into Insights.</h3><p>At this point, we have clean and organized data and an ML-model that predicts the sale price. To conclude this study, I want to summarize what useful insights that gave us.</p><p>Let&#39;s start with the actual data. This is a summarization of all rows of data we have. It shows amongst other things <strong>the mean, standard deviation, max- and min value </strong>in our data for all 9 features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y2UJj31D8-FVdrydkS-BA.png" /><figcaption>Summary of 14 171 rows of data.</figcaption></figure><p>With the assumption that <em>the data available from Hemnet is representative of the apartment market in Stockholm</em>, we can conclude that <strong>for apartments in Stockholm:</strong></p><ul><li>The median price is 3.9 million SEK.</li><li>The median rent is 2 800 SEK.</li><li>The median number of rooms is 2.</li></ul><p>Furthermore, we can compare the relationship between all the features (their correlations) to learn even more how each feature affects each other, not just the pricing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48q1XIC5w_KrNjmZVyr8dw.png" /><figcaption>Shows how much each feature is dependent on each other. For example, the Size is entirely dependent on itself, so its value is 1 (green). The lower (red, -1) or higher (green, 1) the value, the more dependency.</figcaption></figure><p>From this graph, we can see things that might not be surprising, that Rooms is very dependent on Size. But we can also conclude some things we may not have known before about apartments in Stockholm:</p><ul><li>The <em>longitude</em> is significantly dependent on NearbyPOIs. Meaning: the <strong>number of interesting places nearby</strong>(restaurants, bars, schools, etc. that are interesting according to Yelp) <strong>depends on whether you live in West or East Stockholm, where east Stockholm has more NearbyPOIs.</strong></li><li>PricePerKvm is <strong><em>twice </em></strong>as dependent on Longitude as Latitude. Meaning<strong> if you live in East Stockholm, your apartment is likely to be more expensive.</strong></li></ul><p>There are tons, of course, more connections to be made but these were my personal favorites.</p><p>Lastly, I would like to return to this correlation graph again, which showed how much of an impact each feature has on Price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fo96oUqhQv6R3ExQS-BKrw.png" /><figcaption>Which feature that has the biggest impact on the price. The higher the value, the bigger the impact. This means Size affects the pricing the most.</figcaption></figure><p>An insight that I found the most surprising is just how small of an impact Number of Rooms has on the pricing. Meaning:</p><ul><li><strong>The pricing of an apartment is not significantly different whether it has an extra room or two.</strong> It is mostly the Size in Square Meters that matters in this context.</li></ul><p>We can also conclude from this graph that <strong>Size, NearbyPOIs and Latitude, and Longitude are the features that affect the Price the most. </strong>Three of these are all entirely dependent on the location. Meaning:</p><ul><li><strong>Location is everything</strong> and will dramatically affect the pricing.</li></ul><p>To show just how the pricing varies in Stockholm I decided to show this visually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMcXpx3Bj1Jb_1l7GtBfRg.png" /><figcaption>Shows the geographical positions of the most expensive apartments. X-Axis: Latitude, Y-Axis: Longitude, Z-Axis: Sales Price / Square Meters (SalePricePerKvm)</figcaption></figure><p>As you can see, a pattern does exist. The highest point (yellow) as you can see there are coordinates for in the middle of Östermalm.</p><h3>Key Takeaways from this case study</h3><p>For apartments in Stockholm:</p><ul><li>The <strong>median price </strong>is 3.9 million SEK.</li><li>The <strong>median rent</strong> is 2 800 SEK.</li><li>The <strong>median number of rooms</strong> is 2.</li><li>The <strong>number of interesting places nearby </strong>(restaurants, bars, schools, etc. that are interesting according to Yelp) <strong>depends on whether you live in west or east Stockholm</strong>, where <strong>east Stockholm has more interesting places.</strong></li><li>If you live in <strong>east Stockholm</strong>, your <strong>apartment is likely to be more expensive.</strong></li><li>The pricing of an apartment is <strong>not significantly different</strong> <strong>whether it has an extra room or two if it does not add more square meters.</strong></li></ul><p>Read the previous story here:<br><a href="http://medium.com/p/dcee0212596d/"><strong><em>Acquiring and cleaning data with Web Scraping.</em></strong></a></p><p>All source code is available here:<br><a href="https://github.com/gustafvh/Apartment-ML-Predictor-Stockholm_-with-WebScraper-and-Data-Insights"><strong>https://github.com/gustafvh/Apartment-ML-Predictor-Stockholm_-with-WebScraper-and-Data-Insights</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e51772b528" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-data-science-approach-to-stockholms-apartment-prices-part-2-13e51772b528">A Data Science approach to Stockholms Apartment Prices</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[A Data Science approach to Stockholms Apartment Prices]]></title>
            <link>https://medium.com/data-science/a-data-science-approach-to-stockholms-apartment-prices-part-1-dcee0212596d?source=rss-4cd4e8d2b9b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcee0212596d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[se-apartment-project]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gustaf Halvardsson]]></dc:creator>
            <pubDate>Thu, 19 Dec 2019 18:59:42 GMT</pubDate>
            <atom:updated>2019-12-23T16:10:43.464Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://medium.com/tag/se-apartment-project">SE Apartment Project</a></h4><h4>Acquiring and cleaning data with Web Scraping in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EWVubGKGoYvtCQgC" /></figure><h3><strong>Project Background</strong></h3><p>Being considered one of the most overpriced housing markets in the world, I figured the apartment market in Stockholm would serve as an interesting case study with a lot of interesting data available. To transform a large portion of data into useful insights that are easy to understand and make a model that predicts the sale price of future apartment listings.</p><p>I also decided to make sure to approach this problem in the way a Data Scientist would approach it with some of the head-aches and challenges a real-situation would present. This means I want to challenge myself in transforming the data that is available, into clean data that can actually be used.</p><p><em>Note: Usually this role would include being presented a specific goal that would benefit the business. But in this case, I have chosen to take a very general approach where I don’t know yet what patterns I might be looking for.</em></p><blockquote>“A data scientist is someone who can <strong>obtain, scrub, explore, model,</strong> and <strong>interpret data,</strong> blending <strong>hacking, statistics, and machine learning</strong>. Data scientists not only are adept at working with data, <a href="https://www.dezyre.com/article/data-scientist-skills-must-haves/134">but appreciate data itself as a first-class product</a>.” — <a href="https://hilarymason.com/about/"><em>Hillary Mason</em></a><em>, founder, Fast Forward Labs.</em></blockquote><p>Read the next part of this project here:<br><a href="https://medium.com/p/13e51772b528/"><strong><em>Turning data into insights and predictors with Machine Learning.</em></strong></a></p><p>All source code is available here:<br><a href="https://github.com/gustafvh/Apartment-ML-Predictor-Stockholm_-with-WebScraper-and-Data-Insights"><strong>https://github.com/gustafvh/Apartment-ML-Predictor-Stockholm_-with-WebScraper-and-Data-Insights</strong></a></p><h3><strong>Project Goals</strong></h3><p>1. To <strong>gather real-life data</strong> that is available online and be able to <strong>collect, clean and filter it</strong> into a dataset of both good quality and quantity. <strong>No shortcuts with squeaky-clean Kaggle-datasets this time.</strong></p><p>2. Based on data gathered, <strong>make a Machine Learning model</strong> which — based on relevant f<strong>eatures such as size, number of rooms, and location </strong>— makes an accurate guess on its sale-price with a <em>feasible accuracy</em> such that it would actually be considered useful.</p><p>3. <strong>Turn all data I’ve collected into insights</strong> that hopefully teach me <strong>something surprising or useful</strong> about the Stockholm housing market.</p><h3><strong>Special tools used</strong></h3><ul><li><strong>Python</strong>: Entire project is written in Python because of its large support for libraries in this area</li><li><a href="https://selenium.dev/"><strong>Selenium</strong></a><strong> (Python): </strong>Popular end-to-end testing software for executing the Web Scraping program in Chrome.</li><li><a href="https://pandas.pydata.org/"><strong>Pandas</strong></a><strong> &amp; </strong><a href="https://numpy.org/"><strong>Numpy</strong></a><strong>: </strong>Python libraries for easy-to-use data structures and data analysis tools.</li><li><a href="# https://www.yelp.com/developers/documentation/v3/business_search"><strong>Yelp API</strong></a><strong>: </strong>API to receive nearby Points-of-interests as well as coordinates based on an address.</li><li><a href="https://seaborn.pydata.org/"><strong>Seaborn</strong></a><strong> &amp; </strong><a href="https://matplotlib.org/"><strong>Matplotlib</strong></a><strong>:</strong> Data visualization libraries for Python meant to show our results visually.</li></ul><h3>Acquiring Good and Plentiful Data.</h3><p>To even begin this project, I need <em>good</em> data. Good data in this sense means it fulfills mainly two requirements, quality and quantity. For the quality, it is important that our data has different attributes (features) that are relevant to what I want to know and predict. If I want to predict the sale price of an apartment, good features would, for example, be the <em>size of the apartment</em>, its <em>location</em>, <em>number of rooms</em>, <em>when it was sold</em>, etc.</p><p>I can find all of this data available at Hemnet, a Swedish listing site for apartments so that&#39;s where I decided to use the data from.</p><p><strong><em>Very important about web scraping: </em></strong><em>In my case, I will in no way use this as a commercial product or for any monetary gain but always respect other people&#39;s or companies&#39; data and make sure you always double-check what applies when it comes to web-scraping to not infringe on copyright.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JeIUls9xJpKlXCFTERKTag.gif" /><figcaption>Demo of how my Selenium Web Scraper works by automatically controlling an instance of Chrome.</figcaption></figure><p>In short, the Web Scraper works by opening a Chrome browser window, navigate to Hemnets Stockholm listings, get all apartment-listings on that page and navigate to the next page to repeat the process.</p><p>Some problems I encountered and luckily solved:</p><ul><li><strong>Hemnet restricts listings to 50 pages per search query. </strong>I used this as an opportunity to get an <em>even spread of data amongst the size of the apartments.</em> I split my scraping-jobs into querying 20 segments, each corresponding to a specific size of apartments that I then tell the Scraper to get for me. For ex. one segment is all apartments with a size between 20 and 25 square meters. This resulted in me getting:<br><strong>50 listings per page * 50 pages * 20 segments = 50 000 listings<br></strong>Now I also have a better data-spread than before so that turned out great!</li></ul><pre>segments = [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 250]</pre><pre><em>for</em> i in range(0, (len(segments)-1)):<br>driver = initCrawler(segments[i], segments[i+1])apDataNew =           getRowsFromHnet(driver, 50)<br>apData = apData.append(apDataNew, <em>ignore_index</em>=True)</pre><ul><li><strong>Google Ad banners. </strong>These are tricky since their classes are dynamic and can cause the Scraper to misclick when I try to click the ‘Next Page’ button. This, unfortunately, caused the Scraper to get the same page several times in my routine since it didn’t click the next page button properly sometimes. Because of this, <strong>I ended up with 15 000 listings instead of 50 000 after removing duplicates.</strong> However, I did not end up digging deeper into this since luckily 15 000 is still more than enough data to move forward with.</li><li><strong>Privacy Policy Pop-up in an iframe. </strong>Pop-ups every time since we are in incognito mode and needed to be clicked. Turns out it was implemented in an iframe which complicated things but was solved with Seleniums window-management tools.</li></ul><p><strong>Adding features to our data with the help of Yelp.<br></strong>With the help of Yelps API, we can get a lot of details back based on a certain location. By sending an address we can, for example, get the coordinates, (latitude, and longitude) of that location. This is very useful since we can now turn the string-based address, like “Hamngatan 1” <em>into something more quantifiable</em> like two numbers. This will make the location into a usable feature and later creates the possibility to geometrically compare apartments locations.</p><p>Additionally, we also receive the Points-of-Interests feature to add to our apartment dataset. This is defined as the number of places that Yelps deem worthy to list, which is within 2 km of that apartment. You may ask, why is that relevant? It is relevant because it can be an indicator of how central your apartment is located and that may reflect in the sale price. Adding this feature may, therefore, help with our accuracy in our model later on.</p><pre>response = yelp_api.search_query(<em>location</em>=adress, <em>radius</em>=2000, <em>limit</em>=1)</pre><pre><em>return</em> (latitude, longitude, pointsOfInterestsNearby)</pre><h3>Cleaning, Scrubbing and Filtering the data</h3><p>This is the part where I think I learned the most about applying a problem to the real world since data is never a nicely formatted and clean as you would like, and this time was no different. First, I started by cleaning the data to reformat it:</p><ul><li><strong>Change date order and make numerical. </strong>I used a python dictionary structure to convert the month into its numerical value.</li></ul><pre><em># 6 december 2019 --&gt; 20191206<br></em>df.Date = [apartment.split(&#39; &#39;)[2] + (apartment.split(&#39; &#39;)[1]) + (apartment.split(&#39; &#39;)[0]).replace(&#39;december&#39;, &#39;12&#39;)</pre><ul><li><strong>Make all features numerical (floats) except the Address and Broker.</strong></li><li><strong>Trim sale price. </strong>Convert from “Slutpris 6 250 000 kr” to “6250000”.</li><li><strong>Remove wrongly acquired coordinates. </strong>The Yelp API did in a few instances think that an address was in a completely different part of Sweden and returned those coordinates. These could skew the data so if an apartment had coordinates that were significantly outside the range of Stockholm, the entire row was dropped.</li></ul><pre>df = df.loc[17.6 &lt; df[&#39;Longitude&#39;] &lt; 18.3]<br>df = df.loc[59.2 &lt; df[&#39;Latitude&#39;] &lt; 59.45]</pre><ul><li><strong>Add a new combined feature PricePerKvm. </strong>Since the prize is strongly connected to the size of the apartment, comparing the price directly between different sized apartments would not show how fairly priced it was. To directly compare the prizes I created a new feature called (PricePerKvm) which is just the price divided by its square meters.</li></ul><h3><strong>Drumroll, please: Our Final dataset</strong></h3><p>After a lot of cleaning, scrubbing, and filtering we ended up with a <strong>dataset containing 14 171 apartment listings </strong>with <strong>9 different features.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtGxqukYGUMeKfgGTdJz7Q.png" /><figcaption>[Sample of 5 out of 14 171 entries]</figcaption></figure><p>In this part, I learned that a large majority of time in a Data Science project will include gathering and cleaning the data since timewise, <strong>this part took almost 80% of the time for the total project. </strong>Real-life data is rarely clean, filtered or structured in the way you would like. Its also not always uniform so for the next project <em>I would like to take on the challenge of combining different types of datasets into one.</em></p><p>When it comes to this dataset, it should be more than enough data for our next part — <strong>building a predictive Machine Learning model and also turning the data into insights!</strong></p><p>Read the next story in this project here:<br><a href="https://medium.com/@gustaf.halvardsson/a-data-science-approach-to-stockholms-apartment-prices-part-2-13e51772b528"><strong><em>Turning data into insights and predictors with Machine Learning.</em></strong></a></p><p>All source code is available here:<br><a href="https://github.com/gustafvh/Apartment-ML-Predictor-Stockholm_-with-WebScraper-and-Data-Insights"><strong>https://github.com/gustafvh/Apartment-ML-Predictor-Stockholm_-with-WebScraper-and-Data-Insights</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcee0212596d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-data-science-approach-to-stockholms-apartment-prices-part-1-dcee0212596d">A Data Science approach to Stockholms Apartment Prices</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>
    </channel>
</rss>