Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
import theano
2
import theano.tensor as T
3
import numpy as np
4
5
probabilities = T.vector()
6
nb_samples = T.iscalar()
7
8
rng = T.shared_randomstreams.RandomStreams(1234)
9
10
11
def sample_from_pvect(pvect):
12
""" Provided utility function: given a symbolic vector of
13
probabilities (which MUST sum to 1), sample one element
14
and return its index.
15
"""
16
onehot_sample = rng.multinomial(n=1, pvals=pvect)
17
sample = onehot_sample.argmax()
18
return sample
19
20
21
def set_p_to_zero(pvect, i):
22
""" Provided utility function: given a symbolic vector of
23
probabilities and an index 'i', set the probability of the
24
i-th element to 0 and renormalize the probabilities so they
25
sum to 1.
26
"""
27
new_pvect = T.set_subtensor(pvect[i], 0.)
28
new_pvect = new_pvect / new_pvect.sum()
29
return new_pvect
30
31
32
def step(p):
33
sample = sample_from_pvect(p)
34
new_p = set_p_to_zero(p, sample)
35
return new_p, sample
36
37
output, updates = theano.scan(fn=step,
38
outputs_info=[probabilities, None],
39
n_steps=nb_samples)
40
41
modified_probabilities, samples = output
42
43
f = theano.function(inputs=[probabilities, nb_samples],
44
outputs=[samples],
45
updates=updates)
46
47
# Testing the function
48
test_probs = np.asarray([0.6, 0.3, 0.1], dtype=theano.config.floatX)
49
for i in range(10):
50
print(f(test_probs, 2))
51
52