In: Computer Science
Implement the Metropolis-Hastings algorithm below¶
Make sure to read this: Implement the algorithm described above (in the "How it works" section), where you take some user-defined number of steps that randomly step in W and I and are scaled by a step_size. This means you don't want to take steps of a discrete size, but instead use a random distribution of step sizes that are scaled by your step_size variable. You'll want to take steps that have an equal chance of either decrementing or incrementing the values of W and I. Also, W and I don't have to incremented by the exact same amount, in fact, it would best if they weren't so that you can explore more of the parameter space.
Keep track of your accepted guesses for width and intercepts in the lists that are provided below. We have included variables with reasonable values of these quantities to get you started.
# Total number of points we're going to sample (start out with
at least 10^4)
num_sample_points = 100000
# Weight factor in front of the random step
step_size = 0.1
# As we move the walker around, we'll use these same lists
to
# store our new values so that we can visualize the path later!
# (Note: that means you'll want to append new values to these lists!)
widths = [2]
intercepts = [2]
## PUT YOUR CODE HERE ###
SOURCE CODE IN PYTHON:
# Total number of points we're going to sample (start out with at least 10^4)
num_sample_points = 100000
# Weight factor in front of the random step
step_size = 0.1
# As we move the walker around, we'll use these same lists to
# store our new values so that we can visualize the path later!
# (Note: that means you'll want to append new values to these lists!)
widths = [2]
intercepts = [2]
## PUT YOUR CODE HERE ###
import random
for i in range(num_sample_points):
w_change=random.randint(-10, 10)*step_size
i_change=random.randint(-10, 10)*step_size
widths.append(widths[len(widths)-1]+w_change)
intercepts.append(intercepts[len(intercepts)-1]+i_change)
#output the first 10 values of each
for i in widths[:10]:
print('%.2f ' %i, end='')
print()
for i in intercepts[:10]:
print('%.2f ' %i, end='')
print()
OUTPUT:
Refer to screenshot of code for indentations.