Stop Coding Machine Learning Algorithms From Scratch

You Don’t Have To Implement Algorithms
if you’re a beginner and just getting started.

Stop.

Are you implementing a machine learning algorithm at the moment?

Why?

Implementing algorithms from scratch is one of the biggest mistakes I see beginners make.

In this post you will discover:

  • The algorithm implementation trap that beginners fall into.
  • The very real difficulty of engineering world-class implementations of machine learning algorithms.
  • Why you should be using off-the-shelf implementations.

Kick-start your project with my new book Master Machine Learning Algorithms, including step-by-step tutorials and the Excel Spreadsheet files for all examples.

Let’s get started.

Don't Implement Machine Learning Algorithms

Don’t Implement Machine Learning Algorithms
Photo by kirandulo, some rights reserved.

Caught In The Implementation Trap

Here’s a snippet of an email I received:

… I am really struggling. Why do I have to implement algorithms from scratch?

It seems that a lot of developers get caught in this challenge.

They are told or imply that:

Algorithms must be implemented
before being used.

Or that:

You can only learn machine learning by
implementing algorithms.

Here are some similar questions I stumbled across:

  • Why is there a need to manually implement machine learning algorithms when there are many advanced APIs like tensorflow available? (on Quora)
  • Is there any value implementing machine learning algorithms by yourself or should you use libraries? (on Quora)
  • Is it useful to implement machine learning algorithms? (on Quora)
  • Which programming language should I use to implement Machine Learning algorithms? (on Quora)
  • Why do you and other people sometimes implement machine learning algorithms from scratch? (on GitHub)

You’re Probably Doing it Wrong

You don’t have to implement machine learning algorithms from scratch.

This is a part of the bottom-up approach traditionally used to teach machine learning.

  1. Learn Math.
  2. Learn Theory.
  3. Implement Algorithm From Scratch.
  4. ??? (magic happens here).
  5. Apply Machine Learning.

It is a lot easier to apply machine learning algorithms to a problem and get a result than it is to implement them from scratch.

A Lot Easier!

Learning how to use an algorithm rather than implement an algorithm is not only easier, it is a more valuable skill. A skill that you can start using to make a real impact very quickly.

There’s a lot of low-hanging fruit that you can pick with applied machine learning.

Implementing Machine Learning Algorithms Well
…is Really Hard!

Algorithms that you use to solve business problems need to be fast and correct.

Fast Algorithms

The more sophisticated nonlinear methods require a lot more data than their linear counterparts.

This means they need to do a lot of work, which may take a long time.

Algorithms need to be fast to process through all of this data. Especially, at scale.

This may require a re-interpretation of the linear algebra that underlies the method in such a way that best suits a specific matrix operation in an underlying library.

It may require specialized knowledge of caching to make the most of your hardware.

These are not ad hoc tricks that come together after you get a “hello world” implementation working. These are engineering challenges that encompass the algorithm implementation project.

Correct Algorithms

Machine learning algorithms will give you a result, even when their implementation is crippled.

You get a number. An output. A prediction.

Sometimes the prediction is correct and sometimes it is not.

Machine learning algorithms use randomness. They are stochastic algorithms.

This is not just a matter of unit tests, it is a matter of having a deep understanding of the technique and devising cases to prove the implementation is as expected and edge cases are handled.

Use An Off-The-Shelf Implementation

You may be an excellent engineer.

But your “hello world” implementation of an algorithm will probably not cut-it when compared to an off-the-shelf implementation.

Your implementation will probably be based on a textbook description, meaning it will be naive and slow. And you may or may not have the expertise to devise tests to ensure the correctness of your implementation.

Off-the-shelf implementations in open source libraries are built for speed and/or robustness.

How could you not use a standard machine learning library?

They may be tailored to a very narrow problem type intended to be as fast as possible. They may also be intended for general purpose use, ensuring they operate correctly on a wide range of problems, beyond those you have considered.

Libraries Are Not All Created Equal

Not all algorithm implementations you download off the Internet are created equal.

The code snippet from GitHub maybe a grad students “hello world” implementation, or it may be the highly optimized implementation contributed to by the entire research team at a large organization.

You need to evaluate the source of the code you are using. Some sources are better or more reliable than others.

General purposes libraries are often more robust at the cost of some speed.

Lighting fast implementations by hacker-engineers often suffer poor documentation and are highly pedantic when it comes to their expectations.

Consider this when you pick your implementation.

Recommendations

When asked, I typically recommend one of three platforms:

  1. Weka. A graphical user interface that does not require any code. Perfect if you want to focus on the machine learning first and learning how to work through problems.
  2. Python. The ecosystem including pandas and scikit-learn. Excellent for stitching together a solution to a machine learning problem in development that is robust enough to also be deployed into operations.
  3. R. The more advanced platform that although has an esoteric language and sometimes buggy packages, offers access to state-of-the-art methods written directly by academics. Great for one-off projects and R&D.

These are just my recommendations, there are many more machine learning platforms to choose from.

Sometimes You Must Implement

You do not have to implement machine learning algorithms when getting started in machine learning.

But you can.

And there can be very good reasons for doing so.

For example here are 3 big reasons:

  • You want to implement to learn how the algorithm works.
  • There is no available implementation of the algorithm you need.
  • There is no suitable (fast enough, etc.) implementation of the algorithm you need.

The first is my favorite. It’s the one that may have confused you.

You can implement machine learning algorithms to learn how they work. I recommend it. It’s very efficient for developers to learn this way.

But.

You do not have to start by implementing machine learning algorithms. You will build your confidence and skill in machine learning a lot faster by learning how to use machine learning algorithms before implementing them.

The implementation and any research required to complete the implementation would then be an improvement on your understanding. An addition that would help you to get better results the next time you used that algorithm.

Summary

In this post, you discovered that beginners fall into the trap of implementing machine learning algorithms from scratch.

They are told that it’s the only way.

You discovered that engineering fast and robust implementations of machine learning algorithms is a tough challenge.

You learned that it is much easier and more desirable to learn how to use machine learning algorithms before implementing them. You also learned that implementing algorithms is a great way to learn more about how they work and get more from them, but only after you know how to use them.

Have you been caught in this trap?
Share your experiences in the comments.

Further Reading

Discover How Machine Learning Algorithms Work!

Mater Machine Learning Algorithms

See How Algorithms Work in Minutes

...with just arithmetic and simple examples

Discover how in my new Ebook:
Master Machine Learning Algorithms

It covers explanations and examples of 10 top algorithms, like:
Linear Regression, k-Nearest Neighbors, Support Vector Machines and much more...

Finally, Pull Back the Curtain on
Machine Learning Algorithms

Skip the Academics. Just Results.

See What's Inside

30 Responses to Stop Coding Machine Learning Algorithms From Scratch

  1. Avatar
    SalemAmeen October 5, 2016 at 1:23 pm #

    I think, this website and related books are the best in data science. I enjoy reading what you have write.

  2. Avatar
    Diego S October 7, 2016 at 1:43 am #

    I’m a professional developer and stock market trader a 12 years from Brazil and now I know that here I found what I was looking for. Amazing and easy articles to learn Machine Learning is here with Jason!

  3. Avatar
    MIke S October 8, 2016 at 10:49 am #

    Good article, thank you.

  4. Avatar
    Dennis October 9, 2016 at 2:23 pm #

    I think you are right that for implementation, unless you are a strong researcher its foolish to implement algos from scratch — but, for the purposes of understanding whats happening under the hood its pretty useful to code something up yourself. Otherwise its just all mystery meat

  5. Avatar
    Sean McClure October 18, 2016 at 8:46 am #

    Excellent post and definitely true. Writing machine learning algorithms from scratch is not a realistic approach to data science and will almost always lead to irrelevant attempts at building a data product that delivers. We must remember that the purpose of data science is to build products that leverage machine learning, and building products well means rapidly attempting many approaches and pivoting in the face of failed iterations. This is not possible if data scientists are caught in the weeds trying to reinvent the wheel on something that has already been built, tested and improved by the machine learning community.

    Our analyses must be held accountable to the standards deemed relevant in product development and there is little chance a home-grown algorithm can live up to that standard. Data scientists operate at a higher level of abstraction than academics that look to make slightly better models via fundamental improvements. Instead, we must learn the ‘art’ of swapping machine learning libraries in and out at a rapid pace, letting the data, and the end user of the product, lead us to the solution. I call it having great ‘package awareness.’ Being aware of which machine learning package/library does what, the knobs it allows us to turn, its strength and weaknesses and its ability to operate in production are what matters.

    There is always value in going deep and appreciating the mathematics of an approach or the elegance of an algorithm’s heuristic, but this depth of appreciation is better garnered through real-world attempts at trying to solve a problem. There is too much danger of attaching oneself to a set of algorithms we are already familiar with or whose underlying elegance we appreciate. The right algorithm is the one that solves the real problem; helping build a product that matters.

    • Avatar
      Jason Brownlee October 19, 2016 at 9:07 am #

      Really great comment Sean, thanks. I could not agree more.

  6. Avatar
    Florentin April 2, 2018 at 10:41 pm #

    Thank you so much for this article! What you wrote just enlightened me on many hidden questions I’ve been having for long time! Every time I have any problem I always stumble upon this website and I always walk away with so much epiphany. Thank you and keep writing!

  7. Avatar
    Yogesh May 26, 2018 at 4:19 am #

    Very helpful article! Found a big part of the information I was looking for!

  8. Avatar
    Benjamin Schulz March 25, 2019 at 7:28 am #

    I have personally made this mistake, with significant consequences:

    Long ago, when I was in college, the university I was attending offered a basic machine learning course. The idea of machine learning was hugely fascinating to me, so I enrolled.

    The first assignment was to build a simple MLP, and train it on a small contrived dataset. Almost all of the other students in the class were using libraries from Matlab or R. The rest had taken a prequel course where they wrote their own neural network libraries from scratch — which they were encouraged re-use here.

    I knew how to program, and felt like I grasped the elements of the theory pretty well. As such, I assumed that it would be no problem to write my own neural network, from scratch, in C, and also train it, and also have time to write up the required report on the relative impact of tuning various hyperparameters. If I couldn’t even implement the algorithim with just a little bit of work, I reasoned, it must mean that I had totally missed everything relevant in the class. Surely, it would be easy.

    What happened was that I spent two fraught and stressful weeks debugging and rewriting utilities that looked correct at a high level, but never quite worked. (I lost two days just chasing down a subtle error in pointer usage that caused my training set to inexplicably shrink every time I shuffled for the next epoch.) My model made predictions that were not even remotely accurate, I had no time left to write a report, and I got no points, even though I had worked on nothing else for two weeks solid. I ended up dropping the class, just so that I didn’t get an ‘F’ on my record.

    I suppose, in the big picture, one dropped college course is not so serious. I felt really disappointed, though, to abandon such an interesting topic, and I sometimes wonder how my career might have unfolded differently, had I begun to study machine learning much earlier. Certainly, I learned that arbitrarily doing things from the ground up — even with maximal effort — does not predict success, or set useful priorities. It’s reassuring to return to the issue all these years later, and have this lesson confirmed by someone else: the hard way is often not the right way, and all that extra effort has many better, more practical uses.

    Thanks, Jason, for all your work here,

    \0

    • Avatar
      Jason Brownlee March 25, 2019 at 2:15 pm #

      Wow, that is an important story to share, thank you very much!

      You are not alone and I expect events like this unfold all the time.

  9. Avatar
    Hassan Kamran May 4, 2019 at 11:34 pm #

    Thanks this really helps put things into perspective. This is the exact same response I got from a senior engineer and my approach to learning has changed drastically. The math isn’t too hard for me but actually writing a working implementation of an algorithm takes a really long time. I too tried it in C then I moved on to python using only Numpy and I sort of got a plain neural net working. From then on I study the concepts and implement it in Tensorflow. Engineering is built on abstraction, if I succumb to the trap of reinventing the wheel it’s only going to frustrate and discourage me. Maybe this sort of approach might be helpful in some arcane study of Algorithms in grad school but I doubt it. Best go the implemented route for industry or academia.

  10. Avatar
    Amanda Woods May 30, 2019 at 9:23 pm #

    Jason,
    This is a great article! I can see so many people entering comps in Kaggle and spending months writing MLAs to lose out to others spending one to two weeks using a commercial program to train on. Better to spend the time understanding the data. I have argued this point with my husband who believes in doing it the hard way.

    • Avatar
      Jason Brownlee May 31, 2019 at 7:47 am #

      I could not agree more!

      As a professional, the business/client wants the result (model or predictions), not the code/algorithm used to create there result.

      Also open source libraries have less bugs and are more efficient that almost every developer’s first (naive) implementation.

  11. Avatar
    Basu June 2, 2019 at 1:43 am #

    Hi Jason,
    Thanks for the article, and taking the time to go through the comments and responding back. I find more value in going to the comments then the article itself. Thanks for bringing so many people to discuss this great idea.
    Based on my professional experience I can say that it’s important to solve the problem doesn’t matter how you solve the problem and the easiest And quickest way to solve the problem is to take advantage of already built models.

    • Avatar
      Jason Brownlee June 2, 2019 at 6:41 am #

      Yes.

      We re-use code libraries all the time is software engineering, we must do the same in machine learning, not only for fitting new models, but for re-using existing pre-trained models.

  12. Avatar
    Mahsa January 6, 2021 at 12:17 am #

    so nice

  13. Avatar
    Imran March 28, 2021 at 7:41 pm #

    What an amazing article as i always used to wonder that why few people are writing everything from scratch if we have resources like scikit learn and tensorflow, we wont require to do tough computation on our own

  14. Avatar
    Amir April 9, 2021 at 4:23 am #

    Thanks for the outstanding article! , your articles are so valuable to me.

    From a business perspective, do you think employers care if you are able to implement an ml algorithm from scratch? and another question, if I am able to visualize how a ml algorithm works in my mind (and get the math behind it as well) and understand what each parameter does exactly, do u think, it’s still necessary to try to implement these ml algorithms from scratch to learn more or will it be a waste of time?

    Thanks.

    • Avatar
      Jason Brownlee April 9, 2021 at 5:28 am #

      You’re welcome.

      Probably. It depends on the role. Super technical role, I would expect dev can code things from scratch, for a smaller project or applied project, perhaps less so. E.g. if you need to get to the airport, you need a driver, not a mechanic.

      Yes. Theory vs practice is real.

  15. Avatar
    Suraj Joshi July 29, 2021 at 10:13 pm #

    Hey Jason, I was fallen in this trap and I am a beginner , A kind of mindset was there i need to code every algorithm from scratch ,But now I am not going to implement ,By far I implemented Linear ,Logistic and decision tree classifier. My question is that do I need to know each and every math as a beginner like I am currently learning deep learning and I am feeling like backpropagation is very tough and is very high level ,What are your thoughts ?? Should I need to know or not

    • Avatar
      Jason Brownlee July 30, 2021 at 6:28 am #

      No. Just dive and start using the tools of ML to solve real problems.

Leave a Reply