Collecting bayesian-optimization
Downloading bayesian-optimization-1.2.0.tar.gz (14 kB)
Requirement already satisfied: matplotlib in /opt/conda/lib/python3.8/site-packages (3.2.2)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.8/site-packages (4.48.0)
Requirement already satisfied: numpy>=1.9.0 in /opt/conda/lib/python3.8/site-packages (from bayesian-optimization) (1.19.1)
Requirement already satisfied: scipy>=0.14.0 in /opt/conda/lib/python3.8/site-packages (from bayesian-optimization) (1.4.1)
Requirement already satisfied: scikit-learn>=0.18.0 in /opt/conda/lib/python3.8/site-packages (from bayesian-optimization) (0.23.1)
Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib) (2.8.1)
Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.8/site-packages (from matplotlib) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib) (2.4.7)
Display all output >>>
グラフ作る
まずグラフを参考ページの通りに作ります。
Copy
import math
import numpy as np
from matplotlib import pyplot as plt
def f(x):
return math.exp(-(x - 2) ** 2) + math.exp(-(x - 6) ** 2 / 10) + 1 / (x ** 2 + 1)
X = [x for x in np.arange(-5, 15, 0.1)]
y = [f(x) for x in X]
plt.plot(X, y)
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.show()
<Figure size 432x288 with 1 Axes>
最適化する
Copy
import math
from bayes_opt import BayesianOptimization
#関数と値範囲を指定
bo = BayesianOptimization(f=f, pbounds={'x': (-5, 15),})
bo.maximize(init_points=3, n_iter=10)
import math
import numpy as np
from bayes_opt import BayesianOptimization
from matplotlib import pyplot as plt
#関数
def f(x):
return math.exp(-(x - 2) ** 2) + math.exp(-(x - 6) ** 2 / 10) + 1 / (x ** 2 + 1)
#関数と値範囲を指定
bo = BayesianOptimization(f=f, pbounds={'x': (-5, 15),})
bo.maximize(init_points=3, n_iter=10)
#プロット
X = [x for x in np.arange(-5, 15, 0.1)]
#元の関数
y = [f(x) for x in X]
plt.plot(X, y, label='true')
xs = [p['params']['x'] for p in bo.res]
ys = [f(p['params']['x']) for p in bo.res]
plt.scatter(xs, ys, c='green', s=20, zorder=10, label='sample')
mean, sigma = bo._gp.predict(np.array(X).reshape(-1, 1), return_std=True)
plt.plot(X, mean, label='pred')
plt.fill_between(X, mean + sigma, mean - sigma, alpha=0.1)
plt.legend()
plt.grid()
plt.show()