Some Bits: Nelson's log

10 posts about jupyter

soup-to-nuts Jupyter notebook project

I just finished a short project I was working on, an analysis of data from League of Legends about how people are using the new rune system the game just introduced. The report is here and speaks for itself; writing here to talk about how I wrote this up. For context the project consisted of scraping about 250 web pages off a site, parsing them, stuffing data into a database, then analyzing it for patterns.

I decided to do this project as a purely Jupyter notebook project. In the past I’ve used notebooks frequently for data exploration but seldom as my full workflow. In particular it’s not clear notebooks are well suited for production scripts like “scrape this website” but I decided to do it anyway, with some success.

Some notes:

  • IPython has a thing where if an output cell is too tall it will make it smaller with an internal scrollbar. You can adjust that size with some simple Javascript.
  • I wish there were a way to hide cells. I want to keep some code around but I don’t want it to show in whatever report I’m publishing.
  • I hid the code entirely so civilians don’t get overwhelmed. I did this with a “toggle code” button borrowed from here.
  • I wish notebooks had explicit named checkins. I find the commit cycle of git is good discipline for getting me to do only one thing at a time. There’s a Checkpoint feature in notebooks which is similar but it doesn’t prompt you for a comment so I never use it.
  • It seems worth noting that my virtualenv for the project was 550MB. Pandas is big but I wanted it. Somehow I ended up with all of scipy even though I just wanted a few colormaps from Seaborn.

Scraper

I wrote the scraper with BeautifulSoup. As noted before there’s a nice addon for Jupyter that gives notebook previews of scraped data. Interactively working towards robust scrapers was really nice in a notebook. I ended up creating a main loop to scrape all the pages I needed and write them to a simple shelf database. The full scrape only took a few minutes so I just ran it interactively; this wouldn’t work nearly as well for a run that takes hours or is perpetual. One clever thing I did was create a new shelf database for each run, so I could keep old data easily.

Data processor and database creator

My second notebook loaded the scraped data from a shelf and processed it down to a more query-friendly SQLite database. Like shelf files I kept one timestamped database per run so I could easily go back to old data. Interactive development for this part was nice, particularly being able to do some very simple sanity check reports along the way.

I used the dataset module to create the database for me. It’s quite nice; create a list of dicts and it just makes a schema from them and writes the data, no fuss.

Ad hoc queries

For my primary data exploration I used ipython-sql to run SQL code directly as Notebook cells, no Python requires. This was my favorite use of notebooks and no surprise, it’s exactly the kind of work Jupyter is for. Write query, see data as HTML table, done. ipython-sql allows you to mix in Python code, you can capture the results of queries as result sets and do things with them. I started trying to get fancy with that and realized that wasn’t working very well; better to stick to mostly SQL. Also the presentation options are very limited, once I started thinking about sharing this data with other people I wanted to give it more polish.

Final report

For my final report I made a new notebook using Pandas DataFrames with sql queries developed in the ad hoc notebook. Mostly used Pandas as a better table presenter; it makes it easy to round off numbers to 2 digits or color data cells based on their contents. Also I ended up using Pandas Python code to manipulate my data after it came from the database, convolutions that would be awkward to do with SQL queries. This all worked fairly well but in retrospect part of me thinks I should have gone with styling JSON blobs using D3 instead. That’s more work though.

The result of this sheet is the report itself and while it’s a fine Notebook it’s not a very nice deliverable for my target audience. LoL players are used to infographics like this, not boring tables. I’m uninterested in doing that kind of presentation though, so I stopped there.

Update: I posted this to Reddit and got on the front page, as much attention as I expect for a project like this. OTOH most of the discussion doesn’t seem informed by the data I presented. Good ol’ Internet people. Lesson for me in the value of presenting simple conclusions, not data.

Setting up a new Jupyter data exploration notebook

Been a month since I had to set up Jupyter for a new project. Here’s all the steps, which seems awfully complicated for a “standard setup”. Some of that is idiosyncratic to me though.

  1. newvenv
    a shell alias I have. What it does:
    python3 -m venv venv;
    source venv/bin/activate;
    pip install -U setuptools pip
  2. pip3 install jupyter
  3. pip3 install matplotlib numpy pandas seaborn requests
    these are standard visualization libraries, plus a sane HTTP client. Fortunately these install from precompiled wheel files so it’s quick
  4. jupyter notebook --no-browser >> jupyter.log 2>&1 &
    Jupyter really, really wants to be an interactive program. This sort of makes it headless.
  5. ssh -L 8888:localhost:8888 my-server.example.com
    I’ve installed and run Jupyter on a server. I run this command on my local development machine to forward the port to access it.
  6. open http://localhost:8888/ in a browser
  7. %matplotlib inline
    Be sure to run this as the first command in the notebook

 

Better Jupyter charts: animation

Well this is neat; matplotlib supports generating animations, and you can inline HTML5 video right in Jupyter. The only wrinkle I hit is the stupid Ubuntu ffmpeg/avconv kerfuffle. Trying to produce the animation by default produced the error “KeyError: ‘ffmpeg’”; I solved it by setting

matplotlib.rcParams[‘animation.writer’] = ‘avconv’

There’s a GitHub comment saying that avconv may not be reliable, but it seems to be working for me in Chrome.

Now to figure out how to make this work with Seaborn. Some hints here.

Update: the Seaborn hints mostly just worked. Hilariously the inline video solution is to encode the whole MP4 file in a data64 blob right in the HTML, some 130k worth in my case. Hey, it works.

Better Jupyter charts: Seaborn

Took a quick tour through Seaborn, the enhancement library for matplotlib. It’s very good! It does two basic things. It makes the default matplotlib charts prettier, and it gives you an easy API to do some fancier types of statistical visualization. I’d say it’s a no-brainer to use Seaborn if you’re doing exploratory data visualizations. It still just renders raster images in Jupyter, so it doesn’t fulfill my goal of having nice SVG interactive charts in the browser, but Seaborn is solving a different problem.

Prettier

“Drawing attractive figures is important”, the docs say, and I couldn’t agree more. Seaborn reconfigures matplotlib so the default charts look better. I don’t just mean nice anti-aliasing, but also reasonable grid ticks and color choices. Seaborn has good perceptual palettes which are really important. I believe stock matplotlib has recently improved in part with input from Seaborn.

The other part of “attractive figures” is the Seaborn API is DataFrame-aware and will label your plots using the labels in your DataFrame. Getting nicely labelled axes and titles and stuff takes several lines of manual code with matplotlib; with Seaborn it’s a single line of code.

Fancier statistics

The meatier part of Seaborn is it has more complex chart types built in.

Distributions are mostly what I’ve used. In detail:

  • distplot: 1 dimensional distributions, an enhancement of matplotlib.hist. It adds a continuous kernel density estimate to the bars, and also has a rug-plot option.
  • jointplot: 2 dimensional distributions, an enhancement of matplotlib.scatter. Adds correlation coefficient, histograms on the side, a sort of quicky ggplot. Can also do continuous contour plots. One drawback is there doesn’t seem to be any easy way to set the hue of the individual dots, so no sneaking in a third dimension of data. Pass in kind=”reg” to have it try to fit a regression curve to the scatter.
  • hexbins: 2 dimensional histograms
  • pairplot: pairwise jointplots for your N dimensional dataset. So nice to have this in a single command, although it’s unwielding for N > 5 or so. (Note this does have a way to set the hue of individual dots.)

Regressions are for fitting various kinds of statistical models to your dataset.

Categorical graphs are for looking at statistics for qualitative categories, plots like swarm plots and violin plots. They’re really quite beautiful. Here’s a sample visualization of the distribution of a variable (y axis) for each of 5 categories (the x axis). I’ve used a violin plot which shows a KDE continuous approximation, along with a swarm plot to show the actual dots on top of it. (The data set is # of games players have for each of 5 roles in League of Legends. That one crazy outlier is Fiddlesticks Jungle; players tend to have 220+ games on him!)

download.png

Finally data-aware grids are used for making small multiples plots of the same dataset. I already mentioned pairplot, for doing NxN visualizations of N variables, pairwise. FacetGrid is a tool for quickly generating a bunch of graphs comparing across multiple categorical variables.

Conclusion

I like Seaborn. I like that it looks good out of the box. I also like that it allows me to make more sophisticated graphs very simply, with little effort. It may be a little too easy; I’m not sure a violin plot is really the right treatment of that data above, for instance. But it sure looks good!

Better Jupyter charts: mpld3

As much as I’m liking Jupyter, I don’t much like that matplotlib is the default charting library. I mean matplotlib gets the job done, and it’s powerful and popular. But end of the day you’re rendering raster images with 10+ year old software. (Even if seaborn has made the raster images better.) We’ve got a fancy browser viewer, why not have fancy SVG/Javascript graphs?

That’s what mpld3 provides. Using it is as simple as importing it and calling mpld3.enable_notebook(). All (most?) of your old matplotlib API code will still work. mpld3 emulates that charting API but renders to SVG using D3, instead of rendering to a static image. It’s kinda nutty that it just works. The resulting pixels look good, although admittedly matplotlib’s raster backend (agg?) looks pretty good too. 

The real advantage is the graphs are manipulable with Javascript. Out of the box every graph is now pannable / zoomable, right in the browser window. You can do fancy linked brushes across multiple figures.

There’s also plugins to add more capability. PointLabelTooltip plugin is particularly nice, it adds an easy way to have HTML tooltips on a scatterplot when you hover the points. There’s also MousePosition (useful for images).

And... and that’s about it. After a bunch of work a couple of years ago development seems to have stalled. That’s OK, it’s useful as is. Particularly since it’s such a simple drop-in upgrade for matplotlib.

Probably time to look at alternatives. Bokeh is the “better matplotlib” and includes a bunch of browser / notebook stuff. However it’s still rendering raster images (albeit in an HTML5 canvas). The examples sure are pretty though. I also see frequent references to VisPy, which is GL based, but although there’s some noises made about WebGL and notebooks I can’t find a working demo. Other options I’ve run across are pygal, bqplot and Altair. People also talk about Plotly but it’s a hosted system and costs money.

Some other thoughts on this topic: The future of visualization in Python, In defense of Matplotlib, Overview of Python Visualization Tools

While I’m here, ipywidgets is kind of nutty. It lets you add interactive controls to a notebook like sliders and input boxes, to turn your notebook into an interactive app.

 

Notes from a Jupyter/Dataframe project

I’m looking at some League of Legends data; champion win rates by player tier. I’m curious which champions have higher win rates with skilled players, and/or which are more popular. You can see the resulting report here, notebook (without nice CSS) is here.

Learning me some Jupyter and Pandas

Really I’m using this project to get more comfortable with using Jupyter and Pandas DataFrames to analyze data. The DataFrames part is overkill; I’ve got about 10k of data, not the 10G of numbers DataFrames’ highly optimized code is for. But DataFrames have lots of functions that replicate SQL’s analysis capabilities and they display nicely in Jupyter, so here I am.

My data starts as web pages of HTML tables. I imported those into a single Google Spreadsheet with multiple tabs.For a single sheet, rows are champions (120 or so) and columns are statistics like win rate or games played (5 of them). There’s 7 sheets, one per tier Bronze / Silver / Gold / ... I then exported those sheets as CSV files, one per tier, for analysis. (Google Spreadsheets turns out to be a remarkably good HTML table data scraper.)

I then played with various forms of Python code for reading those CSV files and doing some statistics on them. Starting with simple raw Python data structures, a bunch of dicts and tuples all the way up to a full Panda Panel. Along the way I learned how to analyze the data using Pandas a bit, and to format the results nicely in Jupyter. My real goal here is to make interactive reporting as natural as if I’d loaded all the data into a SQL database. Being able to do natural things like sum all values, or get the average of numbers grouped by some criterion.

Data loading

One thing I found is that the more I whipped my data into Pandas shape, the simpler my code got. I finally settled on doing all the parsing way up front, when I read the CSV files, to make clean DataFrame objects with well named columns and rows. That makes the later analysis code much simpler.

The read_csv() function has a lot of options to configure parsing, it’s worth the time to set them. “thousands=,” for instance will allow it to parse things like “1,523,239” as an integer and not a string. I also ended up doing “header=0” and specifying my own “names=[...]” for columns, just so I could make the names valid Python identifiers. (You can access named things in a DataFrame with attribute syntax; either df[“winrate”] or df.winrate.)

But the most important thing for read_csv was index_col. The concept of index in a DataFrame is particularly important. That’s the unique key that names each row; in my data the index is the champion name. In a CSV file this would probably be the column named “label” or the like. In a database table it’d be the primary key. The word index is used all over the docs and it confuses me all the time. Once I set up my data index correctly the code got a lot better.

The thing I find most confusing is the shape of data. DataFrames, for instance, mostly seem to want to treat a column of numbers as a single feature. But I really need to work row-rise most of the time. Slicing a DataFrame is particularly bizarre. df[n] gives you the nth column from the dataframe df. But df[n:n+2] gives you rows n to n+2. I find I often have to transpose my dataframe to make operations convenient, or use the “axis” parameter to functions like sum() to indicate whether I want to sum over columns or over rows.

The final fillip was using a Pandas Panel to store my data. A Panel is a collection of DataFrames; in my case one per tier. This 3 dimensional data structure is a bit confusing, the docs apologize for the names and it’s not clear that Panel adds a lot of value over a dict of DataFrame objects. But it’s Pandas’ way of representing a collection of spreadsheets, so I am going with it. My panels “items” are the tier names, the major_axis is champion rows (named by the index) and the minor_axis is the stats (the columns.)

Data analysis

So now I have my data loaded into a panel, time to analyze. The pattern I’ve settled on is generating a new DataFrame that’s a report table. For instance I’m interested in average statistics per tier. So I start with a 3d Panel of tiers x champions x stats, and I boil that down to a 2d DataFrame of tiers x average(stats). When I do ad-hoc Python report generation I usually just iteratively print out report lines, or maybe make an array of dicts for my data. Those are still fine too, but I wanted to go full Pandas.

I started out by writing lots of laborious loops over panel.iteritems() and the like. See cell 7 and how I first build up a dict named ‘spreads’ and then converted it to a DataFrame. Over time I’ve refined to simply doing operations like dividing a DataFrame by a Series and the like. Cell 8 shows that style, the creation of pick_rates is about the same computation as spreads before, but it’s less code. The whole process feels a lot like vectorizing code, like I did for my machine learning class in Octave/MatLab. The code gets shorter, which is nice, but it should also be more efficient which matters for large datasets.

Presentation

My final goal was to make nice-looking reports right in Jupyter. That proves to be quite difficult. Pandas is amazing at inlining graphs and visualizations with matplotlib and friends. But it’s not quite as good at textual reports. I mean Jupyter will display any HTML you make in python, but I haven’t found any good HTML generation convenience libraries out there for, say, DataFrames.

Fortunately the default DataFrame presentation HTML is pretty good. Labelled columns and rows, decent formatting of numbers. All that’s really missing is right alignment of numbers (and why is that not the default?!) But I want more control, for instance rounding floating point numbers to specific precision. For that I used the DataFrame.style object, which gives you a D3-esque ability to apply per-datum CSS styles to cells. I mostly used .format() to control text formatting of numbers and .set_table_styles() to add some CSS to the HTML table. The .applymap() function is the really powerful one that lets you control things per-datum.

I also threw in the background_gradient style, to give a sort of heatmap coloring to the number cells. That required installing a bunch of crap like python-tk and numpy just to get the colormaps. But it’s pretty painless in the end.

Conclusion

Pandas + Jupyter is a pretty good platform for ad hoc exploration of data, and with some learning and effort you can produce pretty clean code and reports. I love the way notebooks are reproducible and shareable. I think using SQL for this kind of work is probably more effective, but there’s a lot of overhead in getting set up with a database. And the interactive exploration isn’t as nice as a Jupyter notebook. (Hmmm, there’s no reason Jupyter cells couldn’t contain SQL code!)

My first iPython notebook

I finally sat down and learned some IPython for data exploration today. I re-examined some data I had for Battlefield 4 players, something I’d published as my BF4Plots visualization a year or two ago. It’s the stats on ~5000 top Battlefield 4 players, things like their win/loss ratio, skill score, etc.

You can see my notebook in this gist. That’s a static snapshot taken from my last run. If you run it yourself the results will change slightly as some of the algorithms I apply include randomization.

My main goal here was to get more comfortable using IPython. It’s awesome! I really love having the inline, easy to produce graphs. I mostly followed this tutorial for guidance.

Secondarily I was also trying to apply some cluster analysis to my BF4 data to see if I could learn any insights. Not really. This is my first foray into my own machine learning project applying stuff I’ve learned in my course. And it was interesting, I definitely felt I understood what the scikit algorithms were doing. Also a little lost how to get real meaning out of the data. No surprise, that’s the hard part!

The main IPython thing I’m still adjusting to is that it’s a notebook, not a program. I’m so used to iteratively working and re-running my program from scratch. But IPython encourages you to keep a persistent Python VM around and iteratively add to its state. I keep looking for the “Start over and run it all from scratch” button, and there sort of is one, but that’s not really how you’re supposed to work. Which got me into trouble a couple of times. Also I do wonder how IPython people transition their code to running programs for other people to reuse.

Update: a “restart and run all” button was just merged into the main codebase so that’s coming soon. And apparently I’m right that notebooks are more for exploration. When it comes time to create reusable code you create a normal module with some other code editing environment. You can certainly start by pasting your notebook-developed code over, though.

First Python library I learned was Pandas, the data management library. Really all I did was work a bit with DataFrame, which is a data container type that’s a 2d array on steroids. Columns are typed, everything’s nicely addressable and searchable, and it’s all efficient numeric spare arrays behind the scenes. I think it even supports multicore number crunching in a transparent fashion. Really nice library, a joy to use.

Second library I learned was matplotlib, some basic bashing at it to draw some graphs. It’s really great and I wish I’d invested the time to learn this before. But until I saw the HTML notebooks it wasn’t very compelling to me. It’s funny, Mathematica notebooks have been a thing for 20+ years but it’s only the last couple of years where Python caught up.

Final thing I learned was a bit of scikit-learn, in particular how to apply its PCA and K-Means algorithms. Went pretty smoothly. My only annoyance is it seems to only half-support Pandas. It will take DataFrames as inputs but then the objects it returns are basic numpy Arrays which lack column names and some of the nice slicing options. I can’t tell if I’m doing it wrong, it has to be this way, or if it’s just that Pandas is so new that scikit-learn hasn’t fully adopted it yet.

Anyway, all in all my experiment was a big success, very happy. Fun stuff!

IPython notebooks + geodata

IPython notebooks (ie: Jupyter) seem like an important innovation for me. A really nice web-native REPL for exploratory programming, including decent visualization of data. Plot data in particular, graphing with matplotlib. It’s quite capable, I think approaching what people do with R.

So I’ve been asking around about adding geodata capability to Jupyter. My first thought was a visualizer for GeoJSON, but I’ve learned now there are other approaches. I asked SeanG and he pointed me to a couple of things, which lead to some other things.

Summary: there are several geodata visualization packages that work with IPython. Some integrate with matplotlib and some are standalone geographic tools. None of them quite worked right for me after just a few minutes tinkering, but several seem worth the effort to get working.

folium is closest to what I’m looking for. It’s a Leaflet wrapper for Python with baked in support for geojson, various Stamen tilesets, etc. It seems to support inline plots in IPython notebooks but I couldn’t figure it out, there’s been some discussion that it should work. It doesn’t use matplotlib.

leafletwidget is another Leaflet-based map making tool, here’s an example notebook screenshot. It’s not packaged on PyPI and hasn’t been updated in awhile, looks like it’d take some effort to figure out how to use. But it might be a good basis for building my own thing.

mpleaflet lets you visualize matplotlib plots using Leaflet to add a geographical basemap. It looks very promising but I had some trouble using it out of the box. The key thing here is adding map capability to matplotlib, the primary charting visualization library IPython users use already. Seems good for data visualization but less map-specific.

matplotlib basemap toolkit is a more low-level tool for making maps with matplotlib. No Leaflet or otherwise fancy slippy map, it’s just helping you do map projections and draw geographic data in a single static image. Might be nice for one off visualizations!

cartopy is another non-leaflet map maker in python using matplotlib. It has support for using GoogleTiles. IPython support is not mentioned in the docs but it seems to work.

mpld3 has nothing to do with maps but is neat. It adds D3 rendering for matplotlib plots in your notebook, so you have fancy interactive javascript instead of a static image. Works great right out of the box. I want something that works like this for geodata. See also mplexporter, which seems to handle getting the data out of matplotlib.

GeoPandas is a bridge between Pandas and geographic data, including shapeley/fiona support. It uses descartes too, which is a bridge from geodata to matplotlib plots.

IPython and inline matplotlib

I’m trying out IPython. I’m also playing around with machine learning which means I need some simple data visualization, so I’m playing around with matplotlib. Here’s how to display generated plots inline (as opposed to in a popup window); the docs are inconsistent.

QT: ipython qtconsole --matplotlib inline

Notebook: launch with “ipython notebook”, then run “%matplotlib inline” in a notebook.

Here’s a sample program that generates and shows a plot:

from matplotlib import pyplot as plt
years = range(1950, 2020, 10)
gdp = [300, 543, 1075, 2862, 5979, 10289, 14958]
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
plt.show()