from hyperopt import fmin, tpe, hp, Trials
from sklearn.metrics import make_scorer
from sklearn.model_selection import cross_val_score
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold

# Assuming `model`, `X_train`, `y_train`, and `kf` are defined earlier in your code

# Define the search space for hyperopt
search_space = {
    'max_depth': hp.quniform('max_depth', 3, 6, 1),
    'min_samples_leaf': hp.uniform('min_samples_leaf', 0.04, 0.08),
    'max_features': hp.uniform('max_features', 0.2, 0.8)
}

# Define the objective function to minimize
def objective(params):
    model.set_params(**params)
    scores = cross_val_score(model, X_train, y_train, cv=kf, scoring=mae_scorer)
    # loss = 1 - scores
    return np.mean(scores) # loss

# Initialize Trials to store optimization results
trials = Trials()

# Use fmin from hyperopt to perform Bayesian optimization
best_hyperparams = fmin(
    fn=objective,
    space=search_space,
    algo=tpe.suggest,
    max_evals=50,  # Adjust the number of evaluations as needed
    trials=trials,
    verbose=1,
    rstate=np.random.RandomState(42)
)

# Get the best hyperparameters
best_bayes_hyperparams = {key: best_hyperparams[key] for key in search_space}

# Set the best hyperparameters to the model
model.set_params(**best_bayes_hyperparams)

# Fit the model with the best hyperparameters
model.fit(X_train, y_train)

# Save the best model
joblib.dump(model, 'my_best_bayes_model.pkl')

# Access the results from hyperopt
hyperopt_results = pd.DataFrame({
    'Accuracy': [-trial['result']['loss'] for trial in trials.results],
    'Parameter': [trial['misc']['vals'] for trial in trials.trials]
})

# Visualize contribution of parameter to get the optimal accuracy (Scatterplot or kdeplot)
plt.scatter(hyperopt_results['Parameter'], hyperopt_results['Accuracy'], s=100, alpha=0.5)
plt.show()

Python相关代码片段

sorting and extracting rows

django db backup

flask babel messages are not translated

import selenium WebDriverWait

pytorch neural network

text font customtkinter

tkinter grid

numpy vector magnitude

libvirt-python error

yolov8 real time object detection

milvus client python

ython isna() data frame

customtkinter gauge

python regex start of line

6.7 fl perfume

has attribute python

learning rate pytorch

arrays multidimensionales numpy

Checking if a list is empty in Python

Verify if a Python function returns a list

Syntax of the ternary operator in Python

How to check if an item exists in a Python list

Creating a list of dictionaries in Python

pytorch basics

creat key value jetstream python api

lambda python tkinter

add data into json python

create admin in Django

Convert a string to an int in Python

python named parameters command line

Return a list from a function in Python

keras decoder of the inference model

teacher forcing in keras

df.rename(columns= 'a' 'b' )

Python check whether object is picklable

tkinter custom icons

title of a webpage using selenium python

what does DataFrame.factorize do in pandas

tensorflow mse

encoder decoder architecture in keras

pathlib replace extension

pandas access datetime filed

python stopwatch decorator

There is more than one Python

tkinter combobox get value

beautifulsoup returns empty list

importerror: numba needs numpy 1.21 or less

how to install jdk in windows 10

combo box tkinte

run python script on raspberry pi command line

minus infinity in python

hallar angulo de referencia python

create filtered pivot tables in pandas

text in keras

how to mirror screen on tv with python

python read file to string

python import tuple

python sefine function type

meta llama 3 base huggingface

equal to or more than python

equal to or less than python

python pillow transparent background

CLEAR ALL MIGRATIONS DJANGO

decrement in python

hugging face to dataframe

Table Creation and Data Insertion in PySpark

Testing ETL Framework for Fixed-Length Files

Making Bulk SQL Queries from Notebooks

dictionary of tuple python

kml to csv with scraping

kml to csv without scraping

gan in keras

Qrcode Python

No module named 'GeminiAIChat'

How not to write Python codes

tensorflow basics

GET in python

deep learning in tensorflow

custom tensorflow model

pathlib python