jak działa metoda KerasClassifier
- User
jak działa metoda KerasClassifier
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
jak działa metoda KerasClassifier
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
KerasClassifier to wrapper (opakowanie) z biblioteki Scikeras (dawniej część Keras), który pozwala używać modeli Keras/TensorFlow w ekosystemie scikit-learn. Oto szczegółowe wyjaśnienie:
KerasClassifier umożliwia:
GridSearchCV, cross_val_scorefrom scikeras.wrappers import KerasClassifier
# Funkcja tworząca model
def create_model(optimizer='adam', neurons=32):
model = Sequential()
model.add(Dense(neurons, input_dim=8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
return model
# Tworzenie wrappera
model = KerasClassifier(
model=create_model,
epochs=100,
batch_size=10,
verbose=0
)
from sklearn.model_selection import GridSearchCV
# Definiowanie siatki parametrów
param_grid = {
'epochs': [50, 100],
'batch_size': [10, 20],
'optimizer': ['adam', 'rmsprop'],
'neurons': [16, 32, 64]
}
# Grid search
grid = GridSearchCV(
estimator=model,
param_grid=param_grid,
cv=3,
scoring='accuracy'
)
# Trenowanie
grid_result = grid.fit(X_train, y_train)
# Najlepsze parametry
print(f"Najlepsze: {grid_result.best_score_} używając {grid_result.best_params_}")
from sklearn.model_selection import cross_val_score
# Walidacja krzyżowa
scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')
print(f"Dokładność: {scores.mean():.2f} (+/- {scores.std() * 2:.2f})")
Automatyczne dopasowanie parametrów:
set_params()Obsługa danych:
Kompilacja modelu:
from scikeras.wrappers import KerasClassifier
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
def create_model(learning_rate=0.01, dropout_rate=0.2):
model = Sequential([
Dense(128, activation='relu', input_shape=(10,)),
Dropout(dropout_rate),
Dense(64, activation='relu'),
Dropout(dropout_rate),
Dense(3, activation='softmax') # 3 klasy
])
optimizer = Adam(learning_rate=learning_rate)
model.compile(
optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
return model
# Pipeline z preprocessingiem
pipeline = Pipeline([
('scaler', StandardScaler()),
('classifier', KerasClassifier(
model=create_model,
epochs=50,
batch_size=32,
learning_rate=0.001,
dropout_rate=0.3
))
])
# Trenowanie
pipeline.fit(X_train, y_train)
# Predykcja
predictions = pipeline.predict(X_test)
pip install scikeras
KerasClassifier to potężne narzędzie łączące elastyczność Keras z ekosystemem scikit-learn, szczególnie przydatne przy optymalizacji hiperparametrów i walidacji modeli.