wwl wwl - 1 month ago 20
Python Question

Machine learning models: should I define a class or function

I'm using Python to write my own machine learning models for practice. There are two ways I can go about it:


  1. Write a function e.g.
    def logisticRegression(...):

  2. Write a class e.g.
    class logisticRegression:



Obviously, both will work. But which is more Pythonic?

Answer

For me it makes more sense to go with a class approach as you can save your model as instance of the class and have as class functions something like a train() to initialize the model and a predict() method to use your model multiple times without having to retrain it.

Look at the scikit-learn class for Logistic Regression, it makes a lot of sense and is very intuitive.