<jupyter_start><jupyter_text>Metropolis-Hasting算法<jupyter_code>def metropolis(func, steps = 100000):
    """A very simple Metropolis implementation """
    samples = np.zeros(steps)
    old_x = func.mean()
    old_prob = func.pdf(old_x) #PDF概率密度函数
    
    for i in range(steps):
        new_x = old_x + np.random.normal(0, 0.5)
        new_prob = func.pdf(new_x)
        acceptance = new_prob / new_x
        if acceptance >= np.random.random():
            samples[i] = new_x
            old_x = new_x
            old_prob = new_prob
        else:
            samples[i] = old_x
    return samples
        
from scipy import stats

func = stats.beta(0.4,2)
samples = metropolis(func=func)
x = np.linspace(0.01, .99, 100)
y = func.pdf(x)
plt.xlim(0,1)
plt.plot(x, y, 'r-', lw=3, label = 'True distribution')
plt.hist(samples, bins=30,  normed=True, label='Estimated distribution')
plt.xlabel('$x$', fontsize=14)
plt.ylabel('$pdf(x)$',fontsize=14)
plt.legend(fontsize=14)

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1441263573543929, 'fraction_numerical': 0.03060217176702863, 'mean_word_length': 3.072289156626506, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '291220', 'license': 'MIT', 'n_tokens_mistral': 414, 'n_tokens_neox': 391, 'n_words': 75, 'path': 'Chapter 2/demo.ipynb', 'repo_name': 'chenmengjie-xiaomi/BayesianAnalysis', 'size': '1013'}