1 Introduction

Optimization is important in many fields, including in data science. In manufacturing, where every decision is critical to the process and the profit of organization, optimization is often employed, from the number of each products produced, how the unit is scheduled for production, get the best or optimal process parameter, and also the routing determination such as the traveling salesman problem. In data science, we are familiar with model tuning, where we tune our model in order to improve the model performance. Optimization algorithm can help us to get a better model performance.

Bayesian Optimization is one of many optimization algorithm that can be employed to various cases. Bayesian Optimization employ a probabilistic model to optimize the fitness function. The advantage of Bayesian Optimization is when evaluations of the fitness function are expensive to perform — as is the case when it requires training a machine learning algorithm — it is easy to justify some extra computation to make better decisions1. It is best-suited for optimization over continuous domains of less than 20 dimensions, and tolerates stochastic noise in function evaluations2.

This post is dedicated to learn how Bayesian Optimization works and their application in various business and data science case. The algorithm will be run in R.

1.1 About

1.2 Learning Objectives

  • Learn how Bayesian Optimization works
  • Learn how to apply Bayesian Optimization in business and data science problem
  • Compare Bayesian Optimization with Particle Swarm Optimization

2 Bayesian Optimization: Concept

The general procedure when works with Bayesian Optimization is as follows:

Bayesian Optimization consists of two main components: a Bayesian statistical model for modeling the objective function, and an acquisition function for deciding where to sample next. The Gaussian process is often employed for the statistical model due to its flexibility and tractability.

2.1 Gaussian Process

The model used for approximating the objective function is called surrogate model. Gaussian process is one of them. Whenever we have an unknown value in Bayesian statistics, we suppose that it was drawn at random by nature from some prior probability distribution. Gaussian Process takes this prior distribution to be multivariate normal, with a specific mean vector and covariance matrix.

The prior distribution on \([f(x_1), f(x_2), ..., f(x_k)]\) is:

\[f(x_{1:k}) \sim \mathcal{N} (\mu_0(x_{1:k}),\ \Sigma_0(x_{1:k}, x_{1:k})) \]

\(\mathcal{N}(x,y)\) : Gaussian/Normal random distribution

\(\mu_0(x_{i:k})\) : Mean function of each \(x_i\). It is common to use \(m(x)=0\) as Gaussian Process is flexible enough to model the mean arbitrarily well3

\(\Sigma_0(x_{i:k},x_{i:k})\) : Kernel function/covariance function at each pair of \(x_i\)

Gaussian process also provides a Bayesian posterior probability distribution that describes potential values for \(f(x)\) at the candidate point \(x\). Each time we observe f at a new point, this posterior distribution is updated. The Gaussian process prior distribution can be converted into posterior distirbution after having some observed some \(f\) or \(y\) values.

\[f(x)|f(x_{1:n}) \sim \mathcal{N} (\mu_n(x), \ \sigma_n^2(x))\]

Where:

\[\mu_n(x) = \Sigma_0(x,x_{i:n}) * \Sigma_0(x_{i:n},x_{i:n})^{-1} * (f(x_{1:n})-\mu_0(x_{1:n})) + \mu_0(x)\]

\[\sigma_n^2(x) = \Sigma_0(x,x) - \Sigma_0(x,x_{i:n}) * \Sigma_0(x_{i:n},x_{i:n})^{-1} * \Sigma_0(x_{i:n},x)\]

Below is the example of Gaussian Process posterior over function graph. The blue dot represent the fitness function of 3 sample points. The solid red line represent the estimate of the fitness function while the dashed line represent the Bayesian credible intervals (similar to confidence intervals).

Let’s illustrate the process with GPfit package. Suppose I have a function below:

Create noise-free \(f\) for \(n_0\) based on 5 points within range of [0,1].

##              x         y
## [1,] 0.0000000  75.68025
## [2,] 0.3333333  32.59273
## [3,] 0.5000000 -43.46241
## [4,] 0.6666667 -74.99929
## [5,] 1.0000000  17.33797

Create a gaussian process with GP_fit() with power exponential correlation function. You can also use Matern correlation function list(type = "matern", nu = 5/2)4.

After we fitted GP model, we can calculate the expected value \(μ(x)\) at each possible value of x and the corresponding uncertainty \(σ(x)\). These will be used when computing the acquisition functions over the possible values of x.

We can visualize the result.

2.2 Acquisition Function

Acquisition function is employed to choose which point of \(x\) that we will take the sample next. The chosen point is those with the optimum value of acquisition function. The acquisition function calculate the value that would be generated by evaluation of the fitness function at a new point \(x\), based on the current posterior distribution over \(f\).

Below is the illustration of the acquisition function value curve. The value is calculated using expected improvement method. Point with the highest value of the acquisition function will be sampled at the next round/iteration.

There are several choice of acquisition function, such as expected improvement, Gaussian Process upper confidence bound, entropy search, etc. Here we will illustrate the expected improvement function.

\[EI(x) = \left\{ \begin{array}{ll} (\mu(x) - f(x^+) - \xi) \Phi(Z) + \sigma(x) \phi(Z) & if \ \sigma(x) > 0 \\ 0 & if \ \sigma(x) = 0 \\ \end{array} \right. \]

Where

\[Z = \frac{\mu(x) - f(x^+) - \xi}{\sigma(x)}\]

\(f(x^+)\) : Best value of \(f(x)\) of the sample

\(\mu(x)\) : Mean of the GP posterior predictive at \(x\)

\(\sigma(x)\) : Standard deviation of the GP posterior predictive at \(x\)

\(\xi\) : xi(some call epsilon instead). Determines the amount of exploration during optimization and higher ξ values lead to more exploration. A common default value for ξ is 0.01.

\(\Phi\) : The cumulative density function (CDF) of the standard normal distribution

\(\phi\) : The probability density function (PDF) of the standard normal distribution

Suppose that y_best is the best fitness value from the sample

We can use the code below to get the expected improvement value for each x. We will use epsilon value of 0.01.

Let’s visualize the result. Create data.frame for the result and create exp_best which consists of x with the highest expected improvement value.

We can visualize the result

With this basic steps, I hope we are ready to apply Bayesian Optimization.

3 Bayesian Optimization in R

We can do Bayesian optimization in R using rBayesianOptimization package.

3.1 Portofolio Optimization

The problem is replicated from Zhu et al.(2011)5. The study employed a PSO algorithm for portfolio selection and optimization in investment management.

Portfolio optimization problem is concerned with managing the portfolio of assets that minimizes the risk objectives subjected to the constraint for guaranteeing a given level of returns. One of the fundamental principles of financial investment is diversification where investors diversify their investments into different types of assets. Portfolio diversification minimizes investors exposure to risks, and maximizes returns on portfolios.

The fitness function is the adjusted Sharpe Ratio for restricted portofolio, which combines the information from mean and variance of an asset and functioned as a risk-adjusted measure of mean return, which is often used to evaluate the performance of a portfolio.

The Sharpe ratio can help to explain whether a portfolio’s excess returns are due to smart investment decisions or a result of too much risk. Although one portfolio or fund can enjoy higher returns than its peers, it is only a good investment if those higher returns do not come with an excess of additional risk.

The greater a portfolio’s Sharpe ratio, the better its risk-adjusted performance. If the analysis results in a negative Sharpe ratio, it either means the risk-free rate is greater than the portfolio’s return, or the portfolio’s return is expected to be negative.

The fitness function is shown below:

\[Max \ f(x) = \frac{\sum_{i=1}^{N} W_i*r_i - R_f}{\sum_{i=1}^{N}\sum_{j=1}^{N} W_i * W_j * \sigma_{ij}}\]

Subject To

\[\sum_{i=1}^{N} W_i = 1\] \[0 \leq W_i \leq 1\] \[i = 1, 2, ..., N\]

\(N\): Number of different assets

\(W_i\): Weight of each stock in the portfolio

\(r_i\): Return of stock i

\(R_f\): The test available rate of return of a risk-free security (i.e. the interest rate on a three-month U.S. Treasury bill)

\(\sigma_{ij}\): Covariance between returns of assets i and j,

Adjusting the portfolio weights \(w_i\), we can maximize the portfolio Sharpe Ratio in effect balancing the trade-off between maximizing the expected return and at the same time minimizing the risk.

3.1.1 Import Data

Data is acquired from New York Stock Exchange on Kaggle (https://www.kaggle.com/dgawlik/nyse). We will only use data from January to March of 2015 for illustration.

  • date: date
  • symbol: symbol of company stock
  • open: price at the open of the day
  • close: price at the end of the day
  • low: lowest price of the day
  • high: highest price of the day
  • volume: number of transaction at the day

To get clearer name of company, let’s import the Ticker Symbol and Security.

Let’s say I have assets in 3 different stocks. I will randomly choose the stocks.

3.1.2 Calculate Returns

Let’s calculate the daily returns.

Let’s calculate the mean return of each stock.

The value of \(R_f\) is acquired from the latest interest rate on a three-month U.S. Treasury bill. Since the data is from 2016, we will use data from 2015 (Use data from March 27, 2015), which is 0.04%. The rate is acquired from https://ycharts.com/indicators/3_month_t_bill.

3.1.3 Covariance Matrix Between Portofolio

Calculate the covariance matrix between portofolio. First, we need to separate the return of each portofolio into several column by spreading them.

Create the covariance matrix.

3.1.5 Define Parameters

Let’s define the search boundary

Let’s set the initial sample

3.1.6 Run the Algorithm

Use BayesianOptimization() function to employ the algorithm. The parameters include:

  • FUN : the fitness function
  • bounds : a list of lower and upper bound of each dimension/variables
  • init_grid_dt : User specified points to sample the target function
  • init_points : Number of randomly chosen points to sample the target function before Bayesian Optimization fitting the Gaussian Process
  • n_iter : number of repeated Bayesian Optimization
  • acq : Choice of acquisition function
  • kappa : tunable parameter kappa of GP Upper Confidence Bound, to balance exploitation against exploration, increasing kappa will make the optimized hyperparameters pursuing exploration.
  • eps : tunable parameter epsilon of Expected Improvement and Probability of Improvement, to balance exploitation against exploration, increasing epsilon will make the optimized hyperparameters are more spread out across the whole range.

Result of the function consists of a list with 4 components:

  • Best_Par : a named vector of the best hyperparameter set found
  • Best_Value : the value of metrics achieved by the best hyperparameter set
  • History : table of bayesian optimization history
  • Pred : table with validation/cross-validation prediction for each round of bayesian optimization history

So, what is the optimum Sharpe Ratio from Bayesian optimization?

## [1] 16.23812

The greater a portfolio’s Sharpe ratio, the better its risk-adjusted performance. If the analysis results in a negative Sharpe ratio, it either means the risk-free rate is greater than the portfolio’s return, or the portfolio’s return is expected to be negative.

Let’s check the total weight of the optimum result.

## [1] 1

Based on Bayesian Optimization, here is how your asset should be distributed.

3.1.7 Change the Acquisition Function

Let’s try another Bayesian Optimization for the problem. We will change the acquisition function from expected improvement to Gaussian Process upper confidence limit.

The result has Sharpe Ratio of 16.2381179 with the following weight.

3.1.8 Compare With Particle Swarm Optimization

Let’s compare the optimum Sharpe Ratio from Bayesian Optimization with another algorithm: Particle Swarm Optimization. If you are unfamiliar with the method, you can visit my post6.

Let’s redefine the fitness function to suit the PSO from pso package.

Let’s run the PSO Algorithm. PSO will run for 10,000 iterations with swarm size of 100. If in 500 iterations there is no improvement on the fitness value, the algorithm will stop.

## $par
## [1] 0.18286098 0.01961205 0.79752697
## 
## $value
## [1] -19.2006
## 
## $counts
##  function iteration  restarts 
##    107700      1077         0 
## 
## $convergence
## [1] 4
## 
## $message
## [1] "Maximal number of iterations without improvement reached"

The solutions has Sharpe Ratio of 19.201.

Let’s check the total weight

## [1] 1

Based on PSO, here is how your asset should be distributed.

For this problem, PSO works better than Bayesian Optimization, indicated by the optimum fitness value. However, we only ran 30 function evalutions (20 from samples, 10 from iterations) with Bayesian Optimization, compared to PSO, which run more than 1000 evaluations. The trade-off is Bayesian Optimization ran slower than PSO, since the function evaluation is cheap. We will try in more complex problem via deep learning to see if the trade-off don’t change.

3.2 Machine Learning Application

We will try to classify whether a user will give a game an above average score based on the content of the reviews. We will use the neural network model. Reviews will be extracted using text mining approach. On this problem, we will optimize the hyper-parameter of the neural network. This problem is based on my previous post7.

3.2.1 Import Data

The dataset is user reviews of 100 best PC games from metacritic website. I already scraped the data, which you can download here .

The data consists of 4 variables:

  • V1: row index
  • game: the name of the game, consists of 100 different games
  • score: the score given by user, with scale of 0-10
  • category: category of the score given by metacritic, consists of Positive, Mixed, and Negative
  • review: the review of each user

Since we will use keras to build the neural network architecture, we will set the environment first.

3.2.2 Data Preprocessing

We want to clean the text by removing url and any word elongation. We will replace “?” with “questionmark” and “!” with “exclamationmark” to see if these characters can be useful in our analysis, etc.

Since we want to classify the score into above average or below average, we need to add the label into the data.

Finally, we will make a document term matrix, with the row indicate each review and the columns consists of top 1024 words in the entire reviews. We will use the matrix to classify if the user will give an above average score based on the appearance of one or more terms.

3.2.3 Cross-Validation

We will split the data into training set, validation set, and testing set. First, we split the data into training set and testing set.

3.2.5 Define Fitness Function

We will build the neural network architecture. Our model would have several layers. There are layer dense which will scale our data using the relu activation function on the first and second layer dense. There are also layer dropout to prevent the model from overfitting. Finally, we scale back our data into range of [0,1] with the sigmoid function as the probability of our data belong to a particular class. The epoch represent the number of our model doing the feed-forward and back-propagation.

We will try to optimize the dropout rate on the 1st and 2nd layer dropout. We will also optimize the learning rate.

3.2.6 Define Parameters

Define the search boundary

Define initial search sample

3.2.8 Bayesian Optimization

We will run the Bayesian Optimization with 10 iterations.

Check the optimal validation accuracy

## [1] 0.6858289

The best hyper-parameter so far from Bayesian Optimization with 68.58% accuracy on validation set.

3.2.9 Compare with Particle Swarm Optimization

First we need to readjust the fitness function to suit Particle Swarm Optimization

Let’s run the algorithm. See if it can get better solution than Bayesian Optimization. PSO will run in 100 iterations with 10 particles. If in 10 iterations PSO did not improve, the algorithm stop.

## $par
## [1] 0.3696738 0.6246933 0.5514350
## 
## $value
## [1] -0.6858289
## 
## $counts
##  function iteration  restarts 
##       110        11         0 
## 
## $convergence
## [1] 4
## 
## $message
## [1] "Maximal number of iterations without improvement reached"

PSO require more runtime since each function evaluation is heavy. The optimum accuracy (68.583%) is similare to those of Bayesian Optimization.

4 Conclusion

Bayesian Optimization is a method of optimization that apply probabilistic statistical model that will obtain optimum value with minimal number of function evaluation. It is best suited for problem with costly function evaluation, such as hyper-parameter tuning for deep learning model.

What is the benefit of doing optimization? We have illustrated that by using optimization method, be it Bayesian Optimization or Particle Swarm Optimization, we can achieve better performance, for example in machine learning we can achieve higher accuracy compared to the manual parameter setup. In exchange of longer computation, we can achieve better performance.

Compared to Particle Swarm Optimization, Bayesian optimization perform worse in portofolio optimization with longer runtime, but lower number of function evaluation. Since the function evaluation is not costly in these problem, PSO outperformed the Bayesian. Meanwhile for deep learning, Bayesian optimization outperform PSO runtime with quite similar optimum validation accuracy. Number of iterations may influence the result in Bayesian optimization.

5 Reference