计算BTM模型一致性的代码
时间: 2024-05-13 22:15:12 浏览: 130
计算BTM模型一致性的代码如下:
```python
from collections import Counter
import numpy as np
def get_cosine_sim(mat):
"""
计算词向量的余弦相似度矩阵
:param mat: 词向量矩阵
:return: 余弦相似度矩阵
"""
cos_mat = mat.dot(mat.T)
norms = np.linalg.norm(mat, axis=1)
norms[norms == 0] = 1e-8
norm_mat = np.outer(norms, norms)
return cos_mat / norm_mat
def get_topic_coherence(beta, doc_term_mat, vocab, top_n=10):
"""
计算主题一致性
:param beta: 主题-词分布矩阵
:param doc_term_mat: 文档-词矩阵
:param vocab: 词汇表
:param top_n: 取每个主题前top_n个词
:return: 主题一致性值
"""
topic_coherence = []
for k in range(beta.shape[0]):
top_words = beta[k].argsort()[:-top_n:-1]
word_pairs = []
for i in range(len(top_words)):
for j in range(i+1, len(top_words)):
word_pairs.append((vocab[top_words[i]], vocab[top_words[j]]))
word_counts = Counter(vocab)
window_size = 3
co_occur = {}
for doc in doc_term_mat:
doc_len = len(doc)
for i in range(doc_len):
word_i = vocab[doc[i]]
if word_i in top_words:
for j in range(max(0, i - window_size), min(doc_len, i + window_size + 1)):
if j != i:
word_j = vocab[doc[j]]
if word_j in top_words:
if (word_i, word_j) in co_occur:
co_occur[(word_i, word_j)] += 1
else:
co_occur[(word_i, word_j)] = 1
coherence = []
for word_pair in word_pairs:
w1, w2 = word_pair
co_count = co_occur.get((w1, w2), 0)
w1_count = word_counts[w1]
w2_count = word_counts[w2]
coherence.append(np.log((co_count + 1) / w1_count))
coherence.append(np.log((co_count + 1) / w2_count))
topic_coherence.append(np.mean(coherence))
return np.mean(topic_coherence)
# 示例代码
beta = np.array([[0.1, 0.2, 0.3, 0.4],
[0.4, 0.3, 0.2, 0.1],
[0.2, 0.1, 0.4, 0.3],
[0.3, 0.4, 0.1, 0.2]])
doc_term_mat = np.array([[0, 1, 2, 3],
[1, 2, 3, 0],
[2, 3, 0, 1],
[3, 0, 1, 2]])
vocab = ['apple', 'banana', 'cat', 'dog']
cos_sim = get_cosine_sim(beta)
print('主题余弦相似度矩阵:')
print(cos_sim)
topic_coherence = get_topic_coherence(beta, doc_term_mat, vocab)
print('主题一致性值:')
print(topic_coherence)
```
在这个示例代码中,我们使用了一个由4个主题和4个单词组成的语料库,计算了主题的余弦相似度矩阵和主题一致性值。在实际应用中,我们需要将上面的示例代码替换成我们的BTM模型和语料库,然后就可以计算模型的一致性了。
阅读全文