update_w based on https://gist.github.com/ddemidov/10957406