- 5.1 Introduction
- 5.2 Loss Functions
- 5.3 Machine Learning via Bayesian Methods
- 5.4 Conclusion
5.3 Machine Learning via Bayesian Methods
Whereas frequentist methods strive to achieve the best precision about all possible parameters, machine learning cares to achieve the best prediction among all possible parameters. Often, your prediction measure and what frequentist methods are optimizing for are very different.
For example, least-squares linear regression is the simplest active machine-learning algorithm. I say active, as it engages in some learning, whereas predicting the sample mean is technically simpler, but is learning very little (if anything). The loss that determines the coefficients of the regressors is a squared-error loss. On the other hand, if your prediction loss function (or score function, which is the negative loss) is not a squared-error, your least-squares line will not be optimal for the prediction loss function. This can lead to prediction results that are suboptimal.
Finding Bayes actions is equivalent to finding parameters that optimize not parameter accuracy but an arbitrary performance measure; however, we wish to define “performance” (loss functions, AUC, ROC, precision/recall, etc.).
The next two examples demonstrate these ideas. The first example is a linear model where we can choose to predict using the least-squares loss or a novel, outcome-sensitive loss. The second example is adapted from a Kaggle data science project. The loss function associated with our predictions is incredibly complicated.
5.3.1 Example: Financial Prediction
Suppose the future return of a stock price is very small, say 0.01 (or 1%). We have a model that predicts the stock’s future price, and our profit and loss is directly tied to our acting on the prediction. How should we measure the loss associated with the model’s predictions, and subsequent future predictions? A squared-error loss is agnostic to the signage and would penalize a prediction of −0.01 equally as badly as a prediction of 0.03:
- (0.01 − (−0.01))2 = (0.01 − 0.03)2 = 0.004
If you had made a bet based on your model’s prediction, you would have earned money with a prediction of 0.03, and lost money with a prediction of −0.01, yet our loss did not capture this. We need a better loss that takes into account the sign of the prediction and true value. We design a new loss that is better for financial applications, shown in Figure 5.3.1.
figsize(12.5, 4)
def stock_loss(true_return, yhat, alpha=100.):
if true_return*yhat < 0:
# opposite signs, not good
return alpha*yhat**2 - np.sign(true_return)*yhat + abs(true_return)
else:
return abs(true_return - yhat)
true_value = .05
pred = np.linspace(-.04, .12, 75)
plt.plot(pred, [stock_loss(true_value, _p) for _p in pred], label = "loss associated with\n prediction if true value = 0.05", lw=3)
plt.vlines(0, 0, .25, linestyles="--")
plt.xlabel("Prediction")
plt.ylabel("Loss")
plt.xlim(-0.04, .12)
plt.ylim(0, 0.25)
true_value = -.02
plt.plot(pred, [stock_loss(true_value, _p) for _p in pred], alpha=0.6, label="loss associated with\n prediction if true value = -0.02", lw=3)
plt.legend()
plt.title("Stock returns loss if true value = 0.05, -0.02") ;
Figure 5.3.1: Stock returns loss if true value = 0.05, −0.02
Note the change in the shape of the loss as the prediction crosses 0. This loss reflects that the user really does not want to guess the wrong sign, and especially doesn’t want to be wrong and with a large magnitude.
Why would the user care about the magnitude? Why is the loss not 0 for predicting the correct sign? Surely, if the return is 0.01 and we bet millions, we will still be (very) happy.
Financial institutions treat downside risk (as in predicting a lot on the wrong side) and upside risk (as in predicting a lot on the right side) similarly. Both are seen as risky behavior and are discouraged. Therefore, we have an increasing loss as we move further away from the true price, with less extreme loss in the direction of the correct sign.
We will perform a regression on a trading signal that we believe predicts future returns well. Our dataset is artificial, as most financial data is not even close to linear. In Figure 5.3.2, we plot the data along with the least-squares line.
# code to create artificial data
N = 100
X = 0.025 * np.random.randn(N)
Y = 0.5 * X + 0.01 * np.random.randn(N)
ls_coef_ = np.cov(X, Y)[0,1]/np.var(X)
ls_intercept = Y.mean() - ls_coef_*X.mean()
plt.scatter(X, Y, c="k")
plt.xlabel("Trading signal")
plt.ylabel("Returns")
plt.title("Empirical returns versus trading signal")
plt.plot(X, ls_coef_ * X + ls_intercept, label="least-squares line")
plt.xlim(X.min(), X.max())
plt.ylim(Y.min(), Y.max())
plt.legend(loc="upper left");
Figure 5.3.2: Empirical returns versus trading signal
We perform a simple Bayesian linear regression on this dataset. We look for a model like
- R = α + βx +
where α, β are our unknown parameters and ~ Normal(0, 1/τ). The most common priors on β and α are Normal priors. We will also assign a prior on τ, so that is uniform over 0 to 100 (equivalently, then, τ = 1/Uniform(0, 100)2).
import pymc as pm
from pymc.Matplot import plot as mcplot
std = pm.Uniform("std", 0, 100, trace=False)
@pm.deterministic
def prec(U=std):
return 1.0 / U **2
beta = pm.Normal("beta", 0, 0.0001)
alpha = pm.Normal("alpha", 0, 0.0001)
@pm.deterministic
def mean(X=X, alpha=alpha, beta=beta):
return alpha + beta * X
obs = pm.Normal("obs", mean, prec, value=Y, observed=True)
mcmc = pm.MCMC([obs, beta, alpha, std, prec])
mcmc.sample(100000, 80000);
____________________________________________________________________________
[Output]:
[-----------------100%-----------------] 100000 of 100000 complete in
23.2 sec
____________________________________________________________________________
For a specific trading signal, call it x, the distribution of possible returns has the form
- Ri(x) = αi + βix +
where ~ Normal(0, 1/τi) and i indexes our posterior samples. We wish to find the solution to
according to the loss given. This r is our Bayes action for trading signal x. In Figure 5.3.3, we plot the Bayes action over different trading signals. What do you notice?
figsize(12.5, 6)
from scipy.optimize import fmin
def stock_loss(price, pred, coef=500):
sol = np.zeros_like(price)
ix = price*pred < 0
sol[ix] = coef * pred **2 - np.sign(price[ix]) * pred + abs(price[ix])
sol[~ix] = abs(price[~ix] - pred)
return sol
tau_samples = mcmc.trace("prec")[:]
alpha_samples = mcmc.trace("alpha")[:]
beta_samples = mcmc.trace("beta")[:]
N = tau_samples.shape[0]
noise = 1. / np.sqrt(tau_samples) * np.random.randn(N)
possible_outcomes = lambda signal: alpha_samples + beta_samples * signal +u noise
opt_predictions = np.zeros(50)
trading_signals = np.linspace(X.min(), X.max(), 50)
for i, _signal in enumerate(trading_signals):
_possible_outcomes = possible_outcomes(_signal)
tomin = lambda pred: stock_loss(_possible_outcomes, pred).mean()
opt_predictions[i] = fmin(tomin, 0, disp=False)
plt.xlabel("Trading signal")
plt.ylabel("Prediction")
plt.title("Least-squares prediction versus Bayes action prediction")
plt.plot(X, ls_coef_ * X + ls_intercept,
label="least-squares prediction")
plt.xlim(X.min(), X.max())
plt.plot(trading_signals, opt_predictions,
label="Bayes action prediction")
plt.legend(loc="upper left");
Figure 5.3.3: Least-squares prediction versus Bayes action prediction
What is interesting about Figure 5.3.3 is that when the signal is near 0, and many of the possible returns are possibly both positive and negative, our best (with respect to our loss) move is to predict close to 0; that is, take on no position. Only when we are very confident do we enter into a position. I call this style of model a sparse prediction, where we feel uncomfortable with our uncertainty so choose not to act. (Compare this with the least-squares prediction, which will rarely, if ever, predict 0.)
A good sanity check that our model is still reasonable is that as the signal becomes more and more extreme, and we feel more and more confident about the positiveness/negativeness of returns, our position converges with that of the least-squares line.
The sparse-prediction model is not trying to fit the data the best according to a squared-error loss definition of fit. That honor would go to the least-squares model. The sparse-prediction model is trying to find the best prediction with respect to our stock loss-defined loss. We can turn this reasoning around: The least-squares model is not trying to predict the best (according to a stock-loss definition of “predict”). That honor would go the sparse-prediction model. The least-squares model is trying to find the best fit of the data with respect to the squared-error loss.
5.3.2 Example: Kaggle Contest on Observing Dark Worlds
A personal motivation for learning Bayesian methods was trying to piece together the winning solution to Kaggle’s Observing Dark Worlds contest. From the contest’s website:2
- There is more to the Universe than meets the eye. Out in the cosmos exists a form of matter that outnumbers the stuff we can see by almost 7 to 1, and we don’t know what it is. What we do know is that it does not emit or absorb light, so we call it Dark Matter.
- Such a vast amount of aggregated matter does not go unnoticed. In fact we observe that this stuff aggregates and forms massive structures called Dark Matter Halos.
- Although dark, it warps and bends spacetime such that any light from a background galaxy which passes close to the Dark Matter will have its path altered and changed. This bending causes the galaxy to appear as an ellipse in the sky.
The contest required predictions about where dark matter was likely to be. The winner, Tim Salimans, used Bayesian inference to find the best locations for the halos (interestingly, the second-place winner also used Bayesian inference). With Tim’s permission, we provide his solution3 here.
- Construct a prior distribution for the halo positions p(x), i.e. formulate our expectations about the halo positions before looking at the data.
- Construct a probabilistic model for the data (observed ellipticities of the galaxies) given the positions of the dark matter halos: p(e|x).
- Use Bayes’ rule to get the posterior distribution of the halo positions, i.e. use to [sic] the data to guess where the dark matter halos might be.
- Minimize the expected loss with respect to the posterior distribution over the predictions for the halo positions: = arg minprediction Ep(x|e)[L(prediction, x)], i.e. tune our predictions to be as good as possible for the given error metric.
The loss function in this problem is very complicated. For the very determined, the loss function is contained in the file DarkWorldsMetric.py. Though I suggest not reading it all, suffice it to say the loss function is about 160 lines of code—not something that can be written down in a single mathematical line. The loss function attempts to measure the accuracy of prediction, in a Euclidean distance sense, such that no shift bias is present. More details can be found on the contest’s homepage.
We will attempt to implement Tim’s winning solution using PyMC and our knowledge of loss functions.
5.3.3 The Data
The dataset is actually 300 separate files, each representing a sky. In each file, or sky, are between 300 and 720 galaxies. Each galaxy has an x and y position associated with it, ranging from 0 to 4,200, and measures of ellipticity: e1 and e2. Information about what these measures mean can be found at https://www.kaggle.com/c/DarkWorlds/details/an-introduction-to-ellipticity, but we only care about that for visualization purposes. Thus, a typical sky might look like Figure 5.3.4.
from draw_sky2 import draw_sky
n_sky = 3 # choose a file/sky to examine
data = np.genfromtxt("data/Train_Skies/Train_Skies/\
Training_Sky%d.csv"%(n_sky),
dtype=None,
skip_header=1,
delimiter=",",
usecols=[1,2,3,4])
print "Data on galaxies in sky %d."%n_sky
print "position_x, position_y, e_1, e_2 "
print data[:3]
fig = draw_sky(data)
plt.title("Galaxy positions and ellipticities of sky %d."%n_sky)
plt.xlabel("$x$ position")
plt.ylabel("$y$ position");
____________________________________________________________________________
[Output]:
Data on galaxies in sky 3.
position_x, position_y, e_1, e_2
[[ 1.62690000e+02 1.60006000e+03 1.14664000e-01 -1.90326000e-01]
[ 2.27228000e+03 5.40040000e+02 6.23555000e-01 2.14979000e-01]
[ 3.55364000e+03 2.69771000e+03 2.83527000e-01 -3.01870000e-01]]
____________________________________________________________________________
Figure 5.3.4: Galaxy positions and ellipticities of sky 3
5.3.4 Priors
Each sky has one, two, or three dark matter halos in it. Tim’s solution details that his prior distribution of halo positions was uniform; that is,
Tim and other competitors noted that most skies had one large halo, and other halos, if present, were much smaller. Larger halos, having more mass, will influence the surrounding galaxies more. He decided that the large halos would have a mass distributed as a log-uniform random variable between 40 and 180; that is,
- mlarge = log Uniform(40, 180)
and in PyMC,
exp_mass_large = pm.Uniform("exp_mass_large", 40, 180) @pm.deterministic def mass_large(u = exp_mass_large): return np.log(u)
(This is what we mean when we say “log-uniform.”) For smaller galaxies, Tim set the mass to be the logarithm of 20. Why did Tim not create a prior for the smaller mass, or treat it as a unknown? I believe this decision was made to speed up convergence of the algorithm. This is not too restrictive, as by construction, the smaller halos have less influence on the galaxies.
Tim logically assumed that the ellipticity of each galaxy is dependent on the position of the halos, the distance between the galaxy and halo, and the mass of the halos. Thus, the vector of ellipticity of each galaxy, ei, are children variables of the vector of halo positions (x, y), distance (which we will formalize), and halo masses.
Tim conceived a relationship to connect positions and ellipticity by reading literature and forum posts. He supposed the following was a reasonable relationship:
where di, j is the tangential direction (the direction in which halo j bends the light of galaxy i), mj is the mass of halo j, and f (ri, j) is a decreasing function of the Euclidean distance between halo j and galaxy i.
Tim’s function f was defined:
for large halos, and for small halos
This fully bridges our observations and unknown. This model is incredibly simple, and Tim mentions that this simplicity was purposely designed; it prevents the model from overfitting.
5.3.5 Training and PyMC Implementation
For each sky, we run our Bayesian model to find the posteriors for the halo positions—we ignore the (known) halo position. This is slightly different from perhaps more traditional approaches to Kaggle competitions, where this model uses no data from other skies or from the known halo location. That does not mean other data are not necessary; in fact, the model was created by comparing different skies.
def euclidean_distance(x, y):
return np.sqrt(((x - y) **2).sum(axis=1))
def f_distance(gxy_pos, halo_pos, c):
# foo_position should be a 2D numpy array.
return np.maximum(euclidean_distance(gxy_pos, halo_pos), c)[:,None]
def tangential_distance(glxy_position, halo_position):
# foo_position should be a 2D numpy array.
delta = glxy_position - halo_position
t = (2*np.arctan(delta[:,1]/delta[:,0]))[:,None]
return np.concatenate([-np.cos(t), -np.sin(t)], axis=1)
import pymc as pm
# Set the size of the halo's mass.
mass_large = pm.Uniform("mass_large", 40, 180, trace=False)
# Set the initial prior position of the halos; it's a 2D Uniform
# distribution.
halo_position = pm.Uniform("halo_position", 0, 4200, size=(1,2))
@pm.deterministic
def mean(mass=mass_large, h_pos=halo_position, glx_pos=data[:,:2]):
return mass/f_distance(glx_pos, h_pos, 240)* tangential_distance(glx_pos, h_pos)
ellpty = pm.Normal("ellipticity", mean, 1./0.05, observed=True,
value=data[:,2:])
mcmc = pm.MCMC([ellpty, mean, halo_position, mass_large])
map_ = pm.MAP([ellpty, mean, halo_position, mass_large])
map_.fit()
mcmc.sample(200000, 140000, 3)
____________________________________________________________________________
[Output]:
[****************100%******************] 200000 of 200000 complete
____________________________________________________________________________
In Figure 5.3.5, we plot a heatmap of the posterior distribution (this is just a scatter plot of the posterior, but we can visualize it as a heatmap). As you can see in the figure, the red spot denotes our posterior distribution over where the halo is.
t = mcmc.trace("halo_position")[:].reshape (20000,2)
fig = draw_sky(data)
plt.title("Galaxy positions and ellipticities of sky %d."%n_sky)
plt.xlabel("$x$ position")
plt.ylabel("$y$ position")
scatter(t[:,0], t[:,1], alpha=0.015, c="r")
plt.xlim(0, 4200)
plt.ylim(0, 4200);
Figure 5.3.5: Galaxy positions and ellipticities of sky 3
The most probable position reveals itself like a lethal wound.
Associated with each sky is another data point, located in Training halos.csv, that holds the locations of up to three dark matter halos contained in the sky. For example, the night sky we trained on has halo locations
halo_data = np.genfromtxt("data/Training_halos.csv",
delimiter=",",
usecols=[1,2,3,4,5,6,7,8,9],
skip_header=1)
print halo_data[n_sky]
____________________________________________________________________________
[Output]:
[ 3.00000000e+00 2.78145000e+03 1.40691000e+03 3.08163000e+03
1.15611000e+03 2.28474000e+03 3.19597000e+03 1.80916000e+03
8.45180000e+02]
____________________________________________________________________________
The third and fourth column represent the true x and y position of the halo. It appears that the Bayesian method has located the halo within a tight vicinity, as denoted by the black dot in Figure 5.3.6.
fig = draw_sky(data)
plt.title("Galaxy positions and ellipticities of sky %d."%n_sky)
plt.xlabel("$x$ position")
plt.ylabel("$y$ position")
plt.scatter(t[:,0], t[:,1], alpha=0.015, c="r")
plt.scatter(halo_data[n_sky-1][3], halo_data[n_sky-1][4],
label="true halo position",
c="k", s=70)
plt.legend(scatterpoints=1, loc="lower left")
plt.xlim(0, 4200)
plt.ylim(0, 4200);
print "True halo location:", halo_data[n_sky][3], halo_data[n_sky][4]
____________________________________________________________________________
[Output]:
True halo location: 1408.61 1685.86
____________________________________________________________________________
Figure 5.3.6: Galaxy positions and ellipticities of sky 3
Perfect. Our next step is to use the loss function to optimize our location. A naive strategy would be to simply choose the mean:
mean_posterior = t.mean(axis=0).reshape(1,2)
print mean_posterior
____________________________________________________________________________
[Output]:
[[ 2324.07677813 1122.47097816]]
____________________________________________________________________________
from DarkWorldsMetric import main_score
_halo_data = halo_data[n_sky-1]
nhalo_all = _halo_data[0].reshape(1,1)
x_true_all = _halo_data[3].reshape(1,1)
y_true_all = _halo_data[4].reshape(1,1)
x_ref_all = _halo_data[1].reshape(1,1)
y_ref_all = _halo_data[2].reshape(1,1)
sky_prediction = mean_posterior
print "Using the mean:"
main_score(nhalo_all, x_true_all, y_true_all, x_ref_all, y_ref_all, sky_prediction)
# What's a bad score?
print
random_guess = np.random.randint(0, 4200, size=(1,2))
print "Using a random location:", random_guess
main_score(nhalo_all, x_true_all, y_true_all, x_ref_all, y_ref_all, random_guess)
print
____________________________________________________________________________
[Output]:
Using the mean:
Your average distance in pixels away from the true halo is
31.1499201664
Your average angular vector is 1.0
Your score for the training data is 1.03114992017
Using a random location: [[2755 53]]
Your average distance in pixels away from the true halo is
1773.42717812
Your average angular vector is 1.0
Your score for the training data is 2.77342717812
____________________________________________________________________________
This is a good guess; it is not very far from the true location, but it ignores the loss function that was provided to us. We also need to extend our code to allow for up to two additional, smaller halos. Let’s create a function for automatizing our PyMC.
from pymc.Matplot import plot as mcplot
def halo_posteriors(n_halos_in_sky, galaxy_data,
samples = 5e5, burn_in = 34e4, thin = 4):
# Set the size of the halo's mass.
mass_large = pm.Uniform("mass_large", 40, 180)
mass_small_1 = 20
mass_small_2 = 20
masses = np.array([mass_large,mass_small_1, mass_small_2],
dtype=object)
# Set the initial prior positions of the halos; it's a 2D Uniform
# distribution.
halo_positions = pm.Uniform("halo_positions", 0, 4200,
size=(n_halos_in_sky,2))
fdist_constants = np.array([240, 70, 70])
@pm.deterministic
def mean(mass=masses, h_pos=halo_positions, glx_pos=data[:,:2],
n_halos_in_sky = n_halos_in_sky):
_sum = 0
for i in range(n_halos_in_sky):
_sum += mass[i] / f_distance (glx_pos,h_pos[i, :],
fdist_constants[i])* tangential_distance (glx_pos, h_pos[i, :])
return _sum
ellpty = pm.Normal("ellipticity", mean, 1. / 0.05, observed=True,
value = data[:,2:])
map_ = pm.MAP([ellpty, mean, halo_positions, mass_large])
map_.fit(method="fmin_powell")
mcmc = pm.MCMC([ellpty, mean, halo_positions, mass_large])
mcmc.sample(samples, burn_in, thin)
return mcmc.trace("halo_positions")[:]
n_sky =215
data = np.genfromtxt("data/Train_Skies/Train_Skies/\
Training_Sky%d.csv"%(n_sky),
dtype=None,
skip_header=1,
delimiter=",",
usecols=[1,2,3,4])
# There are 3 halos in this file.
samples = 10.5e5
traces = halo_posteriors(3, data, samples=samples,
burn_in=9.5e5,
thin=10)
____________________________________________________________________________
[Output]:
[****************100%******************] 1050000 of 1050000 complete
____________________________________________________________________________
fig = draw_sky(data)
plt.title("Galaxy positions, ellipticities, and halos of sky %d."%n_sky)
plt.xlabel("$x$ position")
plt.ylabel("$y$ position")
colors = ["#467821", "#A60628", "#7A68A6"]
for i in range(traces.shape[1]):
plt.scatter(traces[:, i, 0], traces[:, i, 1], c=colors[i],
alpha=0.02)
for i in range(traces.shape[1]):
plt.scatter(halo_data[n_sky-1][3 + 2 * i],
halo_data[n_sky-1][4 + 2 * i],
label="true halo position", c="k", s=90)
plt.xlim(0, 4200)
plt.ylim(0, 4200);
____________________________________________________________________________
[Output]:
(0, 4200)
____________________________________________________________________________
As you can see in Figure 5.3.7, this looks pretty good, though it took a long time for the system to (sort of) converge. Our optimization step would look something like this.
_halo_data = halo_data[n_sky-1]
print traces.shape
mean_posterior = traces.mean(axis=0).reshape(1,4)
print mean_posterior
nhalo_all = _halo_data[0].reshape(1,1)
x_true_all = _halo_data[3].reshape(1,1)
y_true_all = _halo_data[4].reshape(1,1)
x_ref_all = _halo_data[1].reshape(1,1)
y_ref_all = _halo_data[2].reshape(1,1)
sky_prediction = mean_posterior
print "Using the mean:"
main_score([1], x_true_all, y_true_all, x_ref_all, y_ref_all, sky_prediction)
# What's a bad score?
print
random_guess = np.random.randint(0, 4200, size=(1,2))
print "Using a random location:", random_guess
main_score([1], x_true_all, y_true_all, x_ref_all, y_ref_all, random_guess)
print
____________________________________________________________________________
[Output]:
(10000L, 2L, 2L)
[[ 48.55499317 1675.79569424 1876.46951857 3265.85341193]]
Using the mean:
Your average distance in pixels away from the true halo is
37.3993004245
Your average angular vector is 1.0
Your score for the training data is 1.03739930042
Using a random location: [[2930 4138]]
Your average distance in pixels away from the true halo is
3756.54446887
Your average angular vector is 1.0
Your score for the training data is 4.75654446887
____________________________________________________________________________
Figure 5.3.7: Galaxy positions, ellipticities, and halos of sky 215