from d2l import tensorflow as d2l
import tensorflow as tf
tf.pi = tf.acos(tf.zeros(1)) * 2 # define pi in TensorFlow
# Sample datapoints and create y coordinate
epsilon = 0.1
tf.random.set_seed(8675309)
xs = tf.random.normal((300,))
ys = tf.constant(
[(tf.reduce_sum(tf.exp(-(xs[:i] - xs[i])**2 / (2 * epsilon**2)) \
/ tf.sqrt(2*tf.pi*epsilon**2)) / tf.cast(
tf.size(xs), dtype=tf.float32)).numpy() \
for i in range(tf.size(xs))])
# Compute true density
xd = tf.range(tf.reduce_min(xs), tf.reduce_max(xs), 0.01)
yd = tf.exp(-xd**2/2) / tf.sqrt(2 * tf.pi)
# Plot the results
d2l.plot(xd, yd, 'x', 'density')
d2l.plt.scatter(xs, ys)
d2l.plt.axvline(x=0)
d2l.plt.axvline(x=tf.reduce_mean(xs), linestyle='--', color='purple')
d2l.plt.title(f'sample mean: {float(tf.reduce_mean(xs).numpy()):.2f}')
d2l.plt.show()