How to use R and Python together

If you can have 31 flavours of Icecream, why can’t you have atleast two flavours for open source data science. R for the data visualization and statistical libraries, Python for machine learning and the production environment. As part of my research for my upcoming book ” Python for R users – A Data Science Approach”, here are some ways to use both Python and R

  1. rpy2 communication channel from Python to R. rpy2 is an interface to R running embedded in a Python process. The project is mature, stable, and widely used. A lucid example of using it is given here at A Slug’s Guide to Python Screenshot from 2015-12-07 09:49:24https://sites.google.com/site/aslugsguidetopython/data-analysis/pandas/calling-r-from-python .
  2. conda -Jupyter – You can use R Kernel from within Jupyter/iPython . You can see here https://www.continuum.io/conda-for-r and https://www.continuum.io/blog/developer/jupyter-and-conda-r  Screenshot from 2015-12-07 09:53:18It uses the R kernel for Jupyter at http://irkernel.github.io/   . Here is a tutorial I wrote in Jupyter but in Python alone Screenshot from 2015-12-07 09:58:36 http://nbviewer.ipython.org/gist/decisionstats/c1684daaeecf62dd4bf4
  3. Beaker Notebook – You can see Beaker from http://beakernotebook.com/ . This is a relatively new kind of software and allows you to mix Python and R within the same notebook (unlike Jupyter which allows you either a Python or a R kernel) . Here is a notebook I created https://pub.beakernotebook.com/#/publications/5657e715-bdaf-4787-99fc-a0d7f37c3e38 Beaker allows even JS, Scala and otehr languages within the same notebook so its heavily amazing as an Idea.  I also note that they are silver sponsors at http://user2016.org/ through their parent company https://www.twosigma.com/

Screenshot from 2015-11-27 09:56:34

Using multiple languages in data science is clearly an idea whose time has come. Tools like Jupyter, rpy2 and Beaker can also speeden up this exciting trend.  The customer should dictate the need for data science, and the need should dictate the software, the software should dictate which data scientist to choose or skill up. Right now, we choose data scientists and software first and then try and fit them to the project use case.

Have an amazing 2016 for data science from the DecisionStats team and I hope you liked us in 2015!

 

 

Python for R Users A Data Science Approach

Coming up in the new year, is my new book on enabling polyglotism in data science. It is called Python for R Users :A Data Science Approach by Wiley ( due in 2016).

It will basically expose the target reader ( a data scientist professional) to a small sub set of the Python language which is most pertinent to data science.

p4r

What the Internet does for people like me in developing countries

  1. It gives us access to the best of knowledge, teaching, experts for free
  2. It gives us unfettered entertainment- free music in Youtube and TV shows like Game of Thrones instead of waiting years for our government to approve it
  3. It allows us to criticize our leaders on blog,s Facebook, Twitter without getting censored by corrupt politicians and a corrupt media- Government nexus
  4. It allows us to keep in touch via Skype via Facebook to people far way without straining our purse
  5. It allows us to learn a lot without paying a lot

That is just me- an urban citizen in a relatively decent economy. The benefits to underprivileged humans is even more

Superpowers

India used to be a Superpower but we declined. China was a superpower then it declined. So did Britain. So did Soviet Russia. The United States remains the aging Rocky Balboa of the superpowers, but you can see some decline in influence compared to when Clinton was President.

What do superpowers do?

  • They invest a lot of money in arms and defence
  • They earn a lot of money from trade so they can invest it in arms
  • They put their own interest ahead the interest of their neighbours and competitors
  • They pretend to go to war if you hurt a single citizen, but they themselves do not do much when thousands of their citizens are mal-treated by pollution, by exploitative working conditions, by small arms and guns, by crime, by inequality

Ultimately I think Switzerland is the only superpower. Their superpower lies in not pretending to be super at all.

During trade and now climate negotiations, the past and the present and the future superpowers collide. The needs of the many are more important than the egos of a few politicians , the brilliance of their advisers and the theatrics of a few.

Does the planet need a CEO? Probably yes, and the United Nations has failed to be a superpower or any power at all. It is just a conference holding organization.

The greatest generation that won Word War 2 in the West and defeated Colonialism in the East was succeeded by the Baby Boomer generation that just boomed and consumed. The next generation will pay the price of the past few generations. The country that has the best care of the next generation for a healthy productive workforce for both economic and defence deployment will win the race to be the Superbpower. Thats not a typo. Stop being a superpower and start being a superb power.

In the meantime, I would rather see Matt Damon colonize Mars and Rocky Balbao teach boxing to the nest generation.

Interview Maciej Fijalkowski PyPy

As part of my research for “Python for R Users- A Data Science Approach” (Wiley 2016), I came across PyPy (http://pypy.org/) What is PyPy?

PyPy is a fast, compliant alternative implementation of the Python language (2.7.10 and 3.2.5). It has several advantages and distinct features:

  • Speed: thanks to its Just-in-Time compiler, Python programs often run faster on PyPy.

  • Memory usage: memory-hungry Python programs (several hundreds of MBs or more) might end up taking less space than they do in CPython.

  • Compatibility: PyPy is highly compatible with existing python code. It supports cffi and can run popular python libraries like twisted and django.

  • Stackless: PyPy comes by default with support for stackless mode, providing micro-threads for massive concurrency.

Now R users might remember the debate with Renjin and pqR a few years ago. PyPy is an effort which has been around for some time and they are currently at an interesting phase.

Here is an interview with Maciej Fijalkowski of PyPy

pypy-logo (1)

Ajay Ohr-Why did you create PyPy to serve what need ?

PyPy– I joined pypy in 2006 or 2007, I don’t even remember, but it was about 2 years into the project existence. Shockingly enough, the very first idea was that there will be a python-in-python for educational purposes only. It later occurred to us that we can use the fact that PyPy is written in a high level language and apply various transformations to it, including just-in-time compilation. Overall it was a very roundabout way, but we came to the conclusion that this is the right way to provide a high-performance python virtual machine, after Armins experience writing Psyco, that likely only few people
remember.

Ajay Ohri-  Describe the current state of PyPy especially regarding to using NumPy. Can we use it for Pandas, matplotlib,seaborn, scikit-learn, statsmodels in near future. What hinders your progress?

PyPy- We are right now in the state of flux. I’m almost inclined to say “talk to us in a few weeks/months”. I will describe the status right now as well as possible near futures. Right now, we have a custom version of numpy that supports most of the existing numpy and can be used, although it does not pass all the tests. It has a very fast array item access routines, so you can write your algorithms directly in python without looking into custom solutions. It however, does not provide a C API and so does not support anything else from the numeric stack.

We’re considering also supporting the original numpy with CPython C API, which will enable the whole numeric stack with some caveats. Currently, there are ongoing discussions and I can get back to you once this is resolved.

Our main problem is the CPython C API and the dependency of the entire numeric stack on that. It exposes a lot of CPython internals, like reference counting, the exact layout of lists and strings etc. We have a layer that provides some sort of compatibility with that, but we need more work in order to make it more robust and faster. In the case of C API the main hindrance is funding – I wrote a blog post detailing the current situation: http://lostinjit.blogspot.co.za/2015/11/python-c-api-pypy-and-road-into-future.html We would love to support the entire numeric stack and we will look into ways that make it possible.

Ajay Ohri-A faster more memory efficient Python – will it be useful for analysis of large amounts of numeric data ?

PyPy- Python owes much of it’s success to good integration with the C ecosystem. For years we’ve been told that no one needs a fast Python, because what is necessary to be fast is already in C and we can go away. That has proven to be blatantly false with projects like apache spark embedding python as a way to do computations. There are also a lot of Python programmers and it’s a bit unfair to expect from them to “write all the performance critical parts in C” or any of the other custom languages built around Python, like Cython. I personally think that there is a big place for a faster Python and we’re mostly fulfilling that role, except exactly for the case of integration with numeric libraries that is absolutely crucial for a lot of people. We need to improve that story if we were to fill in that gap completely and while predicting future is hard, we would do our best to support the numeric stack a lot better in the coming months.

Ajay Ohri- What are the day to day challenges you face while working on PyPy? 

PyPy- That’s a tough question. There is no such thing in IT as “day to day challenges with technology” because if it’s really such a hindrance, you can usually automate it away. However, I don’t do only technical work these days, I deal a lot with people asking questions, looking at issues, trying to organize money for PyPy etc. This means that it’s very hard to pinpoint what a day-to-day activity is, let alone what it’s problems are.

The most repeating challenges that we face are how to make sure there is funding for chronically underfunded open source projects and how to explain our unusual architecture to newcomers. The technical issues we are heavily trying to automate away so if it’s a repeating problem, we are going to have more and more infrastructure to deal with it in a more systematic manner.

Ajay Ohri-  You and your highly skilled team could probably make much more money per
hour working for companies in consulting projects, Why devote time to open source coding tools. What is the way we can get more people to donate or  devote time

PyPy- It is a very interesting question, probably exceeding the scope of this interview, but I will try to give it a go anyway. I think by now it’s pretty obvious that Open Source is just a better way to make software, at least as far as infrastructure goes. I can’t think about a single proprietary language platform that’s not tied to a specific architecture. Even Microsoft and .NET are moving slowly towards Open Source, with Apple owning so much of the platform that no one has a say there.

That means that locally, yes, we could very likely make far more money working for some corporations, but globally it’s pretty clear that both our impact and the value we bring is much higher than it would be working for a corporation looking for its short term gains.

Additionally, the problems we are presented to work with are much more interesting than the ones we would likely encounter in the corporate environment. Funding Open Source is a very tricky question here and I think we need to find answers to that.

Everyone uses Open Source software, directly or indirectly and there is enough money made by companies profiting from using it to fund it. How to funnel this money is a problem that we’re trying to solve on a small scale, but would be wonderful to see the solution on a bigger scale.

Ajay Ohri- How can ensure automatic porting of algorithms from languages to Java Python R rather than manually creating packages. I mean if we can have Google Translate for Human languages, what can we do to make automatic translation of code between computer languages

PyPy- It would be very useful, but no one managed to do it well, maybe that means something. However, it’s quite easy to translate between languages naively – without taking into account best practices, more efficient ways of achieving goals etc. There is a whole discussion to be had, but I don’t think I’m going to have much insight into this.

About-

PyPy is a replacement for CPython. It is built using the RPython language that was co-developed with it. The main reason to use it instead of CPython is speed: it runs generally faster

See more here http://pypy.org/features.html

Understanding Indians and their Politics

I am not speaking of Indian Politicians here. Whatever Rahul Gandhi (or his speechwriter) , the ruling party in the state or the central government has always been a perennial source of bemusement to me, unlike the rest of my fellow Indians who keep fighting wars on Facebook and Social Media. Indeed I am surprised by the complete lack of conversation on politics when I am in North America, and a fellow friend of mine confirmed it, Europeans and Indians do talk more about politics than North Americans. Part of the reason is ideologies are much less pronounced between the extremes of political spectrum and  the general culture is to be polite and avoid controversial debates (which explains lack of politics as a dinner topic in the North American West)

I am speaking of politics as I have seen it practiced in Indian companies, startups and educational institutes. The level of politics is much higher than in USA or Canada, and the rudeness and crudeness is much more. Note I have interacted with people at extremely senior levels  (thanks to my blog and consulting) and junior levels (thanks to my teaching).

Without getting into anecdotal details and impose my projections as the New World Order on you- this is what I feel drives Politics between Ordinary Indians (the ones who never get figured in Newspapers)

  1. Insecurity drives politics- Prosperity and luxury is barely half a generation old. The economic insecurity of success is what drives politics in many institutes and institutions. People think- if someone else succeeds I will not get a slice of the pie. That’s because we all came from a socio-economic status where the pie was so small. How small ? Well when I was a Kid, we had one channel on Television, and there were waiting periods for a car for many years. Telephone was a luxury. Even though new India has many malls, many mobile phones and many luxuries, the trauma of childhood endures and ensures educated Indians use sharp elbows at the workplace to grab a share of the bonus or the pie or the economic success on offering
  2. Mistrust drives politics- Mistrust is driven by the different way Indians treat lying compared to North Americans. What is vilified as lying or cunning is treated as being chalu (smart) or jugaad ( innovative) in dodging questions, giving non-clear answers, or plain untruths. Why give promises you cannot keep. That is the Indian way of doing business. Why do people delay payments for vendors. That is both power politics and part economics. In addition a very slow legal system ensures people reach compromises on their own
  3. Saving Face- A big chunk of energy wasted by Indians is to save face, to avoid saying they failed. Everyone fails and everyone learns from their failures. But few people like to admit to mistakes and failures, and the culture in India is vindictive. Saving face is the number one reason people try to harass other people in workplaces when they are trying to leave. They ignore future relationships for the current need to save Face.
  4. Different Ethics– Some people point out to how people joke in Indian workplaces about women as misogny. That is universal. Men treat women badly in North America and are reigned only by legal system and that society. Some people point to hiring people only along state lines (North India, family members, South Indians, Bengalis, Mallus etc)  as regionalism. Midler forms of that racism exist in the US too. No we just have different ethics here. We treat mediocre old people with respect and treat brilliant young  people with condescension. Protestant ethics are different from the ethics of arguementative Indians

What is the solution? One solution is greater intermingling between people of different countries for Indians to learn about the best way to balance your personal ambitions with your professional needs. I recommend Canadians as the politest people among any country I have seen. Maybe we should invite more Canadians to settle in India rather than the other way around!

 

Interview PythonAnywhere

As part of my research for “Python for R Users- A Data Science Approach” (Wiley 2016) I am interviewing startups as well as package creators in the Python Data Science Space. Accordingly here is an interview with Giles Thomas, who leads PythonAnywhere, a UK based company that helps makes Python available anywhere thanks to cloud computing.
PA-logo-large
Ajay- Describe your journey to set up and create Python Anywhere. What were the reasons you chose Python. How has this choice helped you? Describe some usage stats and your core team.

PythonAnyWhere – Well, that’s a long story 🙂   There have been a couple of turns along the way…

In 2005 a couple of friends and I decided to start a company to create a new kind of spreadsheet.  We felt that Excel spreadsheets became unmanageable at scale, and a better solution for many use cases would be to create something that integrated a programming language more closely.  There definitely seemed to be a market for it, especially in the financial world.  We looked at the programming languages available, and Python stood out because it was very powerful, but also easy to learn.  The existence of numerical libraries like NumPy/SciPy was also a huge plus point.

So we built our spreadsheet, a desktop application called Resolver One with Python deeply integrated, and released it in 2008.  Unfortunately that coincided with a downturn in our target market of finance, and additionally we discovered that although many people were very keen on the product, there just weren’t enough of them to run a viable business based on it, especially under the desktop “buy a license and use it forever” kind of business model.  Over the following years we tried moving into alternative markets, and tried different approaches to selling it, but eventually we decided we needed to pivot to a different business, based on the knowledge we’d built up while creating Resolver One.

Our first pivot was simply to take the idea of Resolver One, and turn it into a cloud-based application.  This was codenamed “Project Dirigible”, and went live in 2010.  It was a highly-programmable spreadsheet, displayed in a web browser.  One of the most interesting things about it was that you could code the whole recalculation loop in Python — a default empty spreadsheet would contain code that looked something like this:

load_constants()
recalculate_formulae()

…so if you wanted to add your own functions, you could just def them above the code, and if you wanted to do something like goal-seeking, you could just put a while loop around the call to therecalculate_formulae function.   You can see (a slightly cut-down version of) Dirigible’s source code here:<https://github.com/pythonanywhere/dirigible-spreadsheet>

Dirigible was an excellent product; you could run complex analysis with a spreadsheet-like interface, but you could also (for example) spread calculations over a cluster of servers by calling one spreadsheet from another, kind of like a function call, running multiple spreadsheets in parallel.   And it started getting users, but again, not enough to keep the business going.

So we sat down and looked at how people were using it.  We discovered that for many users, the spreadsheet itself was an irrelevance.  What they wanted was an easy way to run a pre-configured Python distribution from their browser, without setting stuff up, configuring and maintaining machines, and so on.

We pivoted again, rapidly adjusted the code we had, and created PythonAnywhere.  We took a very user-centric attitude for development, keeping up conversations with as many users as possible, implementing the features they asked for (weighted by votes) — a hosted database, websites, cron-style scheduled tasks, and so on.  And that’s what has taken us to where we are today.

Right now, there are four people in the company including myself.  We’re based in Clerkenwell, in London (just up the road from the “Silicon Roundabout” area around Old Street which is London’s tech hub).  We have about 130,000 users, ranging from hobbyists playing around with ideas to data analysts, commercial websites, and startups.  Between them they’ve created about 50,000 websites, and started over 2 million in-browser consoles.  We provide the “Try Python now” in-browser console on Python.org, and also a popular “Try IPython” page for people who want to try it out as an alternative Python command-line.

 

Ajay- What are some of the ways your platform is used especially in data science? How does using Python Anywhere help with setting up data science

PythonAnywhere- That’s hard for us to say.  We provide a platform, and our users decide how to use it.  Data scientists tend to know more about what they’re doing than website creators, so they tend to talk to us less…

 

3) How does Python Anywhere facilitate teaching coding. Name some eamples or user feedback on using your platform for education

It’s hard for teachers to get all of their students set up with a working Python environment.  One person who does training for a living told us that in a five-day Python course, he can spend the first day simply getting Python and all of the appropriate packages installed on people’s laptops.  Django Girls have a special multi-hour “install session” the evening before each of their one-day courses just to get enough basic stuff installed to do their web development tutorial.

So having a site where teachers and trainers can just tell their students to sign up, and then know that everyone has a working development environment in a known state is a huge plus.

We also support console sharing; if you’re working in an in-browser Python console and have a question about something you’re seeing, and your teacher can’t easily come and look over your shoulder, it’s useful to be able to share the console with them so that they can see it in their own browser, and help you out.

Recently, we’ve started specifically adding extra features for teachers and students — for example, a student can designate another user as their teacher, which gives the teacher access to all of their consoles and their files, so that they can — for example — help out with problems, collect homework assignments, and that kind of thing.  More features along those lines are coming.

Finally (and perhaps less relevantly for your readers) people who are teaching website development love the way that it’s easy to deploy a website on PythonAnywhere.   A webdev tutorial that ends with a website running on someone’s laptop is inherently unsatisfactory.   If it’s a website, it should be online!   But teaching a beginner web developer how to configure Apache/nginx, mod_wsgi/uWSGI, and how to secure a machine in the cloud, and so on, is a huge deal and better avoided if possible.

In terms of numbers, it’s hard to say how many people are using us for education, because we offer cut-down free accounts and some courses just use them (we can sometimes spot those when a bunch of people sign up for free accounts with email addresses on the same .edu domain, but often we just can’t tell).  But we do know that there are about 2,000 students using our new education features, and it’s growing about 25% month-on-month.

 

Ajay- You give ipython and python consoles. Any plans to feature Jupyter or Beaker Notebook.

PythonAnywhere- Absolutely — Jupyter is in private beta at the moment.  If you’d like me to add you, just let me know the name of a PythonAnywhere account.

 

Ajay- How is using Python Anywhere a superior user experience than just taking a VM on Amazon AWS and doing the installs themself

PythonAnywhere- Well, firstly you don’t have to do the installs yourself 🙂   Installing Python and its dependencies is a bit of a pain.  Perhaps more importantly, maintaining everything is a huge pain.  Security fixes are constantly being made, and you have to keep up-to-date with them to avoid getting hacked.

Additionally, there’s server size.  We run on extra-large Amazon instances, and you can pay for as much or as little CPU seconds a day as you want, which makes it easier to scale up and down.

 

Ajay- What are your views on using Docker for Python.  Do you see Docker usage increasing faster? What are some of the disadvantages of using it.

PythonAnywhere- We’re using Docker internally for a subset of our in-browser consoles, and are gradually rolling it out to more of them as we discover bottlenecks and errors in our own code that uses it.

It’s an excellent way of sandboxing executable code; we’re using it to replace the sandboxing code we’d written ourselves, and it seems to be superior.  We think that in the future we may well move to a model where every console, every Jupyterhub kernel, every scheduled task, and every website worker process on PythonAnywhere runs in its own Docker container.

We are, however, also tracking alternatives with great interest.  Docker is getting quite large, and adding features that we don’t need (possibly at the expense of performance or even security).   rkt from CoreOS looks like it might be worth considering as an alternative at some point.

For more on PythonAnywhere see https://www.pythonanywhere.com/ and try out their free plan to test Python in the cloud. You can also email them at developers@pythonanywhere.com