<?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 Peter Castellucci on Medium]]></title>
        <description><![CDATA[Stories by Peter Castellucci on Medium]]></description>
        <link>https://medium.com/@castelluccipeter?source=rss-3a96ec6263df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*olPW8pury8A61tF1q5v4PA.jpeg</url>
            <title>Stories by Peter Castellucci on Medium</title>
            <link>https://medium.com/@castelluccipeter?source=rss-3a96ec6263df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:05:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@castelluccipeter/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[Random Forest Regression in Python]]></title>
            <link>https://castelluccipeter.medium.com/random-forest-regression-in-python-7b8d94958caa?source=rss-3a96ec6263df------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8d94958caa</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[k-fold-cross-validation]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Peter Castellucci]]></dc:creator>
            <pubDate>Fri, 02 Jul 2021 16:37:05 GMT</pubDate>
            <atom:updated>2021-07-02T16:37:05.466Z</atom:updated>
            <content:encoded><![CDATA[<h4>Predicting global sales</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmkGWDFcM7OuyIWTE6cBog.png" /></figure><p>Random forests are an ensemble learning method for classification, regression and various other tasks. Ensemble means the algorithm uses numerous decision trees concurrently, in order to produce one optimal predictive mode. A common problem with decision trees alone is overfitting, random forests reduce overfitting since the final classification occurs through a process of “majority voting” and regression problems return the mean of the the individual trees.</p><p>Random forests, although incredibly useful, are quite often referred to as a “black box” algorithm since the user has limited ability to tweak the model, data goes in and predictions or classifications come out.</p><p>In this article we will go through how to implement a random forest regression to predict global sales of video games based on numerous quantitive and categorical variables. We will walk go through how to preprocess the data in Python and then how to fit the model using Sklearn. Finally, we will briefly discuss some ways to improve random forests even further.</p><h4>Preprocessing the data</h4><p>Sklearn is a great library for all sorts of machine learning algorithms and also includes many methods to preprocess data. First we import some of the libraries we will be using.</p><pre>import numpy as np <br>import pandas as pd<br>import seaborn as sns<br>import sklearn as sk<br>from scipy.stats import probplot<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import mean_squared_error</pre><p>As for almost all machine learning algorithms we will have a training data set and a test data set. Our task is to predict <a href="https://www.kaggle.com/c/datern-ml-competition/data">Global Sales</a> from this kaggle data set, we will be working in kaggles version of jupyter notebook.</p><pre>train = pd.read_csv(&quot;/kaggle/input/datern-ml-competition/Kaggle Datern - Training Set.csv&quot;)<br>test = pd.read_csv(&quot;/kaggle/input/datern-ml-competition/Kaggle Datern - Test Set.csv&quot;)</pre><p>Once the data is imported our first task is to preprocess the data to make it suitable for the algorithm. Looking at the data we can see there are some categorical variables which need to be dealt with since computers can only understand numbers, not letters!</p><pre>train.info()</pre><p>There are many ways to deal with categorical variables. Here we go for the simplest method where every category is given a unique integer based on alphabetical ordering, known as label encoding.</p><pre>#Convert categorial variables with label encoder</pre><pre>from sklearn.preprocessing import LabelEncoder</pre><pre># Create arrary of categorial variables to be encoded<br>categorical_cols = [&#39;Name&#39;, &#39;Platform&#39;, &#39;Genre&#39;, &#39;Publisher&#39;, &#39;User_Score&#39;, &#39;Developer&#39;, &#39;Rating&#39;]</pre><pre>le = LabelEncoder()</pre><pre># apply label encoder on categorical feature columns<br>train[categorical_cols] = train[categorical_cols].apply(lambda col: le.fit_transform(col))</pre><p>Next we need check our dataset for Null values since sklearns random forest algorithm cannot deal with them. Checking for Null values we see there are a few columns with quite a large number.</p><pre>#Check for null values<br>train.isnull().sum()</pre><pre>ID                    0<br>Name                  2<br>Platform              0<br>Year_of_Release     246<br>Genre                 2<br>Publisher            48<br>EU_Sales              0<br>Global_Sales          0<br>Critic_Score       8195<br>Critic_Count       8195<br>User_Score         6421<br>User_Count         8805<br>Developer          6358<br>Rating             6470<br>dtype: int64</pre><p>To deal with these Null values we will utilise Sklearns SimplerImputer, this function can use various strategies to replace the missing values, such as calculating the median which is the strategy we use.</p><pre>from sklearn.impute import SimpleImputer</pre><pre>#Initiate simpler imputer which deals with Null values by replacing them with the median<br>imp = SimpleImputer(missing_values=np.nan, strategy=&#39;median&#39;)</pre><pre>#Transform null values<br>imp.fit_transform(train)<br>idf=pd.DataFrame(imp.fit_transform(train))</pre><pre>#Create new dataframe with null values replaced with the median<br>idf.columns= train.columns<br>idf.index= train.index</pre><pre>#Check for null values<br>display(idf.isnull().sum())</pre><p>Checking again for Null values we can see we have successfully replaced them with the median. Now the data is processed and ready to go we can start to fit the model.</p><h4>Fitting the random forest</h4><p>To fit the model we need to split the data frame into the predictor variables and the target variable ‘Global_Sales’, these are then split again into training and tests set using sklearns train_test_split. The split size can be chosen but a common choice is for the test size to be 0.2.</p><pre># Import train_test_split function<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestRegressor</pre><pre>#Get independent variables<br>X = idf.drop(columns = [&#39;Global_Sales&#39;])</pre><pre>#Get dependent variable<br>Global_Sales_column = idf.loc[:,&#39;Global_Sales&#39;]</pre><pre>#Turn dependent variable into an array<br>y = Global_Sales_column.values</pre><pre># Split dataset into training set and test set<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)</pre><p>There is no method to choose the optimal number of trees and the maximum depth of the trees since every forest will be optimal for different amounts, hence we must use trial and error by scoring each model.</p><pre>#Find optimal number of trees<br>n_estimators = [50, 100, 150, 200, 250, 300, 350]</pre><pre>for val in n_estimators:<br>    score = cross_val_score(ensemble.RandomForestRegressor(n_estimators= val, random_state= 42), X, y, cv = kf, scoring=&quot;neg_root_mean_squared_error&quot;)<br>    print(f&#39;Average score({val}): {&quot;{:.3f}&quot;.format(score.mean())}&#39;)</pre><pre>#Find optimal depth<br>n_depth = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30]</pre><pre>for val in n_depth:<br>    score = cross_val_score(ensemble.RandomForestRegressor(n_estimators= 100, max_depth = val, random_state= 42), X, y, cv = kf, scoring=&quot;neg_root_mean_squared_error&quot;)<br>    print(f&#39;Average score({val}): {&quot;{:.3f}&quot;.format(score.mean())}&#39;)</pre><p>We find that there is little improvement after 300 trees and a maximum depth of 6, hence we opt to use these values for our model.</p><pre>#Create the random forest model with 300 trees and a max depth of the trees of 6<br>regr = RandomForestRegressor(n_estimators=300,max_depth=6)</pre><pre>#fit the model with our training data<br>regr.fit(X_train, y_train)</pre><p>Finally we can make the predictions of ‘Global_Sales’ using this random forest model and calculate the model’s accuracy using the root mean squared error between the predictions and the y_test set created earlier.</p><pre>#Calculate the predictions<br>predictions = regr.predict(X_test)</pre><pre>#Calculate the root mean squared error<br>rmse = np.sqrt(mean_squared_error(y_test, predictions))<br>print(rmse)</pre><p>We find that our model has a root mean squared error of 0.002118 which is a high degree of accuracy. We can now use this model to predict global sales for the original test data, it is important to use the model on other datasets in order to make sure it generalises well and we have not overfitted.</p><h4>Improving the accuracy</h4><p>The accuracy of our predictions can be improved using a method of cross validation such as k-folds. k-folds works by splitting the whole training data set into k subsets of testing and training data (folds). For each model the first fold is used as a validation set, and the model is fit on the remaining k − 1 folds. This method works fantastically at improving the accuracy of the predictions from the model on unseen data since it avoids overfitting.</p><p>To conclude, random forest is a robust method that can generalise to many problems despite its lack of control given to the user. I hope this article has shown you that with the right preprocessing random forest is a relatively simple algorithm to implement in Python and has a high degree of accuracy. If you would like to learn more about how random forests work I would recommend the article ‘<a href="https://medium.datadriveninvestor.com/random-forest-regression-9871bc9a25eb">A Beginners Guide to Random Forest Regression’</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8d94958caa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Location Analytics-What Variables Effect House Prices?]]></title>
            <link>https://castelluccipeter.medium.com/location-analytics-what-variables-effect-house-prices-43f6605360b2?source=rss-3a96ec6263df------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f6605360b2</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[location-analytics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Peter Castellucci]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 17:27:16 GMT</pubDate>
            <atom:updated>2021-06-30T17:27:16.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rChtgKNCHSHyP0xfkwiZJw.jpeg" /></figure><p>For years businesses have relied on intuition to make location based decisions. Recent advancements in <strong>GIS (Geographical Information Systems), Location Intelligence </strong>and <strong>Data Analytics</strong> have allowed businesses to make more informed decisions based on what the data shows. A Geographical information system is a computer based framework which allows the user to capture, analyse and create visualisations from spatial geographic data.</p><p>In this article I will go through a few methods and visualisations in Tableau and Python which can be used to create some insights that would be useful to a business in the housing market. The data set used is from <a href="https://www.kaggle.com/janiobachmann/melbourne-comprehensive-housing-market-analysis">Kaggle</a> and gives data on house prices and many other variables which may contribute to house prices in Melbourne, Australia. There are a lot of insights which can be gained from this data sets. I would encourage you to explore the data yourself and see what conclusions you can draw.</p><p>An obvious first variable to investigate is the distance from the city centre. To analyse the distance from the centre in each region I created the following box plot in Tableau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_sTxi171Cjj_IbM0N7h7Q.png" /><figcaption><strong>Fig 1 -Box plot of distances from city centre for each house in each region, sorted by increasing house price.</strong></figcaption></figure><p>From this plot we can begin looking for trends and gathering useful information for future analysis. The box plots are ordered by increasing average house price from left to right. Ordering by another variable is a useful way to look for more trends in one plot, this box plot suggests there is a negative correlation between distance from city centre and house price.</p><p>Another important variable to investigate is the number of houses sold per region as this will give an indication of the demand for houses in each region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MUW6KhZu_OjTfMYYqekIw.png" /><figcaption><strong>Fig 2 -Bubble chart showing the average price per region against the number of houses sold, the size of the bubbles correspond to average building size.</strong></figcaption></figure><p>From the bubble chart we can infer a number of details and features. There is a clear positive correlation between house price and the house demand in that region. Furthermore, the third variable based on the size of the bubbles allows us to interpret that the house price is also positively correlated with the building size.</p><p>After an initial investigation in Tableau we can start to look further into potential trends and correlations with Python. For example it would be good to put numbers on the correlations seen in earlier graphs so we can have a more mathematical grasp on how significant these variables are related to house price. To do this I created a correlation matrix in python and plotted the following heat map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*aMmuBFb9sAaudMWt0vA5vQ.png" /><figcaption><strong>Fig 3 -</strong>Heat map to show the correlations between all variables given in the dataset.</figcaption></figure><p>As expected there is a negative correlation between house price and distance from city centre. One can also spot that there is a significant correlation between price and number of rooms and car spaces, as well as a significant negative correlation between price and year the house was built.</p><p>Armed with these insights it would now be useful to fit a multivariate regression model based on some of the most important variables. The heat map would again be useful to see the correlations between the independent variables since a regression analysis cannot be achieved for high correlations.</p><h4><strong>Conclusions</strong></h4><p>Some conclusions we can draw from this research include</p><ul><li>The regions closer to the city centre have more expensive houses.​</li><li>Older houses are more expensive.​​</li><li>The size of the house and the number of rooms in the house significantly affects the price.​</li><li>Southern Metropolitan is the most expensive region, in the highest demand and has the biggest houses.</li></ul><p>We now have useful information backed up by data that various businesses could utilise. The next step would be to provide some potential actions the business could take based on these findings. An estate agent might use one of the top sellers to train the other sellers.​​ A house building company could use the regression model to find the best location for new builds, to maximise profit.</p><p>These are some of the basic ways you could begin a location analysis and I hope they have been helpful, in practice one would take the statistical nature of the research further to provide insights that we can be more mathematically confident in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f6605360b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>