from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # Load the iris dataset iris = load_iris() X = iris.data y = iris.target # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Define a simple Keras model def create_model(): model = Sequential() model.add(Dense(8, input_dim=4, activation='relu')) model.add(Dense(3, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # Wrap the Keras model with the scikit-learn API clf = KerasClassifier(build_fn=create_model, epochs=20, batch_size=10) # Train the model clf.fit(X_train, y_train) # Predict class probabilities using the `predict_proba` method probabilities = clf.predict_proba(X_test) print(probabilities)
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 train_test_split # Generate a toy classification dataset X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_classes=2, random_state=42) # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Define a simple Keras model def create_model(): model = Sequential() model.add(Dense(16, input_dim=10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # Wrap the Keras model with the scikit-learn API clf = KerasClassifier(build_fn=create_model, epochs=10, batch_size=32) # Train the model clf.fit(X_train, y_train) # Predict class probabilities using the `predict_proba` method probabilities = clf.predict_proba(X_test) print(probabilities)These examples demonstrate how to use the `keras.wrappers.scikit_learn.KerasClassifier` with the `predict_proba` method to predict class probabilities using a Keras model. The package libraries used in these examples are Keras and scikit-learn.