In this code: import numpy as np import optuna from sklearn.modelselection import…
- User
In this code: import numpy as np import optuna from sklearn.model_selection import train_test_split from tensorflow import keras from tensorflow.keras import layers from statistics import mean
Determine if it’s classification or regression problem based on unique values in y.
def is_classification(y, threshold=10): num_classes = len(np.unique(y)) return num_classes <= threshold
def nn_validate(model, target_type, X, y, epochs, batch_size): train_scores, test_scores = [], []
for i in range(3): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.7, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2, random_state=42) model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=0) if target_type == "classification": _, acc_train = model.evaluate(X_train, y_train, verbose=0) _, acc_test = model.evaluate(X_test, y_test, verbose=0) train_scores.append(acc_train) test_scores.append(acc_test) else: _, mae_train = model.evaluate(X_train, y_train, verbose=0) _, mae_test = model.evaluate(X_test, y_test, verbose=0) train_scores.append(mae_train) test_scores.append(mae_test) train_score = mean(train_scores) test_score = mean(test_scores) is_overfitted = train_score - test_score > 0.1 return test_score, is_overfitteddef objective(trial): target_type = "classification" if is_classification(y_train) else "regression"
model = keras.Sequential() model.add(layers.Dense(units=trial.suggest_int('units1', 32, 128), activation='relu', input_shape=(X_train.shape[1],))) model.add(layers.Dense(units=trial.suggest_int('units2', 32, 128), activation='relu')) if target_type == "classification": num_classes = len(np.unique(y_train)) model.add(layers.Dense(num_classes, activation='softmax')) loss = 'sparse_categorical_crossentropy' metric = 'accuracy' else: model.add(layers.Dense(1)) loss = 'mse' metric = 'mae' model.compile(optimizer=keras.optimizers.Adam(trial.suggest_float('learning_rate', 1e-5, 1e-2, log=True)), loss=loss, metrics=[metric]) epochs = trial.suggest_int('epochs', 50, 200) batch_size = trial.suggest_int('batch_size', 16, 128) score, is_overfitted = nn_validate(model, target_type, X, y, epochs, batch_size) if is_overfitted: return 0 else: return scoreDefine the Optuna study
study = optuna.create_study(direction='maximize' if is_classification(y_train) else 'minimize')
Optimize the hyperparameters
study.optimize(objective, n_trials=100) Should there be log=True for classification? If not can you fix it?
- Assistant
The log=True is related to the learning rate for the Adam optimizer, which is an important hyperparameter in the training process. This is not specific to the classification or regression problem. The log=True sets a logarithmic scale for the learning rate that helps it sample reasonably spaced learning rates for both classification and regression problems. So, there's no need to remove or change the log=True for the classification problem in this code.