from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV import numpy as np def create_model(neurons=1): model = Sequential() model.add(Dense(neurons, input_dim=10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model model = KerasClassifier(build_fn=create_model, epochs=10, batch_size=32, verbose=0) param_grid = {'neurons': [1, 5, 10, 20]} grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3) grid.fit(X_train, y_train)
from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.base import BaseEstimator, ClassifierMixin import numpy as np class MyKerasClassifier(KerasClassifier, BaseEstimator, ClassifierMixin): def __init__(self, **kwargs): super().__init__(**kwargs) def fit(self, X, y, **kwargs): self.classes_ = np.unique(y) return super().fit(X, y, **kwargs) def predict(self, X): return super().predict(X) def create_model(): model = Sequential() model.add(Dense(10, input_dim=4, activation='relu')) model.add(Dense(3, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model model = MyKerasClassifier(build_fn=create_model, epochs=10, batch_size=32, verbose=0) model.fit(X_train, y_train) y_pred = model.predict(X_test)In this example, we create a custom classifier by inheriting from KerasClassifier and implementing the fit and predict methods. We then use this classifier to train and predict on the Iris dataset.