I can’t imagine anyone else is interested in this, but here’s my machine learning notes I took for myself during the course. Also attached here as a PDF: machine learning notes, because no web tools seem to deal with RTF well.
Remarkably prominent video compression artifacts in this video. Note the 8x8 rectangles at bottom, those are supposed to be mice being chopped to bits.
(From Scratchtasia, the Simpsons / Itchy & Scratchy parody of Fantasia. Specifically the Sorceror’s Apprentice sequence, which every software engineer should know and love.)
I’ve been doing somework with scikit-learn but running code on your own computers is for chumps, why not do our machine learning in the butt in the cloud? Here’s the offerings from a few, there are lots of others, too. This cross-service developer test is interesting data on prediction and running times.
Google Prediction API. $0.50 / 1000 predictions, $0.002/MB of training data. Focussed on training prediction models, both numeric (regression) and categorical. Didn’t see any documentation of what kind of algorithms they implement.
Amazon Machine Learning. $0.10 / 1000 predictions, $0.42 / hour for training. The FAQ says it does logistic regression, but the docs say it does both categorical and numeric predictions. They also have some data exploration tools and quality metrics.
Microsoft Azure Machine Learning. $0.50 / 1000 “API transactions”, $2 / hour. Also a per-seat charge which is completely “lol Microsoft”, I mean seriously? Offers classification but also other stuff: text analytics, vision, speech. The algorithm cheatsheet makes it look liek you have a lot of choices for basic prediction algorithms, too.
BigML: $0.10 / 1000 predictions, $0.01/MB of training data. Didn’t review what all algorithms it supports, clearly they do predictions. They’re a startup up in Portland and in Spain, with just $1.6M in funding in 4 years.
I’m not qualified to evaluate these yet. Google’s the oldest and simplest, also the most limited. Amazon’s product looks pretty simple and pretty. Microsoft’s has the most bells and whistles but you have to wade through Microsoft’s sales cluelessness. No idea on BigML but I like the idea of a startup making headway here.
JSON is stored as type text. No binary encoding, the docs say the improvement isn’t worth the trouble. JSON arrays are used as a container type in parts of the query language, for things that return N JSON blobs. There’s also some SQLite virtual tables that are created by advanced query methods.
There’s the basic functions you’d expect for manipulating JSON, mostly setting and changing properties on a JSON object.
For basic query, json_extract() is the basic function that pulls out pieces of a document based on a query path. (Ie: $.title means “give me the title property”, $.authors[2] means “give me the 3rd element of the array that is the value of the authors property”)
For advanced query, json_each() and json_tree() turn a single JSON blob into a virtual table you can then query. The table has a schema with one JSON column per property queried, as well as some other data related to the query like integer IDs and the path. json_each() only queries the top level properties, json_tree() is a recursive search.
I like it, it looks really promising. Maybe not quite ready for civilian use yet, but soon? The discussion a month ago advises we “check back soon”.
My one mild concern is that JSON data tends to be really big. Like I have 1000 LoL matches in a SQLite database, each one a 200kb JSON blob. And no surprise, it’s a 200MB file! That starts to get awkward for backups, etc, and is kinda dumb since the JSON is immutable. It’d be better to store them as read-only files but that’s not compatible with SQLite’s design.
JSONlite
JSONlite is the topic of the HN post that let me to JSON1. It’s a valiant effort, a set of bash scripts to store JSON as files and retrieve them with UUIDs. It’s not a bad little wrapper but it’s very simple. And no query interface, which to me is the interesting part, although one could probably just use jq on the backend store.
UnQLite
UnQLite also came up, in this description. “UnQLite is to MongoDB what SQLite is to Postgres”, which sounds good to me! It uses Jx9 for query. I didn’t look any further; it seems promising, but my general rule with tech like this is wait for critical mass before investing any time.
I started trying to apply SVM machine learning to my Battlefield 4 dataset and got something that only predicted my data with 60% accuracy. I’m expecting 95% or more but I don’t really know and I realized I was trying to learn too many new things at once.
So I went back to my Coursera homework, exercise 6, and used their data and problem sets as Python exercises. Specifically I trained SVM classifiers on two datasets. The result is in this notebook.
Cells 2–4 are me simply fitting a binary classifier to the toy input data. Cells 5–9 are fitting a binary classifier to different data, in this case performing repeated training steps to pick the right parameters C and sigma for the learning system. I did it the homework’s way in cells 6–7, using an explicitly split training and test dataset. Then I used sklearn’s cross_validation library to do the training in 8–9, which is a form of resampling to produce test sets on the fly. Results were roughly the same. I’m not 100% certain it is philosophically kosher to use CV in this manner, but I think it is.
Things I learned:
You can load matlab arrays with scipy.io.loadmat()
The ‘rbf’ kernel is what sklearn.svm calls the Gaussian kernel.
Instead of sigma, sklearn parameterizes rbf with gamma. gamma = 0.5/sigma**2
Decision boundaries are plotted by simply creating a raster grid of predictions, then making a contour plot to only show the boundary.
The big thing I learned is how sensitive these systems are to choices of sigma and C. Before I had the code working right I was using bad values and getting insane results. Relatively easy to see in a 2d dataset where you can plot the data and the decision boundary, but this must be much harder to understand and debug in large multidimensional datasets.
First off, it was a good use of my time. I complained about aspects of the course and I definitely think it can be improved. But it was a good introduction to what machine learning is and enough hands-on that I feel like I can no go do my own work with real tools. I also mostly liked the Coursera structure, having weekly deadlines and assignments was the structure I needed to actually learn something.
Techniques and Approaches
The thing I was most interested in learning is the general gestalt of machine learning, like how to sit down and get a problem solved. That was covered reasonably well through the course to varying degrees. Some themes:
The general structure of “take a training set of data. train a model on it. evaluate the mode against your test set. apply the model”. In some sense all the machine learning systems do the same thing: map a vector of input data to a scalar output value. The various algorithms are just different approaches to learning how to map input data to outputs. I didn’t understand they all fit into this category before.
The specific way that the training step is basically just running a function minimizer over your cost function (ie: measure of error). The subtlety here is most minimizers require some understanding of the gradient as well, which means you need to take partial derivatives of your cost function. (I wonder if numeric approximations to the derivative are useful in practice?)
The concept of high bias vs high variance models, ie: overfitting the data vs. underfitting the data. Basically if your choice of algorithm has a lot of internal knobs to twiddle, it’s likely you have high variance and might overfit the data, particularly if you don’t have a big data sample. Alternately if your chosen model is too simple the system might not ever predict the data well because it lacks the expressive power. I particularly liked the way you can detect which problem your system has with measuring the learning curve, how well your system learns based on how much data you give it.
A principled way to normalize data so that all your numbers are on comparable scales of roughly -1 to 1, with mean 0.
Regularized learning algorithms, with an extra term in the cost function to discourage overfitting.
Machine learning pipelines. The way you can segment a broad problem like photo OCR or automatic driving into smaller machine learning problems. Also ceiling analysis to figure out which part of your pipeline could be improved the most.
Stochastic machine learning. For very large datasets just iteratively learn on subsets of the data. Naturally leads to online learning, systems that continually learn in response to new data.
Algorithms
Most of the class was a tour through machine learning algorithms. Too much time implementing those algorithms for my tastes, but at least there’s no mystery to many of them now. Things we learned:
Supervised learning (ie: your training data is classified with expected outputs you are trying to predict.)
Linear regression: fit a linear model to the data. Predict a single number from a vector of numerical inputs.
Logistic regression: fit a logistic model to the data. Predict a single binary classifier from a vector of numerical inputs. (Really it outputs a probability!) Can predict N classes with one-vs-all classes.
Neural networks. Fit multi-stage regression to the data. Hidden layers can discover and calculate their own learned features. Good for non-linear models.
Support Vector Machines: logistic regression with a different error function that encourages your system to make sharp distinctions when classifying data. Also pluggable kernels, which allow you to change the function applied to features being considered to get beyond linear models. I got the impression SVMs with Gaussian kernels are the right choice in practice for many problems.
Unsupervised learning (no expected output on hand)
K-means clustering. Group your data into K natural clusters.
Principle component analysis. Boil high dimensional data down to fewer dimensions, while measuring and minimizing the loss of meaningful data.
Anomaly detection. Find data examples way outside the mean.
Collaborative filtering. Learn from user preferences what features of something result in those user preferences.
Practical skills
Practical application of subject matter was the weakest part of the course. The primary new technical skill I learned was Octave. But that feels like an increasingly obsolete tech and I wish I were using a language I’d be using more later. OTOH it was fun programming in a matrix math language with vectorization. I think if I were reimplementing this course today with the same curriculum, I’d consider using R and a notebook environment.
There were some real applied problems like number OCR and spam classification and movie recommendations. Those were interesting to me, but the exercises tended to have us solving one piece of a system to learn the data rather than putting the whole thing together.
I keep thinking it’d be fun to design an alternate machine learning course, one that focusses on the more practical application. Start with you downloading and pre-processing data. Then create a machine learning experimentation pipeline, plugging in out-of-the-box algorithms rather than implementing the algorithms yourself. Then go back and iteratively improve your application of ML, evaluating with learning curves and test data sets and honing the system so it really works.That’s a different course, but if I were doing that I’d do it in Python with scikit-learn and IPython notebooks.
What I missed
As noted above, the main thing I missed is more practical application. But that’s OK, because I think I learned enough to teach myself the practical stuff.
I also wish the course had a broad overview of more algorithms. There are literally thousands of machine learning algorithms in use out there, and while I trust we hit the most important basic concepts I’d have loved a single week which was just a whirlwind tour. Bayesian inference, decision trees, Markov models, ... so many options.
Next steps
Now on to applying what I’ve learned to my own data. I already did one little exercise in PCA and clustering with Battlefield 4 data, which was a good experience. I should really try applying SVMs to something next. Maybe League of Legends match data, but it’s hard to get a large sample with the default API rate limiting.
What I really want to do is try applying this stuff to map data. Some machine learning system to improve OpenStreetMap, maybe by identifying anomalies comparing the vector map users generate to raster aerial imagery.
These last two weeks of the course were so short I finished them all in one day.
I liked this last week, week 11. Most of the lectures were about a real world machine learning problem: finding and OCRing text in photographs.
Photo OCR
The key idea here is the pipeline.He broke the problem up into 4 separate machine learning problems that can be worked on independently.
Find regions of the image that look like text.
Segment text regions into individual characters.
OCR individual characters
Spell correct OCR errors
The real meat of the lesson was the sliding windows algorithm, the technique by which you identify text regions. Basically you look at small square regions of the image and train a recognizer to identify text/not-text. Then you merge adjacent regions of text into single blobs for handing off to step 2, the segmenter. The segmenter also uses a sliding windows analysis to find whitespace between characters, albeit a 1d window.
Lessons for machine learning
Second half of the lesson was reflections on doing better for machine learning.
First question: do you need more data? It may be expensive to get it. More data is most useful for low bias machine learning algorithms, so don’t bother if you have an overfit model. (Or rather, loosen your model first!). He also talked about artificial data synthesis, ways to generate more data from existing labelled training sets. For instance if you’re doing voice recognition, maybe you can generate more training examples by adding real-world distortion to existing examples. However don’t just add random noise, since that doesn’t really train anything useful.
Second question: what should I work on next? The key idea here is ceiling analysis. Basically you go down your pipeline replacing each step with a perfect system. Ie, replace step 1 with a perfect text region classifier; how much does your system improve? Now also replace step 2 with a perfect segementer: how much better does your system do? With that experiment in hand you can identify which steps in the pipeline have the most room for improvement, are worth your time to work on.
Once again I wish there were a programming exercise here to hammer these lessons home. Have us construct our own pipeline and do some testing / segmentation on it. I think this would be a good time to revisit the ideas of training vs. test sets, applying the test set well. Also evaluating systems for bias/variance problems. I suspect the Stanford undergrad class had students doing some final project which was just left out of the Coursera class, perhaps because it would be impossible to grade. Guess it’s up to me to apply this stuff to real problems and make my own mistakes without a teacher to tell me how I’m doing. Unsupervised learning, as it were.
And that’s the course! I’ve got one more blog post coming summarizing what all we covered and what I thought. Overall I’m quite positive, it was a good use of my time.
Major shift of tone in week 10 of my course. Less detailed algorithms and programming assigments, more of a “here’s some wisdom about real world use”. Well a bit of each, but no programming. Being this high level makes me feel a bit dislocated, I appreciate more now the harder assignments in previous weeks.
Stochastic Gradient Descent
Most of the lecture was on the problem of running machine learning algorithms on enormous data sets, say 100,000,000 examples. These algorithms tend to be of the form “calculate this cost function over all data. then average the cost and update theta, our model parameters”. That’s inefficient when your data is 100M examples! So instead we update theta based on only some of the example set.
Stochastic gradient descent has you doing gradient descent where you update theta once per data example. That means that instead of swiftly following the gradient down to the optimum your optimizer is now doing a bit of a drunken walk, but in the right direction towards the optimum. And with a huge amount of data you can get away with looking at all the data a little less often. Ie: a normal batch gradient descent may do 100 evaluations of all 100M data points. With stochastic you can get away with 1-10 evaluations of the 100M data points. I assume law of large numbers is why. One caveat: it’s important to iterate through your data in a random order, shuffle the data first.
“Mini batch” gradient descent is a middle ground where you calculate the cost over, say, 1000 samples before updating theta. Stochastic looks at 1 sample at a time, batch looks at all N, mini-batch looks at a subset of say 1000. The reason you do this middle ground is because you can still get some benefits of vectorization and/or parallelization.
Convergence is a bit woolly with these stochastic approaches. You still want to monitor convergence, but you really don’t want to calculate the cost function over the whole 100M data samples every time! So instead look at a sliding window of the last, say, 100 cost function calculations you did and monitor it to make sure it’s converging.
Online Learning
Closely related to stochastic machine learning is online learning, where your machine learning model is updating itself continuously in response to new user input. That’s how real websites work. The neat thing about this is your model will adapt to changes in the world over time. Ie: you may have trained a perfect spam classifier in 2013, but spam techniques changed. An online learning system will adapt to new techniques as new data comes in.
Parallelism and map reduce
Last lecture was a funny coda which was basically “oh yeah, you want to run machine learning in parallel on big data!” along with “there’s this thing called map reduce you should know about”. It’s obvious how many ML algorithms are embarrassingly parallel over the input data, so maybe it’s fine to go quickly over this. But a simple map reduce implementation of, say, linear regression would have been a great programming exercise. Perhaps not in Octave though, maybe that’s why they skipped it. I wonder if scikit-learn has support for map reduce? Quick search suggests not really, you roll your own on top of Hadoop.
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 (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.
A lot of people cheat while playing League of Legends. My impression is it’s not so bad that it ruins the game, but it sure is annoying.
Network invalidation
The simple and dumb cheats are denial of service attacks and drophacking. (See this discussion.) DoS attacks are directed against an enemy player in your game. Somehow you already know their IP address, and then you pay a couple of bucks to a bot farm to knock them offline. This happens a lot to high Elo players, particularly streamers. Poor Rivington (a Riot employee) basically couldn’t stream for a whole week because he’d be knocked offline every time he tried to play. Riot can’t stop DoS attacks directly, but they could definitely make it less appealing by having some sort of game invalidation if players are disconnected through most of the game. For some reason they’ve never wanted to implement that. DotA 2 has a good system.
Drophacking is a similar network denial attack, only in this case when you’re losing you crash the game server so it invalidates the whole game. This attack seems less common but not unknown and there’ve been a couple of severe instances at specific times, I assume once someone finds an exploit. Riot seems to be pretty quick about stopping drophacking, which is certainly expected given they control the server code.
Scripting
The other half of cheating is scripting, code running on the player’s computer to help them play better. I’ve seen a couple of what look like scripters to me in game. Specifically someone playing Sivir, where she’d cast her spell shield with inhuman swiftness to block my attempts to hook her as Thresh. I mean maybe she was just very good, but there was the time I cast the hook from inside a bush and she had at best 100ms to press E and yet there she is, pressing E. Or having a script press it for her.
Mostly this seems to be done via DLLs injected into the LoL process itself. The DLL allows Lua scripts to run, alter the UI, and perform player actions automatically. Two popular scripting tools are L# and Bot of Legends. Bot of Legends costs $10/month. Here’s a video of what it looks like to play with BoL.
There’s a huge variety of community-supplied scripts. See BoL Script Status for a gallery of scripts. Unfortunately most of the links go to paywalled forum posts. But scripts seem to be shared on GitHub. Here’s a couple of users I found: BoLFantastik, DraconisBoL.
Here’s an example code snippet that casts Ignite if it will guarantee a kill.
function AutoIgnite(enemy)
iDmg = ((IREADY and getDmg("IGNITE", enemy, myHero)) or 0)
if enemy.health <= iDmg and GetDistance(enemy) <= 600 and ignite ~= nil
then
if IREADY then CastSpell(ignite, enemy) end
end
end
Augmented intelligence
People who cheat at games baffle me, and make me angry when I play against them. But I do find the idea of augmented intelligence interesting, machine tools assisting people in doing things they intend. Like the Zed video I linked above has a short bit for “Jungle clear”, where you tell it “I want to kill this monster” and it combos your skills efficiently for max damage. The Insec video is another good example, scripting the ward / hop / kick combo that is a famously high skill play. Or not anymore, just press the button.
One challenge is UI for augmented intelligence, how do you present these higher level actions to the user? From the few videos I’ve seen there’s nothing impressive. That Insec video just shows a minimal line you draw, which way the enemy will go when you do it. Spare, but functional. Some of the other videos I’ve shown overload the player with information, drawing overlapping circles over everything. Maybe useful for debugging but not anything else.
The other question I have for scripting is how much it really helps the player. I have no doubt that spell-shielding Sivir was getting boosted by a tool that prevented me from hooking her. But there’s still a person in control of the character, it’s not a full bot, and she’s still having to make choices about where to go on the map and what to attack and when to go in or flee. I don’t think these scripts help with that. My gut feeling is the scripts probably cover about 40% of what a good player needs to do, the other 60% is up to them to do themselves. What’s funny is I’m in the bottom 25% of players. So if I see a scripter, they must be truly terrible if they have a 40% boost.
Week 9 of 11, and the last week with coding homework!
Anomaly Detection
The first unit of lectures was on anomaly detection: picking outliers out of a dataset. Very simple compared to previous algorithms we’ve studied. In the one feature case it boils down to “calculate the mean and standard deviation of the input set. Values way outside the mean are anomalies”. He does define it carefully in terms of Gaussian probability distributions, which is the solid way to do this at least.
So what about multi-featured data? Instead of doing proper multivariate Gaussians, the course focusses on handling vector input data by analyzing a single-variable Gaussian separately for each input feature, then calculating the product of all the probabilities to label the full vector. The result is a special case of the general multivariate Gaussian, in particular it’s a case that only really makes sense if you believe there’s no correlations between your input features. If you do it this limited way you’re stuck having to inspect the data to define new synthetic features, like “height times width” based on domain knowledge that the area of something is more relevant than the height or the width itself.
There are optional lectures on multivariate Gaussians but I’m left wondering why the course just doesn’t start there. Maybe to simplify the math (ha!) or maybe because the special case is more efficient to calculate. He notes the multivariate case doesn’t work well if you have more features that data samples. But if that’s the case, you probably shouldn’t be trying some fancy statistics on your meagre dataset anyway. (The irony is the homework code actually does use the multivariate Gaussian afterall.)
The artful step of applying anomaly detection is determining the threshold for what an anomaly is. Ie: if the datapoint has probability of 0.9 it’s clearly good. 0.1? Probably. But 0.01? Or 0.001? Or 0.0001? How improbable does it have to be before you decide it’s an anomaly? The course has us iteratively learning a good epsilon threshold for discrimination, using a classified test set. But we have the standard deviation of the good data available to us; surely it’d be better to talk about “5 standard deviations out” being a threshold? Or maybe that’s implicit in the Gaussian probability calculation?
The programming homework was awfully simple. The solution for the first part of the first question is literally “mu = mean(X);”. I have come to appreciate how nice Octave is about writing vectorized code for computing with vector and matrix data. So much nicer than writing loops!
Recommender systems
Second unit was on recommender systems, specifically collaborative filtering. This is serious throwback for me; when I started grad school in 1996 my group was all excited because some previous students had just gone off to found Firefly, a company to do collaborative filtering recommendations. They did sort of OK and finally sold to Microsoft 6 years later for a rumored $40M. IIRC the machine learning part wasn’t the real value of the company in the end, but rather some engineering details of how they built it.
Anyway, collaborative filtering is a neat algorithm because it lets a machine learning system really learn something. You give it a big batch of user ratings of, say, movies. The system divines hidden features for those movies that best predict why people have preferences for certain movies. (Ie: maybe it figures out there’s a grouping which is roughly “action movies”). Then you can use these learned features to go back and predict ratings you haven’t seen before.
I particularly like the way Ng presented the algorithm first as an iterative problem. “Use ratings to predict features. Then use those features to predict ratings. Then use those to improve your feature predictions, ...”. But in the end it all gets collapsed into a single optimization problem.
OTOH I still hate the math and notation presented in the lectures, it’s just impenetrable. I understand the gist of what it’s doing but what is this supposed to convey? My desire now is that the course not be taught with math notation but instead Octave code notation, so that all those ugly sums and stuff are replaced with simple vector math code samples.
One thing the lecture didn’t take is how you decide how many features to let the system learn. I believe this choice is arbitrary but probably essential to good performance. Someone else already asked in the course discussion. The mentor answered saying basically “try the smallest number that works well on test data”.
I was dreading the homework, since it’s yet again a “translate the confusing math to code” exercise. But having done this kind of thing a few times and with the mentor’s course notes as a guide, it’s pretty straightforward. Particularly to just do a vectorized implementation instead of the for loops the lecture definitions and exercises suggest. Seriously, I think this course got its approach wrong, it’s insane to try to do the calculations unvectorized in a language like Matlab. Both for clarity and performance. The lectures should teach to this approach.
The exercises build up to an actual movie recommender system (using MovieLens data). Neat! Only the homework is flubbed. With the originally supplied code we tell the recommender we liked Alien and Die Hard 2 and then it recommends Star Wars and Braveheart. Makes sense, right? Only the predicted rating I will give these films is 8.9 on a scale of 1–5. Oops. But at least the list of recommended movies is plausible.
Turns out the supplied code forgot to use some normalized values. So I fix that code as instructed and run it again, and now the highest predicted rating is 5. Good! Only now the list of recommended films are completely obscure movies like “Santa with Muscles” and “Aiqing wansui”. I’m left wondering if there’s still a bug in the code or this is a cruel lesson in the confusing vagaries of trained machine learning systems. I looked more closely and the recommendations I expect are there at the top, just not the very top. Still, it’s a disappointing end to the homework problem.
No more programming!
And a disappointing end to the course’s programming assignments. That’s the last one. There’s two more weeks of lectures and short quizzes, but no more coding. I’m sort of glad because hey! no homework! But also sad because I was hoping I’d learn more from the coding assignments.
I’ll say it one last time; I’d love a class that focussed more on application of machine learning systems. I really don’t need to implement the code for neural network back propagation or the fiddly details of collaborative learning. Or rather if I’m going to be doing that, I should be doing it on a graduate level with real math as the foundation. I’m fine with an introductory course being more shallow, but then I wish the programming exercises skipped the half-assed algorithm implementation and focussed on applications, on coaxing good results from these algorithms.
I realize I’m being cranky and truly I’m grateful that the course exists. I certainly appreciate that it’s free! Mostly my criticism is intended as “how could this be better?”.
This week’s lectures were our first foray into what is bizarrely called “unsupervised machine learning”. All our previous algorithms were given data features and correct classification as inputs. This time around all we get are data features, these are algorithms to try to classify / understand the data without guidance. It all seemed much simpler than previous weeks, particularly the assignments, I don’t know if I’m getting smarter or the material is just easier. I vaguely remember enough math from college that this all seemed pretty straightforward.
K-Means Clustering
K_Means clustering is a way to classify a bunch of inputs into a relatively small set of “K” clusters. It’s easy to illustrate visually:
The dots represent data input points, 2 dimensions of input data. Visually we can see these naturally fall into two clusters, helpfully colored here red and blue. Note the input data to this algorithm is not labelled, we don’t know what’s red and blue. The point of k-means clustering is to discover those red/blue labels. Once k-means has converged the model has two points, here marked in Xs. Those are the centroids of the two clusters. The way the algorithm works is you pick points at random to be your cluster centroids, then iteratively optimize that updating centroids so as to minimize the distance between every point in a cluster and its centroid.
Intuitively this is a pretty simple algorithm, and it is effective. Where people get tripped up is that our intuitions about “distance” and “near” from 2 or 3 dimensional spaces don’t really work for 1000+ dimensional data that’s often what we study. Ng didn’t go over that, just wisdom i’ve picked up from friends.
One thing I hadn’t known is that k-means is useful even when the data isn’t strictly clustered. For instance say you have height/weight of people, a continuous smear of points. Now say you want to sell t-shirts in three sizes: Small, Medium, Large. So cluster your data into three clusters and the centroids are the mean person you should make that size for. Kinda neat.
The art of applying k-means is knowing how to pick K, how many clusters. He presented the “elbow method” which basically lets you keep making K bigger until you don’t get a significant improvement in the error from its application.
Principle Component Analysis
PCA is an algorithm to project a high dimensional dataset down to a lower dimensional dataset. You can use this to project 10,000 dimensional input data down to, say, 1000 dimensions so that then your learning algorithms run faster because there’s less data. Or you can try to project data down to 2 or 3 dimensions for visualization.
The actual PCA algorithm basically boils down to “calculate eigenvectors”. Which Ng sort of said was the case, while not assuming the student knows what an eigenvector is. It was a pretty clear explanation really.
You still have to choose how many dimensions you want in your reduced dataset. His heuristic is “You want 99 percent of value retained”, which means “accept up to 1% error”. He says in practice you can often reduce data to 1/5 to 1/10 the number of dimensions and stay in this threshold.
Homework
Our actual homework this week was really simple, basically writing one-two lines of vector math code at a time to implement the pieces of k-means and PCA algorithms. Not much learning. There was a bunch of optional extra homework assignments applying to real world data. Using k-means clustering to reduce an image palette for instance (find the 16 most important colors). Or use PCA to reduce pixel data from pictures to the important components for facial recognition. That was neat stuff, I wish we’d done that for homework.
Once again I find myself wanting to do this stuff in Python. PCA would be nice to apply to that Battlefield 4 dataset I collected; it’s ~20 dimensional data, boil it down to the 4 or 5 eigenvectors that really define people’s performance. Then maybe cluster that to segment the population.
A question inspired by my work on OpenAddresses.. How many addresses are there in the world? By “address” I mean something that should be geocodable to a specific lat/lon, like 1600 Pennsylvania Ave NW, Washington, DC 20500. Normal people might define an address as something you can get mail delivered to, or tell a taxicab.
One address per two people. That’s the estimate Tom Lee came up with by comparing sizes of OpenAddress data we have to population. It’s not a bad estimate!
The confounding factor is that “address” is a somewhat first world concept, I imagine there’s fewer unambiguous addresses in rural / third world places. There’s a lot of the world where naming locations is much more loosely defined, “go to Tegaljaya village, go towards the mountain from the crossroads, turn left at the big banyan tree, and then five houses down”. OTOH I think every country in the world has mail delivery, which means there is some sort of system for finding people. Should do more research.
My second time trying to repair my iMac, my second failure.
I took my 2011 iMac in for extended warranty repair after a hardware crash related to the video card. I got the machine back a week later with a new video card. And a new logic board, which I didn’t ask for, but their testing indicated a problem and they replaced it for free. OK, thanks!
But they’d screwed up the repair. Specifically the WiFi didn’t work at all, which is unacceptable. Also a new problem, a weird chirping noise coming from the right side of the machine when high-contrast areas on screen were scrolled, like in Sublime Text black text on white background. I could live with that but it suggested maybe something wasn’t grounded or shielded right.
So I took it back for the WiFi problem. And got it back a week later, along with a sheepish admission that they plugged the antenna in to the logic board this time. OK, mistakes happen. Then I get the machine home and plug it in and surprise! There’s a big wodge of dust under the screen, about 7 x 4 pixels big. Nice job, Geniuses! The screen chirping noise is still there too.
Now I don’t know what to do. And Apple makes it difficult enough to get through to a human I’m not confident my problem will get fixed. Any reasonable fix will at the least involve me not having the machine for a few days and probably having to lug the machine in again to the Apple store, which takes about an hour each way.
The whole premise of Apple’s high prices is they get stuff right. Their repair folks in Stonestown sure didn’t succeed.
Update: took 20 minutes but talked to a repair manager at Stonestown. No explanation for how they’d screw up a repair twice, but at least polite acknowledgement that it isn’t right. Best they can offer me is I make an appointment to bring it in again and they’ll make it a priority repair, hopefully same day.