from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score # Define the Keras classifier model def create_model(): model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # Create scikit-learn compatible object keras_classifier = KerasClassifier(build_fn=create_model, epochs=5, batch_size=10) # Load some example data X, y = make_classification(n_samples=1000, n_features=8, n_informative=4, n_redundant=2, random_state=42) # Evaluate using cross-validation results = cross_val_score(keras_classifier, X, y, cv=5) print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
from keras.constraints import maxnorm from sklearn.model_selection import GridSearchCV from keras.wrappers.scikit_learn import KerasClassifier from sklearn.datasets import make_classification from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout # Define the Keras classifier model def create_model(neurons=1, activation='relu', dropout_rate=0.0, weight_constraint=0): model = Sequential() model.add(Dense(neurons, input_dim=8, kernel_initializer='uniform', activation=activation, kernel_constraint=maxnorm(weight_constraint))) model.add(Dropout(dropout_rate)) model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # Create scikit-learn compatible object keras_classifier = KerasClassifier(build_fn=create_model, verbose=0) # Load some example data X, y = make_classification(n_samples=1000, n_features=8, n_informative=4, n_redundant=2, random_state=42) # Define hyperparameters to tune param_grid = { 'neurons': [8, 16], 'batch_size': [16, 32], 'epochs': [10, 50], 'dropout_rate': [0.0, 0.1], 'weight_constraint': [2, 3] } # Perform grid search grid = GridSearchCV(estimator=keras_classifier, param_grid=param_grid, n_jobs=-1) grid_result = grid.fit(X, y) # Print the best results print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) for mean, stdev, param in zip(grid_result.cv_results_['mean_test_score'], grid_result.cv_results_['std_test_score'], grid_result.cv_results_['params']): print("%f (%f) with: %r" % (mean, stdev, param))The `keras.wrappers.scikit_learn` module is part of the Keras library.