6
$\begingroup$

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?

$\endgroup$
8
$\begingroup$

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),
                     SVC())

pipe.fit(Xtrain, ytrain)
pipe.predict(Xtest)
$\endgroup$
  • $\begingroup$ What is going to change if my ANN is not already trained? $\endgroup$ – Bhagyesh Vikani Mar 2 '16 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 Mar 2 '16 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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