Hi,
I am implementing LDA with pymc3. I referred to the code for pymc
import numpy as np
import pymc as pm
K = 2 # number of topics
V = 4 # number of words
D = 3 # number of documents
data = np.array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]])
alpha = np.ones(K)
beta = np.ones(V+1)
theta = pm.Container([pm.Dirichlet("theta_%s" % i, theta=alpha) for i in range(D)])
phi = pm.Container([pm.Dirichlet("phi_%s" % k, theta=beta) for k in range(K)])
Wd = [len(doc) for doc in data]
z = pm.Container([pm.Categorical('z_%i' % d,
p = theta[d],
size=Wd[d],
value=np.random.randint(K, size=Wd[d]),
verbose=1)
for d in range(D)])
w = pm.Container([pm.Categorical("w_%i" % d,
p = pm.Lambda('phi_z_%i' % d, lambda z=z, phi=phi: [phi[z[d][i]] for i in range(Wd[d])]),
value=data[d],
observed=True,
verbose=1)
for d in range(D)])
model = pm.Model([theta, phi, z, w])
mcmc = pm.MCMC(model)
mcmc.sample(100, burn=10)
I am trying to use it for pymc3 but I am facing problems while defining
w
import numpy as np
import pymc3 as pm, theano, theano.tensor as t
K = 2 # number of topics
V = 4 # number of words
D = 3 # number of documents
data = np.array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]])
alpha = np.ones(K)
beta = np.ones(V)
model = pm.Model()
Wd = [len(doc) for doc in data]
(D, W) = data.shape
#print(Wd[])
@theano.compile.ops.as_op(itypes=[t.lscalar, t.dscalar],otypes=[t.dvector])
def p(z=z, phi=phi):
return [phi[z[i,j]] for i in range(D) for j in range(Wd)]
with model:
theta = [pm.Dirichlet("pthetax_%s" % i, a=alpha, shape=K) for i in range(D)]
phi =[pm.Dirichlet("pphix_%s" % k, a=beta,shape=V) for k in range(K)]
z = [pm.Categorical('zx_%i' % d,
p = theta[d],
shape=W)
for d in range(D)]
w = [pm.Categorical("wx_%i_%i" % (d,i),
p = p(z,phi), observed = data[d][i])
for d in range(D) for i in range(W)]
#model = pm.Model([theta, phi, z, w])
with model:
step1 = pm.Metroplolis(vars = [theta,phi,z,w])
tr = step1.sample(1000,step = [step1])
pm.plots.traceplot(tr, ['theta', 'phi', 'z','w']);
But everytime I am getting the error:
AttributeError: ‘list’ object has no attribute ‘type’
Can someone please help me with this? Or is there any other way of implementing LDA using pymc3.