I have this optimization code using optuna in Python for neural networks of…
- User
I have this optimization code using optuna in Python for neural networks of hyperparamers: def nn_validate(model, X, y,epochs,batch_size,validation_split=0.2,verbose=0): is_classification = nn_is_classifier(model)
if is_classification: scoring = "accuracy" else: 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) loss, mae = model.evaluate(X_test, y_test) loss, mae_train = model.evaluate(X_train, y_train) train_scores.append(mae_train) test_scores.append(mae) 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):
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')) model.add(layers.Dense(1)) model.compile(optimizer=keras.optimizers.Adam(trial.suggest_float('learning_rate', 1e-5, 1e-2,log=True)), loss='mse', metrics=['mae']) epochs=trial.suggest_int('epochs', 50, 200) batch_size=trial.suggest_int('batch_size', 16, 128) history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2,verbose=0) #loss, mae = model.evaluate(X_test, y_test) score, is_overfitted = nn_validate(model, X, y,epochs, batch_size) if is_overfitted: return 0 else: return scoreDefine the Optuna study
study = optuna.create_study(direction='minimize')
Optimize the hyperparameters
study.optimize(objective, n_trials=100)
Is it working for classification of y from 0:2 and y as regression? If not how to adjust it?
- Assistant
- User
Could you replace mean absolute error with some sort of determination score from 0:1?
- Assistant
Certainly! In that case, for classification problems, you can continue using accuracy as a metric, which is already in the range of 0 to 1. For regression problems, you can use the coefficient of determination or R-squared (R^2) score. Here's how to modify your
nn_validatefunction to use R^2 as a metric for regression:- Import the
r2_scorefunction from the sklearn library. - Use the
predictfunction instead ofevaluateto get the predicted values for both the train and test sets.
- Import the