khuyentran1401 / machine-learning-articles

List of interesting articles on different topics of machine learning and deep learning
https://towardsdatascience.com/how-to-organize-your-data-science-articles-with-github-b5b9427dad37?source=friends_link&sk=4dfb338164ad6e95809d943f0dc0578e
164 stars 55 forks source link

Create Sklearn model #13

Open alfredoarturo opened 4 years ago

alfredoarturo commented 4 years ago

TL;DR

The basis to build a customized model in Scikit-learn, it is like writing a Python class

Article Link

https://towardsdatascience.com/building-a-custom-model-in-scikit-learn-b0da965a1299

Author

Tim Book

Key Takeaways

Useful Code Snippets

from self.preprocessing import OneHotEncoder
class KMeansTransformer(TransformerMixin):
    def __init__(self, *args, **args):
        self.model = KMeans(*args, **args)
    def fit(self, X):
        self.X = X
        self.model.fit(X)
    def transform(self, X):
        # Need to reshape into a column vector in order to use
        # the onehot encoder.
        cl = self.model.predict(X).reshape(-1, 1)

        self.oh = OneHotEncoder(
            categories="auto", 
            sparse=False,
            drop="first"
        )
        cl_matrix = self.oh.fit_transform(cl)      

        return np.hstack([self.X, cl_matrix])
    def fit_transform(self, X, y=None):
        self.fit(X)
        return self.transform(X)

Useful Tools

Comments/ Questions

khuyentran1401 commented 4 years ago

Really interesting to know that we can create a custom model with Scikit-learn