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
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)
-
$\begingroup$ What is going to change if my ANN is not already trained? $\endgroup$ 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$– stmaxMar 2, 2016 at 15:15