I want to make a sklearn pipeline using the custom Artificial Neural Network I already have. I want to make pipeline in which input goes to ANN and its output goes to the sklearn.svm.SVC model and final prediction is made. So, how can I do this using sklearn pipeline?


1 Answer 1


Implementing a custom transformer is simple. You have to implement the fit and transform methods like below. Since your ANN is already trained (right?) the fit method has to do nothing, just return self. And the transform method has to pass the incoming data to the ANN and return its output.

from sklearn.base import BaseEstimator, TransformerMixin

class MyANNTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, ann):
        self.ann = ann

    def fit(self, X, y):
        return self

    def transform(self, X)
        return self.ann.predict(X)

Now you can include that in pipelines:

from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC

pipe = make_pipeline(MyANNTransformer(ann),

pipe.fit(Xtrain, ytrain)
  • $\begingroup$ What is going to change if my ANN is not already trained? $\endgroup$ Commented Mar 2, 2016 at 14:36
  • 2
    $\begingroup$ You'd have to add some code to the fit method that trains the ANN using X and y. $\endgroup$
    – stmax
    Commented Mar 2, 2016 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.