Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.06 KB | None | 0 0
  1. import time
  2.  
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import pymc3 as pm
  6. import theano.tensor as tt
  7. import pystan
  8.  
  9.  
  10. # CONFIG
  11. # ----------------------------------------------------------------------
  12. R = 10 # number of runs
  13. K = 5 # predictor dimension
  14. N = 10000 # number of samples
  15.  
  16. # Data generation
  17. # ----------------------------------------------------------------------
  18. def scale(w0, w1):
  19. scale = np.sqrt(w0**2 + np.sum(w1**2))
  20. return w0/scale, w1/scale
  21.  
  22.  
  23. X = np.random.rand(N, K) # predictors
  24. w1 = np.random.rand(K) # weights
  25. w0 = -np.median(np.dot(X, w1)) # 50% of elements for each class
  26. w0, w1 = scale(w0, w1) # unit length (euclidean)
  27. y = w0 + np.dot(X, w1) > 0 # labels
  28.  
  29.  
  30. def stan_model(n_samples=1000, n_chains=8, verbose=False):
  31. logit_code = r"""
  32. functions {
  33. real sigmoid(real x) {
  34. return 1.0/(1.0 + exp(-x));
  35. }
  36. }
  37. data {
  38. int<lower=0> N; // number of samples
  39. int<lower=0> K; // number of predictors
  40. real X[N, K]; // sample predictors
  41. int<lower=0,upper=1> y[N]; // labels
  42. }
  43.  
  44. parameters {
  45. real w0;
  46. real w1[K];
  47. }
  48.  
  49. transformed parameters {
  50. real p[N];
  51. real x;
  52. for (i in 1:N) {
  53. x = w0;
  54. for (j in 1:K) {
  55. x = x + w1[j]*X[i, j];
  56. }
  57. p[i] = sigmoid(x);
  58. }
  59. }
  60.  
  61. model {
  62. w0 ~ normal(0, 20);
  63. w1 ~ normal(0, 20);
  64. y ~ bernoulli(p);
  65. }
  66. """
  67.  
  68. logit_data = {
  69. 'N': len(y),
  70. 'K': K,
  71. 'X': X,
  72. 'y': y.astype(int)
  73. }
  74. fit = pystan.stan(
  75. model_code=logit_code,
  76. data=logit_data,
  77. iter=n_samples,
  78. chains=8,
  79. verbose=verbose)
  80. trace = fit.extract()
  81. return trace
  82.  
  83.  
  84. def pymc_model(n_samples=8000, verbose=False):
  85. with pm.Model():
  86. w0_pred = pm.Normal('w0', 0, 20)
  87. w1_pred = pm.Normal('w1', 0, 20, shape=K)
  88. y_pred = pm.Bernoulli('y',
  89. p=tt.nnet.sigmoid(w0_pred + tt.dot(X, w1_pred)),
  90. observed=y.astype(int))
  91. trace = pm.sample(n_samples, progressbar=verbose)
  92. return trace
  93.  
  94.  
  95. def get_weights(trace, discard=0):
  96. if discard == 'half':
  97. discard = len(trace['w0'])/2
  98. return scale(
  99. np.mean(trace['w0'][discard:], axis=0),
  100. np.mean(trace['w1'][discard:], axis=0))
  101.  
  102. w_true = np.hstack((w0, w1))
  103. w_stan = np.empty((R, K + 1))
  104. w_pymc = np.empty((R, K + 1))
  105. for i in range(R):
  106. trace_stan = stan_model(100, 8)
  107. w_stan[i, :] = np.hstack(get_weights(trace_stan))
  108.  
  109. trace_pymc = pymc_model(800)
  110. w_pymc[i, :] = np.hstack(get_weights(trace_pymc, discard='half'))
  111.  
  112. def avg_error(w_true, w_pred):
  113. return np.mean(np.sum((w_pred - w_true)**2, axis=1), axis=0)
  114.  
  115. print('Avg error (stan):', avg_error(w_true, w_stan))
  116. print('Avg error (pymc):', avg_error(w_true, w_pymc))
  117.  
  118. # Avg error (stan): 4.60143514284e-06
  119. # Avg error (pymc): 0.00473672889666
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement