<jupyter_start><jupyter_text>Dirichlet Process<jupyter_code>import scipy.stats as st
import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Stick-breaking<jupyter_code>class DirichletProcess:
    def __init__(self, alpha, n, G_0):
        self.alpha = alpha
        self.n = n
        self.G_0 = G_0
    
    def pdf(self):
        b = st.beta(1, self.alpha).rvs(size=self.n)
        p = np.zeros(self.n)
        p[0] = b[0]
        p[1:] = np.asarray([b[i] * np.prod(1-b[:i]) for i in range(1,self.n)])
        p[-1] = 1 - sum(p[:-1])
        return p
    
    def rvs(self, size, y=None):
        p = self.pdf()
        if y is None:
            y = self.G_0.rvs(size=size)
        return np.random.choice(y, size=size, replace=True, p=p)
dp = DirichletProcess(alpha=10, n=1000, G_0=st.norm(0, 1))
y = dp.G_0.rvs(dp.n)
p = dp.pdf()
fix, ax = plt.subplots(figsize=(20,8))
[ax.vlines(y[i], 0, p[i]) for i in range(dp.n)]
ax.set_ylim(0,None)
ax.set_xlim(-4,4)
ax.grid(True)
ax.set_title(f"$\\alpha$ = {dp.alpha}");
dp = [None] * 4
dp[0] = DirichletProcess(alpha=1, n=10000, G_0=st.norm(0, 1))
dp[1] = DirichletProcess(alpha=10, n=10000, G_0=st.norm(0, 1))
dp[2] = DirichletProcess(alpha=100, n=10000, G_0=st.norm(0, 1))
dp[3] = DirichletProcess(alpha=1000, n=10000, G_0=st.norm(0, 1))
fix, axs = plt.subplots(4, 3, figsize=(24,24))
for k in range(4):
    for j in range(3):
        y = dp[k].G_0.rvs(dp[k].n)
        p = dp[k].pdf()
        [axs[k,j].vlines(y[i], 0, p[i]) for i in range(dp[k].n)]
        axs[k,j].set_ylim(0,None)
        axs[k,j].set_xlim(-4,4)
        axs[k,j].grid(True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1946955997588909, 'fraction_numerical': 0.054249547920433995, 'mean_word_length': 3.15, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, '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': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '623231', 'license': 'Apache-2.0', 'n_tokens_mistral': 799, 'n_tokens_neox': 745, 'n_words': 137, 'path': 'notebooks/Dirichlet_Process.ipynb', 'repo_name': 'dbernaciak/bayes-np', 'size': '1659'}