segasai

Untitled

Oct 17th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. import numpy as np
  2. import scipy.stats
  3. import scipy.optimize
  4. np.random.seed(1)
  5.  
  6. # input
  7. cov0 = np.array([[1.19, -0.08, 0., -0.08], [-0.08, 0.68, 0.02, -0.04],
  8.                  [0., 0.02, 0.9, -0.05], [-0.08, -0.04, -0.05, 0.65]])
  9.  
  10. mu0 = np.array([1, 2, 3, 4])
  11. print('input', mu0)
  12. print(cov0)
  13.  
  14. N1 = 100000
  15. N2 = 120000
  16.  
  17. xs1 = np.random.multivariate_normal(mu0, cov0, size=N1)
  18. xs2 = np.random.multivariate_normal(mu0, cov0, size=N2)
  19.  
  20. proj1 = np.array([[1, 0, 0, 0], [0, 1, 0, 0]])
  21. proj2 = np.array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
  22.  
  23. # measurements
  24. xmeas1 = np.dot(xs1, proj1.T)
  25. xmeas2 = np.dot(xs2, proj2.T)
  26.  
  27. ndim = 4
  28.  
  29.  
  30. def like(p, getVecMat=False):
  31.     # likelihood of two dataset given mean vector and covar mat
  32.  
  33.     mean = p[:ndim]
  34.     covar = np.zeros((ndim, ndim))
  35.     covar[np.arange(ndim), np.arange(ndim)] = p[ndim:2 * ndim]
  36.     ix, iy = np.tril_indices(ndim, -1)
  37.     covar[ix, iy] = p[2 * ndim:]
  38.     covar[iy, ix] = p[2 * ndim:]
  39.     eigv = scipy.linalg.eigh(covar)[0]
  40.     if np.any(eigv <= 0):
  41.         #print('oops')
  42.         return 1e30
  43.     if getVecMat:
  44.         return mean, covar
  45.  
  46.     c1 = np.dot(proj1, np.dot(covar, proj1.T))
  47.     c2 = np.dot(proj2, np.dot(covar, proj2.T))
  48.     m1 = np.dot(mean, proj1.T)
  49.     m2 = np.dot(mean, proj2.T)
  50.     L1 = scipy.stats.multivariate_normal(m1, c1).logpdf(xmeas1)
  51.     L2 = scipy.stats.multivariate_normal(m2, c2).logpdf(xmeas2)
  52.     lprior = scipy.stats.wishart(df=4, scale=np.ones(4)).logpdf(covar)
  53.     logp = L1.sum() + L2.sum() + lprior
  54.     return -logp
  55.  
  56.  
  57. R = scipy.optimize.minimize(
  58.     like, np.r_[np.ones(4), np.ones(4), np.zeros(6)], method='Nelder-Mead')
  59. R = scipy.optimize.minimize(
  60.     like, R['x'])
  61. retmean, retcov = like(R['x'], True)
  62.  
  63. print('output', np.round(retmean, 3))
  64. print(np.round(retcov, 3))
  65.  
  66. $ python xx.py
  67. input [1 2 3 4]
  68. [[ 1.19 -0.08  0.   -0.08]
  69.  [-0.08  0.68  0.02 -0.04]
  70.  [ 0.    0.02  0.9  -0.05]
  71.  [-0.08 -0.04 -0.05  0.65]]
  72. output [1.001 1.998 3.002 4.   ]
  73. [[ 1.188 -0.084 -0.299 -0.056]
  74.  [-0.084  0.682  0.019 -0.041]
  75.  [-0.299  0.019  0.901 -0.053]
  76.  [-0.056 -0.041 -0.053  0.652]]
Advertisement
Add Comment
Please, Sign In to add comment