5
最近,我在Python上使用numpy實現了針對LDA主題模型的Gibbs採樣,並將其作爲參考來源於站點的一些代碼。在吉布斯採樣的每次迭代中,我們刪除一個(當前)字,根據LDA模型推斷的後驗條件概率分佈爲該字採樣一個新話題,並更新字 - 話題計數,如下所示:使用Python實現主題模型(numpy)
for m, doc in enumerate(docs): #m: doc id
for n, t in enumerate(doc): #n: id of word inside document, t: id of the word globally
# discount counts for word t with associated topic z
z = z_m_n[m][n]
n_m_z[m][z] -= 1
n_z_t[z, t] -= 1
n_z[z] -= 1
n_m[m] -= 1
# sample new topic for multinomial
p_z_left = (n_z_t[:, t] + beta)/(n_z + V * beta)
p_z_right = (n_m_z[m] + alpha)/(n_m[m] + alpha * K)
p_z = p_z_left * p_z_right
p_z /= numpy.sum(p_z)
new_z = numpy.random.multinomial(1, p_z).argmax()
# set z as the new topic and increment counts
z_m_n[m][n] = new_z
n_m_z[m][new_z] += 1
n_z_t[new_z, t] += 1
n_z[new_z] += 1
n_m[m] += 1
在上面的代碼中,我們用多項式scipy函數對新的(單個)z進行了採樣。
現在,我想實現一個聯合情緒主題模型this paper。現在,我需要保持跟蹤所需要的計數以下結構:
3D matrix containing # occurrences for a word for each topic, for each sentiment
3D matrix containing # occurrences for a topic, for each sentiment, for each document
2D matrix containing # occurrences for a topic, for each sentiment
2D matrix containing # occurrences for a sentiment for each document
現在問題來了:在這個吉布斯採樣器,爲一個文件既是一個新的話題和情緒標籤是在看到每個字現在從條件後驗樣本中抽取(本文的第4頁公式5)。 現在我怎樣才能在Python中「採樣這兩個值」?
在此先感謝...
第一個'for'循環做了什麼?似乎所有在第一個「for」中完成的工作在第二個工作上都沒有完成。 – Netzsooc