<jupyter_start><jupyter_text>https://discourse.pymc.io/t/how-to-use-a-densitydist-in-a-mixture/1371/<jupyter_code>%pylab inline
import pymc3 as pm
d1 =  np.random.normal(loc=1,scale=1,size=1000) # toy data set

with pm.Model() as model:
    mu = pm.HalfNormal('mu',sd=1,shape=1)
    sd = pm.HalfNormal('sd',sd=1,shape=1)
    g = pm.Normal.dist(mu=mu,sd=sd,shape=1)
    obs = pm.DensityDist('obs',logp=g.logp,random=g.random,observed=d1)
    trace = pm.sample(draws=1000, tune=1000,chains=1)
    
pm.traceplot(trace);
plt.show()
# toy dataset
d1 = np.random.normal(loc=1, scale=1, size=1000)
d2 = np.random.normal(loc=2, scale=2, size=500)
data = np.concatenate([d1, d2])  # a bimodal toy data set

with pm.Model() as model:
    mu = pm.HalfNormal('mu', sd=1, shape=2)
    sd = pm.HalfNormal('sd', sd=1, shape=2)
    g = pm.Normal.dist(mu=mu, sd=sd, shape=2)
    
    comp = pm.DensityDist('comp', logp=g.logp, random=g.random, shape=2)
    comp_dists = comp.distribution
    comp_dists.mean = comp_dists.mode = g.mean#np.array([0, 0])
    
    w = pm.Dirichlet('w', a=np.array([1, 1]))
    mix = pm.Mixture('mix', w=w, comp_dists=comp_dists, observed=data)

    trace = pm.sample(draws=1000, tune=1000, chains=1)

pm.traceplot(trace)
plt.show()<jupyter_output>Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Sequential sampling (1 chains in 1 job)
NUTS: [w, comp, sd, mu]
100%|██████████| 2000/2000 [00:11<00:00, 172.87it/s]
Only one chain was sampled, this makes it impossible to run some convergence checks
{'fraction_non_alphanumeric': 0.17643229166666666, 'fraction_numerical': 0.056640625, 'mean_word_length': 4.392982456140351, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 4, 'https://': 1, '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': '520203', 'license': 'MIT', 'n_tokens_mistral': 696, 'n_tokens_neox': 633, 'n_words': 124, 'path': 'PyMC3QnA/mixture/mixture_with_densitydist.ipynb', 'repo_name': 'junpenglao/Planet_Sakaar_Data_Science', 'size': '1536'}