<?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 Guilherme Marmerola on Medium]]></title>
        <description><![CDATA[Stories by Guilherme Marmerola on Medium]]></description>
        <link>https://medium.com/@guilherme-marmerola-41685?source=rss-69b33d479bb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*npQJyGSV5JohYHYR1fI_IQ.jpeg</url>
            <title>Stories by Guilherme Marmerola on Medium</title>
            <link>https://medium.com/@guilherme-marmerola-41685?source=rss-69b33d479bb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 08:10:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guilherme-marmerola-41685/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[Using Machine Learning to find value zones in São Paulo]]></title>
            <link>https://medium.com/loftbr/using-machine-learning-to-find-value-zones-in-s%C3%A3o-paulo-37be3841fa4a?source=rss-69b33d479bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/37be3841fa4a</guid>
            <category><![CDATA[loftworld]]></category>
            <dc:creator><![CDATA[Guilherme Marmerola]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 20:00:52 GMT</pubDate>
            <atom:updated>2021-06-10T20:00:52.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7eORhyAPSykks8H3" /><figcaption>How to split the city in such a way as to have value zones with the least dispersion of price per meter? Different colors indicate different value zones in the city.</figcaption></figure><p>Here at Loft, we are continually building our understanding of the real estate market, bringing data and the experience of our partners and founders together. We like to exercise our creativity by exploring and adapting existing concepts with data and algorithms.</p><p>One of the most established concepts in the real estate market is that of the neighbourhood. Each person has a different relationship with this concept: some people care little about which neighbourhood they live in, as long as it is close to work; others were born, grew up and created roots in the same neighbourhood, or identify with its lifestyle.</p><p>At Loft, in addition to identifying which neighbourhoods meet the different profiles of our clients, we are interested in understanding neighbourhoods by more functional aspects, such as size, population density, presence of green areas, and more. In particular, we were interested in knowing where the pockets of real estate value are located in the city. That is, to find out how to divide the city into parts such that property prices in each part are very similar.</p><p>Thus, we exercise our understanding of the market by creating a new value-focused neighbourhood concept, comparing new neighbourhood lines with existing ones.</p><h3><strong>Simplicity and effectiveness: decision trees</strong></h3><p>A decision tree is a machine learning algorithm that learns through rule induction. It partitions the training dataset aiming at reducing the dispersion of its target variable. In our case of neighbourhood partitioning, this algorithm fits very well, because we want to do just that: divide the city in partitions (splits in latitude and longitude data) such that homes in these partitions have low dispersion of price per square meter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P4UwngPJ2lFSyCOU" /><figcaption>In our case, we use a decision tree to divide the city aiming to find partitions with low price dispersion through latitude and longitude rules.</figcaption></figure><p>In a nutshell, we arrive at the result as follows:</p><ul><li>We prepared a database of real estate listings that contains estimates of price per meter of flats in 2018. At Loft, in addition to the listing database, we use several other data sources for pricing, including more up-to-date and accurate sources such as registrations and transactions on our marketplace. For the purposes of our exercise, however, the data collected is sufficient.</li><li>Each row in our database is a building, containing the median price per metre of the apartments advertised in the building:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MD8G2AfXTA4PyJOu" /></figure><ul><li>We apply a rotation transformation to the latitude and longitude data. This way the tree can make diagonal splits.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*UN0ejfzk528ea5PE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WCZvi4gsvpz81mSa" /></figure><ul><li>We fit the tree on the rotated lat-longs, with the constraint that we must have at least 200 buildings per partition.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tP9k0eyfhR-kQipU" /></figure><ul><li>We publish the result using kepler.gl, which allows us to see the partitions and the average price per metre of the partition.</li></ul><h3><strong>Results</strong></h3><p>Below we publish the map with the results, where you can switch between the layer of clusters (partitions) and average price per cluster. It’s worth mentioning again that we used a listings data source from 2018. Therefore, the prices on this map may not accurately reflect current market prices. Nevertheless, that does not defeat the purpose of using this database for making comparisons between neighbourhoods.</p><p><a href="https://kepler.gl/demo/map?mapUrl=https://dl.dropboxusercontent.com/s/bovlqcljnej3oy5/keplergl_98r6e33.json">Large-scale WebGL-powered Geospatial Data Visualization Tool</a></p><h3><strong>Example: Jardins</strong></h3><p>Each person has a slightly different definition, but it is common to refer to the neighbourhoods between Avenida Paulista, Rua Estados Unidos, Avenida Rebouças and Avenida Brigadeiro Luiz Antônio as “Jardins”. Loft was born in these neighbourhoods. Our first office and first apartments were in this area. We are therefore very fond of this region and have a lot of experience operating there. We generally evaluate the behaviour of our algorithms in Jardins to see if they “make sense”.</p><p>It is common to divide Jardins into two different neighbourhoods:</p><ul><li>Jardim América, between Avenida Rebouças and Avenida Nove de Julho</li><li>Jardim Paulista, between Avenida Nove de Julho and Avenida Brigadeiro Luiz Antônio</li></ul><p>The algorithm, on the other hand, divided Jardins into 4 different partitions, dividing both Jardim América and Jardim Paulista in two (the central line runs through Alameda Casa Branca, almost at the division of the two neighbourhoods):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*am9kfB6FS6o2BgQU" /><figcaption>Partitioning Jardins into 4 value pockets. Different colours indicate different partitions.</figcaption></figure><p>When we change the visualisation to the price per metre of each of the partitions, we see a pattern of higher valuation in the Jardim América region and in the vicinity of Rua Estados Unidos, a fact that had been heard in the market a lot, and has now been discovered and confirmed through data :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xuT_PUHL_GoPXzVt" /><figcaption>Distribution of prices in the partitions of Jardins. Darker reds represent higher prices, while yellow and blue tones represent intermediate prices.</figcaption></figure><h3><strong>Conclusion</strong></h3><p>Finally, we show this last visualisation of the average price per partition in São Paulo. We see several interesting patterns: (a) Vila Nova Conceição and a part of Moema coming together into a single zone; (b) different partitions in Higienópolis; (c) price increases around Ibirapuera Park; (d) a mini-high-value zone between Consolação and Bela Vista, and others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sWD47kn8jAfaGc2e" /><figcaption>Distribution of prices in São Paulo. Darker reds represent higher prices, yellow tones represent intermediate prices and dark blues represent lower prices.</figcaption></figure><p>Feel free to explore the map we have provided above and create your understanding of the market together with us!</p><p>We continue to use data science to address the complexity of the housing market, reinvent the consumption of housing, and eliminate, for our clients, the friction in the process of switching homes.</p><p>Do you want to join Loft and build the future of real estate?</p><p>Apply for our open positions! — <a href="https://jobs.lever.co/loft/">https://jobs.lever.co/loft/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37be3841fa4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/loftbr/using-machine-learning-to-find-value-zones-in-s%C3%A3o-paulo-37be3841fa4a">Using Machine Learning to find value zones in São Paulo</a> was originally published in <a href="https://medium.com/loftbr">Loft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[xgbse: Improving XGBoost for Survival Analysis]]></title>
            <link>https://medium.com/data-science/xgbse-improving-xgboost-for-survival-analysis-393d47f1384a?source=rss-69b33d479bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/393d47f1384a</guid>
            <category><![CDATA[explore]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[survival-analysis]]></category>
            <dc:creator><![CDATA[Guilherme Marmerola]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 22:12:28 GMT</pubDate>
            <atom:updated>2021-03-08T15:09:41.892Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>Introducing <a href="https://loft-br.github.io/xgboost-survival-embeddings/index.html"><strong>XGBoost Survival Embeddings (xgbse)</strong></a>, our survival analysis package built on top of XGBoost</h4><blockquote>“There are two cultures in the use of statistical modeling to reach conclusions from data. One assumes that the data are generated by a given stochastic data model. The other uses algorithmic models and treats the data mechanism as unknown.”<em> — Leo Breiman, </em><a href="https://projecteuclid.org/euclid.ss/1009213726"><em>Statistical Modeling: The Two Cultures</em></a></blockquote><p><a href="https://en.wikipedia.org/wiki/Survival_analysis#:~:text=Survival%20analysis%20is%20a%20branch,and%20failure%20in%20mechanical%20systems.">Survival Analysis</a> is a branch of statistics concerned with modeling the duration of events, most importantly providing tools to deal with (and not simply discard) <em>censored</em> data, partial but useful information about durations. For instance, if an apartment is on the market for 90 days, we don&#39;t know how long it will take to actually sell it, but we <em>do know </em>that it took <em>at least</em> 90 days (where 90 days is the <em>time of censoring</em>). Survival analysis is useful for a wide range of applications, such as predictive maintenance, customer churn, credit risk, asset liquidity risk, and many others.</p><p>The most common output of survival analysis models is a survival curve, which shows the cumulative probability of survival (event not happening) over time. Other models may output <em>risk</em>, which is a number proportional to how fast the curve decays, or an <em>expected time</em>, obtained by direct optimization or by numerically integrating the curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJnO61raSo9DsQxsuKGJ1Q.png" /><figcaption>Survival curves can give us a lot of insight when we care about time to event predictions. Image by author.</figcaption></figure><p>At <a href="https://a16z.com/2020/01/03/loft/">Loft</a>, we&#39;re a big user of survival analysis models, as the journey of finding a new home is rather long in Brazil, with several milestones along the way (visits, offers, deeds, renovation, etc). Particularly, as Loft operates an <a href="https://www.opendoor.com/w/guides/what-is-an-ibuyer">iBuyer</a> (using its own equity to buy, renovate, and sell apartments), we&#39;re interested in modeling the time to sell an apartment, as holding it for too long represents the biggest risk we are subject to. The models that produce these estimates are used to make million-dollar decisions and thus have strict requirements on discrimination performance and calibration.</p><p>Therefore, we invested a lot of time exploring survival analysis packages. In our quest we found that most implementations embraced one of two cultures:</p><ol><li>Models with sound statistical properties (such as calibrated survival curves), but lacking in expressiveness and computational efficiency</li><li>Highly efficient and expressive models, but lacking some statistical properties (producing only risk or uncalibrated expected survival times — XGBoost fits here)</li></ol><p>Given this scenario, we embarked on a journey to unite the two cultures in a single package that would meet our requirements: <a href="https://github.com/loft-br/xgboost-survival-embeddings"><strong>XGBoost Survival Embeddings (xgbse)</strong></a>. And now we’re open sourcing it!</p><p>We chose XGBoost as our &quot;base model&quot; for its efficient and easy-to-use implementation, and leveraged some tricks to add nice statistical properties to it. We provide more details about XGBoost&#39;s shortcomings and these tricks next.</p><h4>XGBoost Shortcomings for Survival Analysis</h4><p>The XGBoost implementation provides two methods for survival analysis: <a href="https://forecast.global/insight/underrated-in-ml-intro-to-survival-analysis/"><strong>Cox</strong></a> and <a href="https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html"><strong>Accelerated Failure Time (AFT)</strong></a>. When it comes to ordering individuals by risk (discrimination), both show competitive performance (as measured by C-index, the ROC AUC equivalent for survival) while being lightning fast.</p><p>However, we can observe shortcomings when it comes to other desirable statistical properties. Specifically, three properties are of concern:</p><ul><li>prediction of <strong>survival curves</strong> rather than <strong>point estimates</strong></li><li>estimation of <strong>confidence intervals</strong></li><li><strong>calibrated</strong> (unbiased) expected survival times</li></ul><p>Let us take the AFT implementation as an example (as Cox only outputs risk and not time or survival). The AFT model outputs a value that should be interpreted as the expected survival time for each sample. To compute this time, it assumes an underlying distribution for times and events, controlled by the aft_loss_distribution and aft_loss_distribution_scale hyperparameters. As they control hard-wired assumptions of the model, we would expect that they could drastically change its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsUU2YTvtC9Ce5pd-yjAPQ.png" /><figcaption>Table explaining the impact of aft_loss_distribution and aft_loss_distribution_scale, the latter represented by the &quot;z&quot; variable in the formulas. Source: <a href="https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html">XGBoost AFT documentation</a>.</figcaption></figure><p>To confirm this is true, let us perform an experiment using the METABRIC dataset. We will test different values for aft_loss_distribution_scale while keeping aft_loss_distribution as &quot;normal&quot; and check how this will affect model performance. We test the following values: [0.5, 1.0, 1.5]. The following gist gives a rough idea on how to run this simple experiment but you can find the full code <a href="https://github.com/loft-br/xgboost-survival-embeddings/blob/main/examples/how_xgbse_works.ipynb">here</a>. The results are very interesting, if not alarming:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f8cbe2ba8618ce2af6bef1e60e3c1ae/href">https://medium.com/media/9f8cbe2ba8618ce2af6bef1e60e3c1ae/href</a></iframe><pre>aft_loss_distribution_scale: 1.5<br>C-index: 0.645<br>Average predicted survival time: 203 days<br>----<br>aft_loss_distribution_scale: 1.0<br>C-index: 0.648<br>Average predicted survival time: 165 days<br>----<br>aft_loss_distribution_scale: 0.5<br>C-index: 0.646<br>Average predicted survival time: 125 days<br>----</pre><p>In all three scenarios, we can build models with C-index results close to the state of the art [8]. However, our predictions change drastically, with two models showing an average predicted survival time difference of 78 days. This difference would perhaps be understandable if we were analyzing a single sample. But we&#39;re looking across the full validation dataset where the average prediction should be fairly stable regardless of which model we use.</p><p>If we plot these results alongside an unbiased survival estimator such as the Kaplan Meier we can check that for each step of 0.5 in aft_loss_distribution_scale we move roughly one decile to the right in the curve. Also, we don&#39;t see a full survival curve: XGBoost only outputs point time-to-event predictions (no confidence intervals either).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQYUhZG8IplpwqwdtOxi3A.png" /><figcaption>Vanilla XGBoost outputs predictions that are overly sensitive to hyperparameters, which prevents its use on applications that are sensitive to survival curve calibration. Image by author.</figcaption></figure><p>Given these results, we raise the question: &quot;what model should we trust?&quot;. Although we could try to optimize for some error measure such as L1-loss [9], we would like more guarantees for applications that are dependent on stable and calibrated time-to-event estimates. Having only point estimates, no confidence intervals, and no &quot;calibration by design&quot; mines trust and prevents shipping survival analysis models to production.</p><h4>Improving XGBoost by using it as a feature transformer</h4><p>Although in need of an extension for better statistical properties, XGBoost is undoubtedly a powerhouse. C-index results show that the model has great discrimination performance, being competitive with the state of the art. We just need to adapt how we use it.</p><p>Besides being leveraged for prediction tasks, Gradient Boosted Trees (GBTs) can also be used as <strong><em>feature transformers</em></strong> of the input data. Trees in the ensemble perform splits on features that discriminate the target, encoding relevant information in their structure. In particular, the terminal nodes (leaves) at each tree in the ensemble define a very nice <a href="http://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html"><strong><em>feature transformation</em></strong></a><strong><em> (embedding)</em></strong> of the input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiEsq9SF3sQFdLr87owtbg.png" /><figcaption>We can extract features from a forest model like XGBoost, transforming the original feature space into a &quot;leaf occurrence&quot; embedding. Orange nodes represent the path of a single sample in the ensemble. Image by author.</figcaption></figure><p>This kind of <strong><em>tree ensemble embedding</em></strong> has very convenient properties:</p><ol><li><strong>sparsity and high-dimensionality:</strong> trees deal with nonlinearity and cast original features to a sparse, high-dimensional embedding, which helps linear models perform well when trained on it. For instance, a logistic regression trained on the embedding (with features as one-hot encoded leaf indices) can show comparable performance to the actual ensemble, with the added benefit of probability calibration (see [1], [2], and [3])</li><li><strong>supervision:</strong> trees also work as a noise filter, performing splits only through features that have predictive power. Thus, the embedding actually has a lower intrinsic dimension than the input data (see [4]). This mitigates the curse of dimensionality and allows a kNN model trained on the embedding (using hamming distance) to have comparable performance to the actual ensemble. With neighbor-sets at hand, we can use robust estimators such as the Kaplan-Meier to get predictions.</li></ol><p>These two properties are the foundation upon which we built <strong>xgbse</strong>. We show how we put them to good use next.</p><h4>Logistic regressions, time windows, embedding as input</h4><p>Our first approach, XGBSEDebiasedBCE, takes inspiration from the multi-task logistic regression method in [5], the BCE (binary cross-entropy) approach in [6], and the probability calibration ideas from [1], [2] and [3].</p><p>It consists of training a set of logistic regressions on top of the embedding produced by the underlying XGBoost model, each predicting survival at different user-defined discrete time windows. The classifiers remove individuals as they are censored, with targets that are indicators of surviving at each window.</p><p>As the embedding is sparse and high dimensional, the linear models actually can <em>improve</em> the ensemble performance, while also adding nice statistical properties to it, such as probability calibration (as logistic regressions are calibrated by design).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktqm81oXDxt3Vd0eBZioAw.png" /><figcaption>In XGBSEDebiasedBCE we stack several logistic regressions on top of XGBoost, which is used as a feature transformer. Each logistic regression predicts survival at different user-defined time windows. The predictions are then composed to form a survival curve. Image by author.</figcaption></figure><p>The naive approach tends to give biased survival curves, due to the removal of censored individuals. Thus, we made some adaptations such that logistic regressions estimate the di/ni term (point probabilities) in the <a href="https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf">Kaplan-Meier formula</a> and then use the KM estimator to get nearly unbiased survival curves.</p><p>This way, we can get full survival curves from XGBoost, and confidence intervals with minor adaptations (such as performing some rounds of bootstrap). Training and scoring of logistic regression models is efficient, being performed in parallel through joblib, so the model can scale to hundreds of thousands or millions of samples.</p><h4>Kaplan-Meier on nearest neighbors</h4><p>As explained in the previous section, even though the embedding produced by XGBoost is sparse and high dimensional, its intrinsic dimensionality actually should be lower than the input data. This enables us to &quot;convert&quot; XGBoost into a nearest neighbor model, where we use hamming distance to define similar elements as the ones that co-occurred the most at the ensemble terminal nodes. Then, at each neighbor-set we can get survival estimates with robust methods such as the Kaplan-Meier estimator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiZ4P0pOVjNeHlDz3-ZyOg.png" /><figcaption>In XGBSEKaplanNeighbors we stack a kNN model on top of XGBoost, which is used as a feature transformer. We use hamming distance to build neighbor-sets. At each neighbor-set a KM estimator is executed to get a survival curve. Image by author.</figcaption></figure><p>We recommend using dart as the booster to prevent any tree to dominate variance in the ensemble and break the leaf co-occurrence similarity logic. We built a high-performing implementation of the KM estimator to calculate several survival curves in a vectorized fashion, including upper and lower confidence intervals based on the Exponential Greenwood formula [7].</p><p>However, this method can be very expensive at scales of hundreds of thousands of samples, due to the nearest neighbor search, both on training (construction of search index) and scoring (actual search).</p><h4>Single tree, and Kaplan-Meier on its leaves</h4><p>As a simplification to XGBSEKaplanNeighbors, we also provide a single tree implementation. Instead of doing expensive nearest neighbor searches, we fit a single tree via XGBoost and calculate KM curves at each of its leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHFdIJ3sPPpl9t9TJX7_cg.png" /><figcaption>We fit a single tree using the vanilla XGBoost implementation and execute one KM curve for each of its leaves, instead of using the default prediction. Image by author.</figcaption></figure><p>It is by far the most efficient implementation, able to scale to millions of examples easily. At fit time, the tree is built and all KM curves are pre-calculated, so that at scoring time a simple query will suffice to get the model’s estimates.</p><p>However, as we’re fitting a single tree, predictive power may be worse. That could be a sensible tradeoff, but we also provide XGBSEBootstrapEstimator, a bootstrap abstraction where we can fit a forest of XGBSEKaplanTree&#39;s to improve accuracy and reduce variance.</p><h4>Does it solve the problem?</h4><p>Now we return to the first example and check how XGBEmbedKaplanNeighbors performs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d69e48839ec8bafb4ab17aaf578005f0/href">https://medium.com/media/d69e48839ec8bafb4ab17aaf578005f0/href</a></iframe><pre>aft_loss_distribution_scale: 1.5<br>C-index: 0.640<br>Average probability of survival at [30, 90, 150] days: [0.9109, 0.6854, 0.528]<br>----<br>aft_loss_distribution_scale: 1.0<br>C-index: 0.644<br>Average probability of survival at [30, 90, 150] days: [0.9111, 0.6889, 0.5333]<br>----<br>aft_loss_distribution_scale: 0.5<br>C-index: 0.650<br>Average probability of survival at [30, 90, 150] days: [0.913, 0.6904, 0.5289]<br>----</pre><p>As measured by the average probability of survival in 30, 90 and 150 days the model shows good results, with comparable C-index results and predictions being very close and independent of aft_loss_distribution_scale choice. Visually, the comparison of the average model predictions to a Kaplan Meier yields much better results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mr6qPf1ojcfKjHC3" /><figcaption>XGBSE outputs a full survival curve and it is much more stable than vanilla XGBoost, its average prediction being fairly close to the unbiased KM estimator. Image by author.</figcaption></figure><p>Much less bias, full survival curves and stability! Although is too harsh to claim that the problem is solved, we believe that the we could build a strong survival analysis package and bring the &quot;two cultures&quot; much closer together.</p><h4>Try it for yourself!</h4><p>XGBoost Survival Embeddings shows great results in several survival analysis <a href="https://loft-br.github.io/xgboost-survival-embeddings/benchmarks/benchmarks.html">benchmarks</a>, outperforming vanilla XGBoost and parametric methods in most cases. It is pip installable and scikit-learn compatible. There are more features to try, such as confidence intervals, extrapolation of survival curves, explainability through prototypes, metrics, and more. We’re committed to improving the lib and adding new content in the future.</p><p>For more details, please check the the library on <a href="https://github.com/loft-br/xgboost-survival-embeddings">github</a>, the <a href="https://loft-br.github.io/xgboost-survival-embeddings/index.html">docs</a>, and <a href="https://github.com/loft-br/xgboost-survival-embeddings/tree/main/examples">examples</a>! We invite the community to contribute. Please help by trying it out, reporting bugs, and letting us know what you think!</p><p>By <a href="https://www.linkedin.com/in/davivieirab/">Davi Vieira</a>, <a href="https://www.linkedin.com/in/gdmarmerola/">Guilherme Marmerola</a>, <a href="https://www.linkedin.com/in/gabriel-gimenez-b8b010140/">Gabriel Gimenez</a> and <a href="https://www.linkedin.com/in/vrcestima/">Vitor Estima</a>.</p><h4>References</h4><p>[1] X. He, J. Pan, O. Jin, T. Xu, B. Liu, T. Xu, Y. Shi, A. Atallah, R. Herbrich, S. Bowers, and J. Q. Candela. <a href="https://research.fb.com/wp-content/uploads/2016/11/practical-lessons-from-predicting-clicks-on-ads-at-facebook.pdf">Practical Lessons from Predicting Clicks on Ads at Facebook</a> (2014). In Proceedings of the Eighth International Workshop on Data Mining for Online Advertising (ADKDD’14)<em>.</em></p><p>[2] <a href="https://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html">Feature transformations with ensembles of trees</a>. Scikit-learn documentation at <a href="https://scikit-learn.org/">https://scikit-learn.org/</a>.</p><p>[3] G. Marmerola. <a href="https://gdmarmerola.github.io/probability-calibration/">Calibration of probabilities for tree-based models</a>. Personal Blog at <a href="https://gdmarmerola.github.io/">https://gdmarmerola.github.io/</a>.</p><p>[4] G. Marmerola. <a href="https://gdmarmerola.github.io/umap-supervised-embeddings/">Supervised dimensionality reduction and clustering at scale with RFs with UMAP</a>. Personal Blog at <a href="https://gdmarmerola.github.io/">https://gdmarmerola.github.io/</a>.</p><p>[5] C. Yu, R. Greiner, H. Lin, V. Baracos<em>.</em> <a href="http://www.cs.cornell.edu/~cnyu/papers/nips11_survival.pdf">Learning Patient-Specific Cancer Survival Distributions as a Sequence of Dependent Regressors</a>. Advances in Neural Information Processing Systems 24 (NIPS 2011).</p><p>[6] H. Kvamme, Ø. Borgan. <a href="https://arxiv.org/pdf/1912.08581.pdf">The Brier Score under Administrative Censoring: Problems and Solutions</a>. arXiv preprint arXiv:1912.08581.</p><p>[7] S. Sawyer. <a href="https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf">The Greenwood and Exponential Greenwood Confidence Intervals in Survival Analysis</a>. Handout on Washington University in St. Louis website.</p><p>[8] H. Kvamme, Ø. Borgan, and I. Scheel. <a href="https://jmlr.org/papers/v20/18-424.html">Time-to-event prediction with neural networks and Cox regression</a>. Journal of Machine Learning Research, 20(129):1–30, 2019.</p><p>[9] H. Haider, B. Hoehn, S. Davis, R. Greiner. <a href="https://arxiv.org/pdf/1811.11347.pdf">Effective Ways to Build and Evaluate Individual Survival Distributions</a>. Journal of Machine Learning Research 21 (2020) 1–63.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=393d47f1384a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/xgbse-improving-xgboost-for-survival-analysis-393d47f1384a">xgbse: Improving XGBoost for Survival Analysis</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[Data & Decision Science Loft: nosso ecossistema de algoritmos]]></title>
            <link>https://medium.com/loftbr/data-decision-science-loft-nosso-ecossistema-de-algoritmos-919ab9d33505?source=rss-69b33d479bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/919ab9d33505</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[real-estate]]></category>
            <dc:creator><![CDATA[Guilherme Marmerola]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 16:46:34 GMT</pubDate>
            <atom:updated>2021-01-26T19:33:08.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M214foIk99Rh6h59raF92Q.png" /><figcaption>Construímos algoritmos com foco em gerar valor para pessoas usuárias da nossa plataforma, atingindo nossa visão de Freedom Living</figcaption></figure><p>Na Loft, acreditamos que o mercado imobiliário está quebrado e precisa ser reinventado com tecnologia e dados. Queremos mudar a forma como as pessoas consomem moradia, com o foco em melhorar a experiência de pessoas compradoras e vendedoras, atingindo a visão de <a href="https://www.loft.com.br/about-us">Freedom Living</a>.</p><p>Nesse contexto, nosso time de ciência de dados (Data &amp; Decision Science) tem a missão de transformar nossos dados em algoritmos que suportem nossos produtos e tomada de decisão em prol desta visão. Somos responsáveis pela geração de resultados de negócio e protagonistas nessa jornada: tornar o mercado imobiliário mais líquido, com menos assimetria de informação, conectando pessoas vendedoras e compradoras por meio da tecnologia.</p><p>Com o tempo nossos projetos evoluíram, e conseguimos montar melhor nosso quebra-cabeça de tomada de decisão em um processo orgânico que deu origem ao que apelidamos de nosso “ecossistema” de algoritmos, que continua evoluindo. Vamos mostrá-lo nesse post.</p><h4><strong>Nosso ecossistema de algoritmos</strong></h4><p>O mercado imobiliário tem diversas complexidades. Nele, são realizadas as maiores transações das vidas das pessoas, geralmente relacionadas a sonhos ou grandes mudanças. Clientes sofrem com pouca transparência de preços, dificuldade de achar um novo lar por conta de silos de informação e dificuldade de vender o lar atual por falta de visibilidade do mercado.</p><p>Nesse cenário, investimos fortemente em dados para resolver esses problemas, possibilitando construir confiança entre agentes do mercado. Construindo essa confiança, transformamos nosso marketplace em um motor de liquidez, ajudando pessoas compradoras a encontrar rápido seu apartamento dos sonhos, e pessoas vendedoras a obter propostas rapidamente. Suportando essa máquina temos uma série de modelos e políticas de tomada de decisão, formando nosso ecossistema de algoritmos.</p><p>Para trazer uma ajuda visual ao artigo, montamos a seguinte apresentação com diagramas do nosso ecossistema. Fique a vontade para usar como material de suporte. Vamos lá!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fpresentation%2Fembed%3Fid%3D1YsjPzNFQG-A9vejZJVqQPoAUpsw7PBcSiUSgR5VCVoA%26size%3Dl&amp;display_name=Google+Docs&amp;url=https%3A%2F%2Fdocs.google.com%2Fpresentation%2Fd%2F1YsjPzNFQG-A9vejZJVqQPoAUpsw7PBcSiUSgR5VCVoA%2Fedit%3Fusp%3Dsharing&amp;image=https%3A%2F%2Flh4.googleusercontent.com%2FDcgsysWdhx9BHd2tu7VynuiKuzTGwqQgupWbC1WMCRi-H7MpUAlM6XPgMDfFwd3DwRsb5_JPyA%3Dw1200-h630-p&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="700" height="559" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1110e6d1e970a2df351074e51cc6e09/href">https://medium.com/media/f1110e6d1e970a2df351074e51cc6e09/href</a></iframe><p><strong>Estruturando o histórico de transações imobiliárias</strong></p><p>Em países onde temos alta liquidez de imóveis e baixa dispersão de preços geralmente encontramos um sistema centralizado de anúncios e transações de imóveis. Nos Estados Unidos, esse sistema se chama MLS (Multiple Listings System). No Brasil, esses dados se encontravam em silos, nos cartórios. Trabalhamos intensamente com as associações de registradores de imóveis para mudar esse cenário, fazendo bons avanços.</p><p>Dessa forma, a primeira etapa da nossa máquina envolve catalogar as informações dos imóveis contidas em uma certidão chamada matrícula. Isso envolve digitalizar a matrícula, converter a imagem digitalizada para texto e aplicar algoritmos de NLP para encontrar as informações de interesse (entidades) nesse texto. Ao final do processo, teremos uma base de transações centralizada e estruturada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uct3CGn2J7Wg6fdlc_HksA.png" /><figcaption>Nosso modelo de extração de informações de matrículas baseado em OCR e NLP.</figcaption></figure><p><strong>Definindo uma referência de preços</strong></p><p>Uma vez em posse de uma base de transações confiável, podemos utilizá-la para construir modelos de valoração de imóveis ou, na sigla em inglês, AVMs (Automated Valuation Models), em conjunto com outras fontes de dados como anúncios no mercado, transações no nosso próprio marketplace e a nossa feature store de imóveis (com informações de localização, condomínios, estado de conservação do apartamento e muitas outras).</p><p>Esses modelos entregam uma referência de preços de mercado, um ponto de partida para clientes determinarem o preço de anúncio dos seus imóveis, a depender da necessidade de rapidez na venda desses ativos. Além disso, essa referência de preços é consumida por diversos outros times na Loft, para ajudar na experiência de clientes em diversos outros pontos de contato. Esse é o primeiro passo para diminuirmos a assimetria de informação entre participantes do mercado, aumentar liquidez, e estabilizar preços (que atualmente são muito voláteis).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udZN2EMvrp9yOfTyMZKY9Q.png" /><figcaption>Nossos modelos de valoração de imóveis, o primeiro passo para diminuirmos a assimetria de informação entre participantes do mercado, aumentar liquidez, e estabilizar preços.</figcaption></figure><p><strong>Operando fundos imobiliários</strong></p><p>Com nossas referências de preço disponíveis, nosso ecossistema se torna mais diverso do ponto de vista de aplicações. O primeiro negócio que a Loft operou foi o de <a href="https://www.loft.com.br/vender-apartamento">iBuyer</a> (instant Buyer), que consiste em comprar, reformar e vender apartamentos, onde assumimos risco investindo em apartamentos de pessoas vendedoras que querem liquidez rápida e reformamos para pessoas compradoras que querem um apartamento pronto para morar.</p><p>Nesse processo, a Loft se torna proprietária dos imóveis até eles serem vendidos, financiando a compra deles por meio de fundos imobiliários, que atualmente têm centenas de ativos na carteira. Uma parte significativa do capital desses fundos foi fornecida por pessoas que decidiram investir seu patrimônio na visão da Loft e esperam retornos compatíveis aos riscos que elas assumiram.</p><p>Além do risco de variações de preço de mercado, o principal fator de risco para nossos ativos imobiliários é a liquidez (tempo até vender o imóvel). Dessa forma, investimos bastante energia na construção de modelos de liquidez imobiliária. Os modelos entregam estimativas de tempo até venda dos imóveis no portfolio, permitindo calcular o risco (e retorno esperado) desses ativos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yh_d3UGWJsO8W95zgIadzA.png" /><figcaption>Nosso modelo de liquidez de imóveis, permitindo o cálculo do risco e retorno de apartamentos.</figcaption></figure><p>Mais especificamente, as métricas de risco e retorno dos ativos são derivadas de um simulador que calcula os custos de carregamento e as receitas associadas de cada apartamento. Com isso podemos escolher bons investimentos (inclusive diversificando o portfolio!), visando bons retornos para clientes dos nossos fundos e propostas justas para clientes do iBuyer.</p><p><strong>Monitorando a saúde do nosso marketplace</strong></p><p>Melhorar o motor de liquidez do iBuyer resolve somente uma parte do desafio de portfolio. Temos também a gestão de todos os outros apartamentos que estão listados na plataforma e não são de nossa propriedade, representando a maioria dos anúncios no marketplace.</p><p>Esses apartamentos pertencem a clientes que confiaram na Loft para conseguir boas propostas rápido. Do outro lado, pessoas compradoras querem encontrar o apartamento dos sonhos rápido e fazer bons negócios. Em qualquer marketplace, essas forças (de oferta e demanda) se equilibram e na Loft não é diferente. Contudo, dado o alto ticket médio e baixo giro do mercado imobiliário, precisamos garantir que o mercado tem a capacidade de se equilibrar sozinho e muitas vezes dar alguns empurrões para que ele se mantenha saudável.</p><p>Nesse cenário, antes de tudo, precisamos ter boas unidades de monitoramento: saber quais “produtos” existem na nossa vitrine, quais estão em falta e quais temos que trabalhar mais na sua divulgação. Portanto, começamos construindo um modelo de clusterização de apartamentos, que usa informações de demanda na plataforma Loft e outros registros para definir quais apartamentos são similares do ponto de vista da demanda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9K5YUQGlvkOrDq8D-qTUPQ.png" /><figcaption>Nosso modelo de clusterização define quais “tipos de produtos” temos na vitrine, para que possamos monitorar o equilíbrio do marketplace.</figcaption></figure><p>Uma vez com o modelo de clusterização, podemos fazer o monitoramento da saúde do marketplace em diferentes clusters. Quando notamos desequilíbrio na plataforma tentamos acionar alavancas visando retornar a níveis saudáveis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxHX7enep5cnP6J4wm-KUg.png" /><figcaption>Quando enxergamos desequilíbrio de oferta e demanda na plataforma acionamos alavancas através da nossa política de marketplace.</figcaption></figure><p>Além disso, a partir do modelo de clusterização conseguimos obter um serviço para determinar, dado um apartamento, quais são seus comparáveis, atuando como um ponto de partida para recomendação no site.</p><p><strong>Transmitindo a voz da pessoa compradora através de dados</strong></p><p>No cálculo de equilíbrio do marketplace, temos relativamente nítida nossa métrica de oferta, o número de apartamentos na vitrine. Contudo, a métrica de demanda é menos trivial. Para isso, temos um time dedicado a entender a demanda, transmitindo a voz de pessoas compradoras através de dados.</p><p>Usando informações de navegação na plataforma, construímos algoritmos de previsão de demanda, indicando o engajamento esperado de pessoas compradoras na nossa vitrine e fechando a lacuna no cálculo de equilíbrio no marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7bjKeFGB_eaZI7SecfulA.png" /><figcaption>Nosso modelo de previsão de demanda, vital para o equilíbrio do marketplace.</figcaption></figure><p>Além de ajudar no fornecimento da informação de demanda esperada, o modelo de previsão de demanda serve de fonte de dados para modelos de recomendação no site, junto com o serviço de comparáveis derivado do modelo de clusterização. Assim ajudamos clientes na busca dos seus apartamentos dos sonhos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h27gZnuHSb_eEGZylrP-4g.png" /><figcaption>Nossos modelos de recomendação, ajudando pessoas compradoras a encontrar seus apartamentos dos sonhos.</figcaption></figure><p>Por fim, nossa última alavanca (ativa) de demanda é mídia de performance (propaganda em redes sociais e outros sites). Dada a complexidade do problema, começamos construindo uma plataforma de experimentação (o <a href="https://medium.com/loftbr/masp-nosso-framework-de-marketing-digital-3ec46bfc2f96">MASP</a>!) para validar hipóteses de melhorias nas nossas campanhas e diminuir nosso CAC (custo de aquisição de clientes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efc7a1ZW_2eH3nprHhBkgQ.png" /><figcaption>Nossa plataforma de experimentação em mídia de performance (o <a href="https://medium.com/loftbr/masp-nosso-framework-de-marketing-digital-3ec46bfc2f96">MASP</a>!).</figcaption></figure><p>Contudo, não enxergamos CAC como algo necessariamente ruim, mas como um investimento que precisa ser utilizado de forma inteligente, como uma alavanca de demanda em prol de clientes do marketplace. Assim, fechamos o ciclo de oferta e demanda na Loft.</p><p><strong>Ajudando a pessoa vendedora a alavancar a liquidez do seu imóvel</strong></p><p>Fechamos nosso ecossistema de algoritmos com um produto de dados responsável por expor inteligência para ajudar anunciantes no nosso site, baseado em algoritmos construídos para entregar recomendações para alavancar a liquidez dos seus imóveis.</p><p>Nesta missão, logo encaramos nosso primeiro desafio. Tínhamos a hipótese de que uma das principais alavancas para o sucesso de um anúncio é a qualidade das fotos do imóvel, sendo isso uma das principais formas de capturar a atenção de pessoas compradoras. Portanto, precisávamos caracterizar as imagens no nosso site de forma precisa e escalável.</p><p>Assim nasceram nossos modelos de &quot;tagueamento&quot; de imagens. Usando dados rotulados por Lofters, construímos modelos que conseguem caracterizar as imagens dos apartamentos (em termos de qualidade, ângulo, e outros), insumo que passou a ser importante para diversos times na Loft.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9cG--KIAQj-z3b6BA6E2g.png" /><figcaption>Nossos modelos de tagueamento de imagens</figcaption></figure><p>Com os dados de caracterização das imagens e diversas outras fontes como clusterização, demanda e precificação, criamos um “perfil competitivo” do anúncio para sugerir melhorias visando alavancar a liquidez do apartamento.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ePIEWflnzSi7RvK8IrvOA.png" /><figcaption>Nosso modelo de prescrição de ações para alavancagem de demanda.</figcaption></figure><p><strong>Pensamentos finais</strong></p><p>Esperamos que tenha gostado da leitura e que esse documento tenha ajudado você a conhecer mais um pouco sobre o time de Data &amp; Decision Science na Loft. Ressaltamos a importância de criar as condições certas — alta intensidade de aprendizado, cultura de compartilhamento de conhecimento e foco em resultado de negócio — para o surgimento desse ecossistema, tema que vamos abordar mais em um próximo post.</p><p>Valeu!</p><p>Ficou com vontade de fazer parte da Loft?</p><p>Se inscreva nas nossas vagas! — <a href="https://jobs.lever.co/loft/">https://jobs.lever.co/loft/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=919ab9d33505" width="1" height="1" alt=""><hr><p><a href="https://medium.com/loftbr/data-decision-science-loft-nosso-ecossistema-de-algoritmos-919ab9d33505">Data &amp; Decision Science Loft: nosso ecossistema de algoritmos</a> was originally published in <a href="https://medium.com/loftbr">Loft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encontrando zonas de valor em SP com machine learning]]></title>
            <link>https://medium.com/loftbr/encontrando-zonas-de-valor-em-sp-com-machine-learning-dde454c7f5a?source=rss-69b33d479bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dde454c7f5a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[neighborhoods]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Guilherme Marmerola]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 14:25:08 GMT</pubDate>
            <atom:updated>2020-08-31T14:25:08.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMdyyGdx6c3tkqVBnUfc8Q.png" /><figcaption>Como dividir a cidade de forma a ter zonas de valor com a menor dispersão de preço por metro? Cores diferentes indicam zonas de valor diferentes na cidade.</figcaption></figure><p>Aqui na Loft, estamos em contínua construção do nosso entendimento do mercado imobiliário, juntando dados com a experiência dos nossos parceiros e fundadores. Gostamos de exercitar nossa criatividade explorando e adaptando conceitos existentes com dados e algoritmos.</p><p>Um dos conceitos mais estabelecidos no mercado imobiliário é o de bairro. Cada pessoa tem um relacionamento diferente com esse conceito: alguns se importam pouco com qual bairro morar, desde que seja perto do trabalho; outros nasceram, cresceram e criaram raízes no mesmo bairro (alô Mooca!), ou se identificam com o estilo de vida dele (Santa Ceciliers ❤).</p><p>Na Loft, além de identificar quais bairros atendem aos diferentes perfis dos nossos clientes (que fica para um próximo post!), nos interessa entender bairros por aspectos mais funcionais, como metragem, densidade demográfica, arborização e outros. Em particular, despertou nosso interesse saber onde estão os bolsões de valor imobiliário na cidade. Ou seja, descobrir como dividir a cidade em partições tal que os preços dos imóveis em cada uma delas sejam muito parecidos.</p><p>Assim, exercitamos nosso entendimento do mercado ao criar um novo conceito de bairro focado em valor, comparando as novas linhas de bairros com as existentes.</p><p><strong>Simplicidade e eficácia: árvores de decisão</strong></p><p>Uma <a href="https://scikit-learn.org/stable/modules/tree.html">árvore de decisão</a> é um algoritmo de machine learning que aprende através da indução de regras, construindo um particionamento da base de treino visando a redução de dispersão da sua variável alvo. No nosso caso de particionamento de bairros, esse algoritmo encaixa muito bem, pois estamos querendo justamente isso: dividir a cidade em partições (quebras a partir de dados de latitude e longitude) tal que os imóveis nessas partições apresentem baixa dispersão de preço por metro quadrado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oM98gP_V59DCdeyYUv2IXA.png" /><figcaption>No nosso caso, usamos uma árvore de decisão para dividir a cidade visando encontrar partições com baixa dispersão de preço através de regras de latitude e longitude.</figcaption></figure><p>Explicamos intuitivamente (e visualmente, em menos de 8 minutos) como o algoritmo funciona neste vídeo do <a href="https://www.youtube.com/watch?v=JInCsSRUJeY">Loft Storm</a>. De uma maneira resumida, chegamos no resultado da seguinte forma:</p><ul><li>Preparamos uma base de anúncios imobiliários que contém estimativas de preço por metro de apartamentos em 2018. Na Loft, além de bases de anúncios, utilizamos diversas outras fontes de dados para precificação, incluindo fontes mais atualizadas e precisas como matrículas e transações no nosso marketplace. Para os propósitos do nosso exercício, contudo, os dados coletados são suficientes.</li><li>Cada linha na nossa base de dados é um prédio, contendo a mediana do preço por metro dos apartamentos anunciados no prédio:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrOJp9PaXyWKx5B8016R8A.png" /></figure><ul><li>Aplicamos uma transformação de rotação nos dados de latitude e longitude. Assim a árvore pode fazer quebras diagonais.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZHA2qCZRAOysIyVM-Sxxg.png" /></figure><ul><li>Ajustamos a árvore nos lat-longs rotacionados, com a restrição de termos no mínimo 200 prédios por partição.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DpBSxKZtu9tfBR-zafUqA.png" /></figure><ul><li>Publicamos o resultado usando o <a href="https://kepler.gl/">kepler.gl</a>, que nos permite enxergar as partições e o preço por metro médio da partição.</li></ul><p><strong>Resultados</strong></p><p>Abaixo publicamos o mapa com os resultados, onde você pode alternar entre a camada dos clusters (partições) e preço médio por cluster. Vale ressaltar novamente que usamos uma fonte de dados de anúncios de 2018. Portanto, os preços nesse mapa podem não refletir exatamente os preços de mercado. Apesar disso, a comparação entre bairros mantém válida a utilização dessa base para esse exercício.</p><p><a href="https://kepler.gl/demo/map?mapUrl=https://dl.dropboxusercontent.com/s/bovlqcljnej3oy5/keplergl_98r6e33.json">Large-scale WebGL-powered Geospatial Data Visualization Tool</a></p><p><strong>Exemplo: Jardins</strong></p><p>Cada um tem uma definição um pouco diferente, mas é comum nos referirmos como “Jardins” os bairros que se situam entre a Avenida Paulista, a Rua Estados Unidos, a Avenida Rebouças e a Avenida Brigadeiro Luiz Antônio. A Loft nasceu nesses bairros. Nosso primeiro escritório e primeiros apartamentos transacionados foram nessa área. Temos, portanto, muito carinho por essa região, e muita experiência operando nela. Geralmente avaliamos o comportamento dos nossos algoritmos nos Jardins para ver se eles “fazem sentido”.</p><p>É comum dividir os Jardins em dois bairros diferentes:</p><ul><li>Jardim América, entre a Avenida Rebouças e a Avenida Nove de Julho</li><li>Jardim Paulista, entre a Avenida Nove de Julho e a Avenida Brigadeiro Luiz Antônio</li></ul><p>O algoritmo, em contrapartida, dividiu os Jardins em 4 partições diferentes, dividindo tanto o Jardim América quanto o Jardim Paulista em dois (a linha central passa na Alameda Casa Branca, quase na divisão dos dois bairros):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXWxv305B0GzH36GKqh1FQ.png" /><figcaption>Particionando os Jardins em 4 bolsões de valor. Cores diferentes indicam partições diferentes.</figcaption></figure><p>Quando mudamos a visualização para o preço por metro de cada uma das partições, vemos um padrão de valoração mais alta na região do Jardim América e nas proximidades da Rua Estados Unidos, padrão que se ouvia falar muito no mercado, e agora foi descoberto e confirmado por meio de dados :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HSuJLEqS2yTOOHMNAwZVQ.png" /><figcaption>Distribuição de preços nas partições dos Jardins. Vermelhos mais escuros representam preços maiores, enquanto tons amarelos e azuis representam preços intermediários</figcaption></figure><p><strong>Conclusão</strong></p><p>Por fim, deixamos essa última visualização do preço médio por partição em São Paulo. Vemos diversos padrões interessantes: Vila Nova Conceição e uma parte de Moema se juntando em uma única zona, diferentes partições em Higienópolis, aumento de preços ao redor do Parque Ibirapuera, uma mini-zona de alto valor entre Consolação e Bela Vista, e outros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTF294V693MeO3_l-UpT-w.png" /><figcaption>Distribuição de preços em São Paulo. Vermelhos mais escuros representam preços maiores, tons amarelos representam preços intermediários e azuis escuros representam preços menores</figcaption></figure><p>Fique a vontade para explorar o mapa que disponibilizamos anteriormente e criar seu entendimento do mercado junto com a gente!</p><p>Seguimos usando ciência de dados para lidar com a complexidade do mercado imobiliário, reinventar o consumo de moradia, e eliminar, para os nossos clientes, a fricção no processo de mudar de lar. Mudar faz parte da gente!</p><p>Ficou com vontade de fazer parte da Loft?</p><p>Se inscreva nas nossas vagas! — <a href="https://jobs.lever.co/loft/">https://jobs.lever.co/loft/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dde454c7f5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/loftbr/encontrando-zonas-de-valor-em-sp-com-machine-learning-dde454c7f5a">Encontrando zonas de valor em SP com machine learning</a> was originally published in <a href="https://medium.com/loftbr">Loft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should join Loft as a Data Scientist]]></title>
            <link>https://medium.com/loftbr/why-you-should-join-loft-as-a-data-scientist-52eeb32cfa8f?source=rss-69b33d479bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/52eeb32cfa8f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[loftworld]]></category>
            <dc:creator><![CDATA[Guilherme Marmerola]]></dc:creator>
            <pubDate>Wed, 17 Jul 2019 18:02:05 GMT</pubDate>
            <atom:updated>2020-01-30T21:43:25.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PSRdXTuIT98U5QlHhhp4Q.png" /><figcaption>Want to have this view at the end of your workday?</figcaption></figure><p>Loft’s mission is to disrupt the real-estate market, transforming painful and bureaucratic processes into simple and delightful experiences. There’s plenty of evidence that we’re going to get there, and a lot of reasons for anyone to accept this challenge: <a href="https://epocanegocios.globo.com/Empresa/noticia/2020/01/exclusivo-apos-novo-aporte-loft-se-torna-11-unicornio-brasileiro-e-o-mais-rapido-da-historia-do-pais.html">we&#39;ve just raised our Series C, and entered unicorn territory after just one and a half years since foundation</a>; <a href="https://www.linkedin.com/in/florianhagenbuch/">Florian</a> and <a href="https://www.linkedin.com/in/matepencz/">Mate</a> experiences as second-time entrepreneurs speak for themselves; our <a href="https://www.youtube.com/watch?v=VI5pY65cWn0&amp;feature=youtu.be">team and investors</a> mean business, and we have been elected by LinkedIn <a href="https://www.linkedin.com/pulse/linkedin-top-startups-2019-empresas-jovens-de-destaque-rafael-kato/">as one of the Top 3 startups to work in Brazil</a>.</p><p>However, on top of all that, I want to add my view on specifically why you, as a Data Scientist, should join Loft. You and I know that Data Science has yet to fully mature in industry, and while some companies might seem very cool at first, data science work in them may be very <a href="https://towardsdatascience.com/why-so-many-data-scientists-are-leaving-their-jobs-a1f0329d7ea4">frustrating</a>.</p><p>Therefore, I want to clear things up and show you that at Loft you’ll do meaningful, stimulating data science work that will actually drive business decisions and help Loft achieve its goals.</p><h3>1. You can focus on doing your best Data Science work</h3><p>We have excellent infrastructure and a world-class data engineering team, with whom you’ll work in a close partnership. This means you’ll spend less time cleaning and tidying data and more time performing analysis and driving business decisions. Our stack (AWS, Databricks, Spark, and others) allows us to use state-of-the-art machine learning models and ship them company-wide with little overhead.</p><p>You’ll have freedom to choose a setup that works for you. That includes choosing between Mac or PC, using a second monitor, etc. You can work at your desk or at our rooftop, with one of the best views in São Paulo. You’ll book meeting rooms seamlessly through Google Calendar, and will have brainstorm sessions using one of many whiteboards across the office. You’ll have fruits, snacks and coffee ready for you at any time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mj36TGkoIDibgY8v" /><figcaption>We hold several events at our rooftop. In this instance, we hosted a talk by brazilian explorer Amyr Klink.</figcaption></figure><h3>2. There’s a strong, company-wide buy-in and data-driven culture</h3><p>Loft’s goal is to leverage technology and <strong><em>data</em></strong> to disrupt the real estate market. Thus, being data-driven is one of Loft’s core values, so you won’t be hindered by politics and lack of buy-in. If you can use data to convince people of making a decision (which should be what you’re best at), there’s nothing else to stop you from having an impact.</p><p>Loft spent a small fortune buying data and partnering with companies that can bring us new data capabilities. We have access to real transaction values (which are very hard to get here in Brazil), which come in the form of a messy and expensive document called Matrícula. We invested a lot of our engineering team’s time to build the stack to process Matrículas and transform them in valuable, structured data ready for analysis. We acquired Spry, a company that works similarly to Amazon’s Mechanical Turk, but for data collection in the real world: we pay people to physically go to neighborhoods and collect information about real-estate demand, demographics, and more.</p><p>Florian, Loft co-CEO, even joked that “sometime we’ll need to take losses in some transactions, so the algorithms can learn”. Even though this is a joke and it’s very unlikely to happen, I’m confident that the company’s willing to experiment in order to learn and make the best decisions.</p><h3>3. You won’t work in an isolated team</h3><p>Loft adopts Spotify’s <a href="https://www.growly.io/spotify-engineering-model-with-squads-tribes-chapters-and-guilds/">engineering model</a> with Squads, Tribes, Chapters and Guilds. On your daily routine, you’ll work in a Squad, alongside a multidisciplinary team of business analysts, designers and developers.</p><p>Additionally, you’ll be very close to your colleagues at the Data Science Chapter, who will have your back on technical issues. Our team has a mix of backgounds in engineering, statistics, economics and business. Diversity matters to us: we always take into account how &quot;decorrelated&quot; our candidates&#39; thinking is from the rest of the group. As a company, we&#39;ve set a goal of fulfilling 30% of our tech positions with women for the first quarter of 2020, and we plan to add other types of diversity in the near future.</p><p>The DS Chapter holds a number of rituals for decision-making and training. The first is our Study Group: weekly training sessions to explore foundational machine learning, statistics, business and computer science concepts. We also encourage Data Scientists to explore new algorithms, read papers, and have small research projects through our LobsterWorks initiative, staying in touch with the state-of-the-art and sharing knowledge with colleagues. Finally, we hold weekly all hands meetings to discuss issues common to all DSs, using the <a href="https://medium.com/loftbr/meetings-from-hell-c82e651b8dcf">High Stakes Meetings</a> format, to keep them productive and inclusive.</p><p>Loft holds several internal and external meetups. In particular, we have an internal event called Tech &amp; Beers (yes, you got that right!) where we discuss bleeding edge issues in product, design, engineering and data science. <a href="https://medium.com/loftbr/j%C3%A1-ouviu-falar-no-hackday-da-loft-2dbf72b74d3f">We&#39;re also building a culture of hosting internal hackatons</a> (HackDays) for people to work on a side project outside their squad priorities and solve different problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kbtv4MD3CWaPpeII.png" /><figcaption>You&#39;ll work with a multidisciplinary team of business analysts, designers and developers.</figcaption></figure><h3>4. You’ll solve the hardest, most interesting problems in real-estate</h3><p>You’ll solve problems that no one in Brazil (and perhaps around the world) has solved before. We built the first <a href="https://loft.com.br/quanto-vale-meu-apartamento">Automated Valuation Model trained with real transactions in Brazil</a>, and we’re just beginning. Here are some examples of questions you’ll try to answer:</p><ul><li>How to find comparable houses when we have hundreds of dimensions to compare them? What criteria should we use?</li><li>What index should we use to bring older transactions values to current values, at the most granular level possible?</li><li>What should be Loft’s price premium, in order to add liquidity to the market and reduce friction in the process?</li><li>How do we account for risk in our models, given that price predictions won’t be perfect?</li><li>How can we explain prices generated by a black box model? Or, can we build interpretable models that achieve the same level of accuracy?</li><li>How long it takes for an apartment to sell? How price plays a role in liquidity?</li><li>How many kinds of apartments exist? What makes apartments &quot;different&quot; from one another?</li><li>Which apartments should be in our portfolio so we meet our business goals? In which markets we should bet?</li><li>How to help clients find the apartment of their dreams, through our website? How to recommend apartments for the client to visit?</li><li>How to engaje brokers in our platform, supplying intelligence to help them make more deals?</li></ul><p>And much more! Loft is just getting started and the possibilities for new business models (and new questions that you can answer using data science!) are endless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xy_HFbzyLX2xZXmB7ri74g.png" /><figcaption>A small sample of the scope of your models! Taken from our office.</figcaption></figure><h3>What are you waiting for?</h3><p>If this article made sense to you, I strongly advise you to apply to our<a href="https://jobs.lever.co/loft?department=Tech%20%26%20Product&amp;team=Data%20science"> Data Scientist positions</a> and come build the future of real estate with us. We’re looking forward to it!!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lX0w-j7YhBWPIUzj11C2yA.jpeg" /><figcaption>Our team as of December 2019.</figcaption></figure><p>Hope the article helped! If you have any questions, please don’t hesitate <a href="https://www.linkedin.com/in/gdmarmerola/">getting in touch with me</a> or the crew.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52eeb32cfa8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/loftbr/why-you-should-join-loft-as-a-data-scientist-52eeb32cfa8f">Why you should join Loft as a Data Scientist</a> was originally published in <a href="https://medium.com/loftbr">Loft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>