MCPcopy Create free account
hub / github.com/Dod-o/Statistical-Learning-Method_Code / load_data

Function load_data

LDA/LDA.py:30–82  ·  view source on GitHub ↗

INPUT: file - (str) 数据文件的路径 K - (int) 设定的话题数 OUTPUT: org_topics - (list) 原始话题标签列表 text - (list) 文本列表 words - (list) 单词列表 alpha - (list) 话题概率分布,模型超参数 beta - (list) 单词概率分布,模型超参数

(file, K)

Source from the content-addressed store, hash-verified

28
29#定义加载数据的函数
30def load_data(file, K):
31 '''
32 INPUT:
33 file - (str) 数据文件的路径
34 K - (int) 设定的话题数
35
36 OUTPUT:
37 org_topics - (list) 原始话题标签列表
38 text - (list) 文本列表
39 words - (list) 单词列表
40 alpha - (list) 话题概率分布,模型超参数
41 beta - (list) 单词概率分布,模型超参数
42
43 '''
44 df = pd.read_csv(file) #读取文件
45 org_topics = df['category'].unique().tolist() #保存文本原始的话题标签
46 M = df.shape[0] #文本数
47 alpha = np.zeros(K) #alpha是LDA模型的一个超参数,是对话题概率的预估计,这里取文本数据中各话题的比例作为alpha值,实际可以通过模型训练得到
48 beta = np.zeros(1000) #beta是LDA模型的另一个超参数,是词汇表中单词的概率分布,这里取各单词在所有文本中的比例作为beta值,实际也可以通过模型训练得到
49 #计算各话题的比例作为alpha值
50 for k, topic in enumerate(org_topics):
51 alpha[k] = df[df['category'] == topic].shape[0] / M
52 df.drop('category', axis=1, inplace=True)
53 n = df.shape[0] #n为文本数量
54 text = []
55 words = []
56 for i in df['text'].values:
57 t = i.translate(str.maketrans('', '', string.punctuation)) #去除文本中的标点符号
58 t = [j for j in t.split() if j not in stopwords.words('english')] #去除文本中的停止词
59 t = [j for j in t if len(j) > 3] #长度小于等于3的单词大多是无意义的,直接去除
60 text.append(t) #将处理后的文本保存到文本列表中
61 words.extend(set(t)) #将文本中所包含的单词保存到单词列表中
62 words = list(set(words)) #去除单词列表中的重复单词
63 words_cnt = np.zeros(len(words)) #用来保存单词的出现频次
64 #循环计算words列表中各单词出现的词频
65 for i in range(len(text)):
66 t = text[i] #取出第i条文本
67 for w in t:
68 ind = words.index(w) #取出第i条文本中的第t个单词在单词列表中的索引
69 words_cnt[ind] += 1 #对应位置的单词出现频次加一
70 sort_inds = np.argsort(words_cnt)[::-1] #对单词出现频次降序排列后取出其索引值
71 words = [words[ind] for ind in sort_inds[:1000]] #将出现频次前1000的单词保存到words列表
72 #去除文本text中不在词汇表words中的单词
73 for i in range(len(text)):
74 t = []
75 for w in text[i]:
76 if w in words:
77 ind = words.index(w)
78 t.append(w)
79 beta[ind] += 1 #统计各单词在文本中的出现频次
80 text[i] = t
81 beta /= np.sum(beta) #除以文本的总单词数得到各单词所占比例,作为beta值
82 return org_topics, text, words, alpha, beta
83
84
85#定义潜在狄利克雷分配函数,采用收缩的吉布斯抽样算法估计模型的参数theta和phi

Callers 1

LDA.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected