<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/how-to-make-python-easier-for-the-r-user-revoscalepy/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://blog.revolutionanalytics.com/2017/11/revoscalepy.html"> Revolutions</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<p><em>by Siddarth Ramesh, Data Scientist, Microsoft</em></p>
<p>I’m an R programmer. To me, R has been great for data exploration, transformation, statistical modeling, and visualizations. However, there is a huge community of Data Scientists and Analysts who turn to Python for these tasks. Moreover, both R and Python experts exist in most analytics organizations, and it is important for both languages to coexist.</p>
<p>Many times, this means that R coders will develop a workflow in R but then must redesign and recode it in Python for their production systems. If the coder is lucky, this is easy, and the R model can be exported as a serialized object and read into Python. There are packages that do this, such as <a rel="nofollow" href="https://cran.r-project.org/web/packages/pmml/index.html" target="_blank">pmml</a>. Unfortunately, many times, this is more challenging because the production system might demand that the entire end to end workflow is built exclusively in Python. That’s sometimes tough because there are aspects of statistical model building in R which are more intuitive than Python. </p>
<p>Python has many strengths, such as its robust data structures such as Dictionaries, compatibility with Deep Learning and Spark, and its ability to be a multipurpose language. However, many scenarios in enterprise analytics require people to go back to basic statistics and Machine Learning, which the classic Data Science packages in Python are not as intuitive as R for. The key difference is that many statistical methods are built into R natively. As a result, there is a gap for when R users must build workflows in Python. To try to bridge this gap, this post will discuss a relatively new package developed by Microsoft, <a rel="nofollow" href="https://docs.microsoft.com/en-us/sql/advanced-analytics/python/what-is-revoscalepy" target="_blank">revoscalepy</a>. </p>
<h3>Why revoscalepy?</h3>
<p>Revoscalepy is the Python implementation of the R package <a rel="nofollow" href="https://docs.microsoft.com/en-us/machine-learning-server/r-reference/revoscaler/revoscaler" target="_blank">RevoScaleR</a> included with <a rel="nofollow" href="https://docs.microsoft.com/en-us/machine-learning-server/what-is-machine-learning-server" target="_blank">Microsoft Machine Learning Server</a>.</p>
<p>The methods in ‘revoscalepy’ are the same, and more importantly, the way the R user can <em>view </em>data is the same. The reason this is so important is that for an R programmer, being able to understand the data shape and structure is one of the challenges with getting used to Python. <em>In Python, data types are different, preprocessing the data is different, and the criteria to feed the processed dataset into a model is different. </em></p>
<p>To understand how revoscalepy eases the transition from R to Python, the following section will compare building a decision tree using revoscalepy with building a decision tree using <a rel="nofollow" href="http://scikit-learn.org/stable/" target="_blank">sklearn</a>. The <a rel="nofollow" href="https://www.kaggle.com/c/titanic" target="_blank">Titanic</a> dataset from Kaggle will be used for this example. To be clear, this post is written from an R user’s perspective, as many of the challenges this post will outline are standard practices for native Python users.</p>
<h3>revoscalepy versus sklearn</h3>
<p>revoscalepy works on Python 3.5, and can be downloaded as a part of <a rel="nofollow" href="https://docs.microsoft.com/en-us/machine-learning-server/what-is-machine-learning-server" target="_blank">Microsoft Machine Learning Server</a>. Once downloaded, set the Python environment path to the <code>python</code> executable in the MML directory, and then import the packages.</p>
<p>The first chunk of code imports the revoscalepy, numpy, pandas, and sklearn packages, and imports the Titatic data. Pandas has some R roots in that it has its own implementation of DataFrames as well as methods that resemble R’s exploratory methods. </p>
<div>
<pre><span>import</span> <span>revoscalepy</span> <span>as</span> <span>rp</span>;
<span>import</span> <span>numpy</span> <span>as</span> <span>np</span>;
<span>import</span> <span>pandas</span> <span>as</span> <span>pd</span>;
<span>import</span> <span>sklearn</span> <span>as</span> <span>sk</span>;
titanic_data <span>=</span> pd<span>.</span>read_csv(<span>'titanic.csv'</span>)
titanic_data<span>.</span>head()
</pre>
</div>
<h3>Preprocessing with sklearn</h3>
<p>One of the challenges as an R user with using sklearn is that the decision tree model for sklearn can only handle the numeric datatype. <em>Pandas has a categorical type that looks like factors in R, but sklearn’s Decision Tree does not integrate with this.</em> As a result, numerically encoding the categorical data becomes a mandatory step. This example will use a one-hot encoder to shape the categories in a way that sklearn’s decision tree understands.</p>
<p>The side effect of having to one-hot encode the variable is that if the dataset contains high cardinality features, it can be memory intensive and computationally expensive because each category becomes its own binary column. While implementing one-hot encoding itself is not a difficult transformation in Python and provides good results, it is still an extra step for an R programmer to have to manually implement. The following chunk of code detaches the categorical columns, label and one-hot encodes them, and then reattaches the encoded columns to the rest of the dataset.</p>
<div>
<pre><span>from</span> <span>sklearn</span> <span>import</span> tree
le <span>=</span> sk<span>.</span>preprocessing<span>.</span>LabelEncoder()
x <span>=</span> titanic_data<span>.</span>select_dtypes(include<span>=</span>[<span>object</span>])
x <span>=</span> x<span>.</span>drop([<span>'Name'</span>, <span>'Ticket'</span>, <span>'Cabin'</span>], <span>1</span>)
x <span>=</span> pd<span>.</span>concat([x, titanic_data[<span>'Pclass'</span>]], axis <span>=</span> <span>1</span>)
x[<span>'Pclass'</span>] <span>=</span> x[<span>'Pclass'</span>]<span>.</span>astype(<span>'object'</span>)
x <span>=</span> pd<span>.</span>DataFrame(x)
x <span>=</span> x<span>.</span>fillna(<span>'Missing'</span>)
x_cats <span>=</span> x<span>.</span>apply(le<span>.</span>fit_transform)
enc <span>=</span> sk<span>.</span>preprocessing<span>.</span>OneHotEncoder()
enc<span>.</span>fit(x_cats)
onehotlabels <span>=</span> enc<span>.</span>transform(x_cats)<span>.</span>toarray()
encoded_titanic_data <span>=</span>  
  pd<span>.</span>concat([pd<span>.</span>DataFrame(titanic_data<span>.</span>select_dtypes(include<span>=</span>[np<span>.</span>number])), 
  pd<span>.</span>DataFrame(onehotlabels)], axis <span>=</span> <span>1</span>)
</pre>
</div>
<p>At this point, there are more columns than before, and the columns no longer have semantic names (they have been enumerated). This means that if a decision tree is visualized, it will be difficult to understand without going through the extra step of renaming these columns. There are techniques in Python to help with this, but it is still an extra step that must be considered.</p>
<h3>Preprocessing with revoscalepy</h3>
<p>Unlike sklearn, revoscalepy reads pandas’ ‘category’ type like factors in R. This section of code iterates through the DataFrame, finds the string types, and converts those types to ‘category’. In pandas, there is an argument to set the order to False, to prevent ordered factors.</p>
<div>
<pre>titanic_data_object_types <span>=</span> titanic_data<span>.</span>select_dtypes(include <span>=</span> [<span>'object'</span>])
titanic_data_object_types_columns <span>=</span> np<span>.</span>array(titanic_data_object_types<span>.</span>columns)
<span>for</span> column <span>in</span> titanic_data_object_types_columns:
    titanic_data[column] <span>=</span> titanic_data[column]<span>.</span>astype(<span>'category'</span>, ordered <span>=</span> <span>False</span>)
titanic_data[<span>'Pclass'</span>] <span>=</span> titanic_data[<span>'Pclass'</span>]<span>.</span>astype(<span>'category'</span>, ordered <span>=</span> <span>False</span>)
</pre>
</div>
<p>This dataset is already ready to be fed into the revoscalepy model.</p>
<h3>Training models with sklearn</h3>
<p>One difference between implementing a model in R and in sklearn in Python is that sklearn does not use formulas.</p>
<p>Formulas are important and useful for modeling because they provide a consistent framework to develop models with varying degrees of complexity. With formulas, users can easily apply different types of variable cases, such as ‘<code>+</code>’ for separate independent variables, ‘<code>:</code>’ for interaction terms, and ‘<code>*</code>’ to include both the variable and its interaction terms, along with <a rel="nofollow" href="http://faculty.chicagobooth.edu/richard.hahn/teaching/formulanotation.pdf" target="_blank">many other convenient calculations</a>. Within a formula, users can do mathematical calculations, create factors, and include more complex entities third order interactions. Furthermore, formulas allow for building highly complex models such as mixed effect models, which are next to impossible build without them. In Python, there are packages such as ‘statsmodels’ which have more intuitive ways to build certain statistical models. However, statsmodels has a limited selection of models, and does not include tree based models.</p>
<p>With sklearn, <code>model.fit</code> expects the independent and dependent terms to be columns from the DataFrame. Interactions must be created manually as a preprocessing step for more complex examples. The code below trains the decision tree:</p>
<div>
<pre>model <span>=</span> tree<span>.</span>DecisionTreeClassifier(max_depth <span>=</span> <span>50</span>) 
x <span>=</span> encoded_titanic_data<span>.</span>drop([<span>'Survived'</span>], <span>1</span>)
x <span>=</span> x<span>.</span>fillna(<span>-</span><span>1</span>)
y <span>=</span> encoded_titanic_data[<span>'Survived'</span>]
model <span>=</span> model<span>.</span>fit(x,y)
</pre>
</div>
<h3>Training models with revoscalepy</h3>
<p>revoscalepy brings back formulas. Granted, users cannot view the formula the same way as they can in R, because formulas are strings in Python. However, importing code from R to Python is an easy transition because formulas are read the same way in the revoscalepy functions as the model fit functions in R. The below code fits the Decision Tree in revoscalepy.</p>
<div>
<pre><span>#rx_dtree works with formulas, just like models in R</span>
form <span>=</span> <span>'Survived ~ Pclass + Sex + Age + Parch + Fare + Embarked'</span>
titanic_data_tree <span>=</span> rp<span>.</span>rx_dtree(form, titanic_data, max_depth <span>=</span> <span>50</span>)
</pre>
</div>
<p>The resulting object, <code>titanic_data_tree</code>, is the same structural object that <code>RxDTree()</code> would create in R. Because the individual elements that make up the <code>rx_dtree()</code> object are the same as <code>RxDTree()</code>, it allows R users to easily understand the decision tree without having to translate between two object structures.</p>
<h3>Conclusion</h3>
<p>From the workflow, it should be clear how revoscalepy can help with transliteration between R and Python. Sklearn has different preprocessing considerations because the data must be fed into the model differently. The advantage to revoscalepy is that R programmers can easily convert their R code to Python without thinking too much about the ‘Pythonic way’ of implementing their R code. Categories replace factors, <code>rx_dtree()</code> reads the R-like formula, and the arguments are similar to the R equivalent. Looking at the big picture, revoscalepy is one way to ease Python for the R user and future posts will cover other ways to transition between R and Python.</p>
<p>Microsoft Docs: <a rel="nofollow" href="https://docs.microsoft.com/en-us/sql/advanced-analytics/python/what-is-revoscalepy" target="_blank">Introducing revoscalepy</a></p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://blog.revolutionanalytics.com/2017/11/revoscalepy.html"> Revolutions</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/XyMOSIFh9Ow" height="1"></a></div>