Pm.mixture not working

I wanted to code a weibull mixture with 4 prior gamma but when I execute the code the message below appear, any recommendation ?

import pymc as pm
import numpy as np
import pytensor
import pytensor.tensor as pt
import arviz as az
import matplotlib.pyplot as plt

# Set values for the prior parameters
gamma_mode = 1
gamma_variance = 0.5
gamma_2_mean = 40.0
gamma_2_variance = 100.0

z = np.array([0.05, 1, 0.18, 0.19])

# Definition of prior for gammamixt1
aux1 = 2.0 + (gamma_mode**2.0) / gamma_variance
a = 0.5 * (aux1 + np.sqrt(aux1**2.0 - 4.0))
b = gamma_mode / (a - 1.0)

# Definition of prior for gammamixt2
ap = (gamma_2_mean)**2 / gamma_2_variance
bp = gamma_2_mean / gamma_2_variance

# Definition of prior for gammamixt3
aux2 = 2.0 + (gamma_mode**2.0) / gamma_variance
aa = 0.5 * (aux1 + np.sqrt(aux1**2.0 - 4.0))
bb = gamma_mode / (a - 1.0)

# Definition of prior for gammamixt4
app = (gamma_2_mean)**2 / gamma_2_variance
bpp = gamma_2_mean / gamma_2_variance

# Définition des paramètres du modèle
with pm.Model() as model:
    # Paramètre p
    p = pm.Uniform('p', 0, 1)
    
    # Paramètres de la distribution Weibull pour PDF1
    gammamixt1 = pm.Gamma('gammamixt1', alpha=a, beta=1/b)
    gammamixt2 = pm.Gamma('gammamixt2', alpha=ap, beta= bp)
    gammamixt3 = pm.Gamma('gammamixt3', alpha=aa, beta=1/bb)
    gammamixt4 = pm.Gamma('gammamixt4', alpha=app, beta=bpp)
    
    # DĂ©finition des PDF Weibull
    components = [
    pm.Weibull.dist('pdf1',alpha=gammamixt1, beta=gammamixt2),
    pm.Weibull.dist('pdf2', alpha=gammamixt3, beta=gammamixt4)
    ]
    
    # `shape=(2,)` indicates 2 mixture components
    components = pm.Weibull.dist(alpha=pm.math.stack([gammamixt1, gammamixt2], beta=pm.math.stack([gammamixt3, gammamixt4]), shape=(4,))
    
    # PDF mixte
    pdf_mixture = pm.Mixture('pdf_mixture', w=[p, 1 - p], comp_dists=components, observed=z)

# Échantillonnage
with model:
    trace = pm.sample(10000, tune=1000)

# RĂ©sultats
pm.summary(trace)
File "<ipython-input-18-bdf970718404>", line 55
    pdf_mixture = pm.Mixture('pdf_mixture', w=[p, 1 - p], comp_dists=components, observed=z)
    ^
SyntaxError: invalid syntax

This is a python error, it’s telling you that you have a typo. Usually it’s one line above the line that the interpreter flags for you. If you look closely here:

    components = pm.Weibull.dist(alpha=pm.math.stack([gammamixt1, gammamixt2], beta=pm.math.stack([gammamixt3, gammamixt4]), shape=(4,))

You will see that you are missing a ) to close the first pm.math.stack function.

1 Like