It uses special functions math ndtr and ndtri, a Gaussian distribution and inverse distribution functions. Since these functions cannot be found by the search API, including here.
import numpy as np
import tensorflow as tf
from tensorflow.python.ops.distributions import special_math as dsm
import matplotlib.pylab as pl
def tf_conditioned_normal(x1,x2, dtype = tf.float32):
Fx1 = dsm.ndtr(x1)
Fx2 = dsm.ndtr(x2)
gamma = tf.random_uniform([1], dtype = dtype)
return dsm.ndtri(Fx1 + gamma*(Fx2 - Fx1))
if __name__ == '__main__':
graph = tf.Graph()
with graph.as_default():
t_x1ph = tf.placeholder(tf.float32,[])
t_x2ph = tf.placeholder(tf.float32,[])
t_cn = tf_conditioned_normal(t_x1ph,t_x2ph, dtype = tf.float32)
t_rn = tf.random_normal([1])
sess = tf.Session(graph = graph)
print 'Conditioned...'
x1 = -5.
x2 = -1.
N = 5000
res = np.zeros(N)
for i in xrange(N):
res[i] = sess.run(t_cn,
feed_dict = {
t_x1ph : x1 ,
t_x2ph : x2 ,
}
)
print 'Regular...'
Nn = 50000
nres = np.zeros(Nn)
for i in xrange(Nn):
nres[i] = sess.run(t_rn)
nres = nres[ (nres>=x1) & (nres <= x2) ]
pl.figure()
tmp = pl.hist(res, np.linspace(x1,x2,200), normed = True)
tmp = pl.hist(nres, np.linspace(x1,x2,200), normed = True, alpha = 0.7)
pl.show()
source
share