Skip to content

Commit e5fdf1c

Browse files
authored
Add LSA.py
1 parent 1c4ad2c commit e5fdf1c

1 file changed

Lines changed: 123 additions & 0 deletions

File tree

LSA/LSA.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
#coding=utf-8
2+
#Author:Harold
3+
#Date:2021-1-27
4+
#Email:zenghr_zero@163.com
5+
6+
'''
7+
数据集:bbc_text
8+
数据集数量:2225
9+
-----------------------------
10+
运行结果:
11+
话题数:5
12+
原始话题:'tech', 'business', 'sport', 'entertainment', 'politics'
13+
生成话题:
14+
1:'said people would music blair government best year film howard'
15+
2:'said would labour party people last could years kilroysilk show'
16+
3:'music microsoft year best urban industry record software email think'
17+
4:'wales first games lord government play house public control prime'
18+
5:'said mobile england people phone dallaglio rugby blair election would'
19+
运行时长:212.96s
20+
'''
21+
22+
import numpy as np
23+
import pandas as pd
24+
import string
25+
from nltk.corpus import stopwords
26+
import time
27+
28+
29+
#定义加载数据的函数
30+
def load_data(file):
31+
'''
32+
INPUT:
33+
file - (str) 数据文件的路径
34+
35+
OUTPUT:
36+
org_topics - (list) 原始话题标签列表
37+
text - (list) 文本列表
38+
words - (list) 单词列表
39+
40+
'''
41+
df = pd.read_csv(file) #读取文件
42+
org_topics = df['category'].unique().tolist() #保存文本原始的话题标签
43+
df.drop('category', axis=1, inplace=True)
44+
n = df.shape[0] #n为文本数量
45+
text = []
46+
words = []
47+
for i in df['text'].values:
48+
t = i.translate(str.maketrans('', '', string.punctuation)) #去除文本中的标点符号
49+
t = [j for j in t.split() if j not in stopwords.words('english')] #去除文本中的停止词
50+
t = [j for j in t if len(j) > 3] #长度小于等于3的单词大多是无意义的,直接去除
51+
text.append(t) #将处理后的文本保存到文本列表中
52+
words.extend(set(t)) #将文本中所包含的单词保存到单词列表中
53+
words = list(set(words)) #去除单词列表中的重复单词
54+
return org_topics, text, words
55+
56+
57+
#定义构建单词-文本矩阵的函数,这里矩阵的每一项表示单词在文本中的出现频次,也可以用TF-IDF来表示
58+
def frequency_counter(text, words):
59+
'''
60+
INPUT:
61+
text - (list) 文本列表
62+
words - (list) 单词列表
63+
64+
OUTPUT:
65+
X - (array) 单词-文本矩阵
66+
67+
'''
68+
X = np.zeros((len(words), len(text))) #定义m*n的矩阵,其中m为单词列表中的单词个数,n为文本个数
69+
for i in range(len(text)):
70+
t = text[i] #读取文本列表中的第i条文本
71+
for w in t:
72+
ind = words.index(w) #取出第i条文本中的第t个单词在单词列表中的索引
73+
X[ind][i] += 1 #对应位置的单词出现频次加一
74+
return X
75+
76+
77+
#定义潜在语义分析函数
78+
def do_lsa(X, k, words):
79+
'''
80+
INPUT:
81+
X - (array) 单词-文本矩阵
82+
k - (int) 设定的话题数
83+
words - (list) 单词列表
84+
85+
OUTPUT:
86+
topics - (list) 生成的话题列表
87+
88+
'''
89+
w, v = np.linalg.eig(np.matmul(X.T, X)) #计算Sx的特征值和特征向量,其中Sx=X.T*X,Sx的特征值w即为X的奇异值分解的奇异值,v即为对应的奇异向量
90+
sort_inds = np.argsort(w)[::-1] #对特征值降序排列后取出对应的索引值
91+
w = np.sort(w)[::-1] #对特征值降序排列
92+
V_T = [] #用来保存矩阵V的转置
93+
for ind in sort_inds:
94+
V_T.append(v[ind]/np.linalg.norm(v[ind])) #将降序排列后各特征值对应的特征向量单位化后保存到V_T中
95+
V_T = np.array(V_T) #将V_T转换为数组,方便之后的操作
96+
Sigma = np.diag(np.sqrt(w)) #将特征值数组w转换为对角矩阵,即得到SVD分解中的Sigma
97+
U = np.zeros((len(words), k)) #用来保存SVD分解中的矩阵U
98+
for i in range(k):
99+
ui = np.matmul(X, V_T.T[:, i]) / Sigma[i][i] #计算矩阵U的第i个列向量
100+
U[:, i] = ui #保存到矩阵U中
101+
topics = [] #用来保存k个话题
102+
for i in range(k):
103+
inds = np.argsort(U[:, i])[::-1] #U的每个列向量表示一个话题向量,话题向量的长度为m,其中每个值占向量值之和的比重表示对应单词在当前话题中所占的比重,这里对第i个话题向量的值降序排列后取出对应的索引值
104+
topic = [] #用来保存第i个话题
105+
for j in range(10):
106+
topic.append(words[inds[j]]) #根据索引inds取出当前话题中比重最大的10个单词作为第i个话题
107+
topics.append(' '.join(topic)) #保存话题i
108+
return topics
109+
110+
111+
if __name__ == "__main__":
112+
org_topics, text, words = load_data('bbc_text.csv') #加载数据
113+
print('Original Topics:')
114+
print(org_topics) #打印原始的话题标签列表
115+
start = time.time() #保存开始时间
116+
X = frequency_counter(text, words) #构建单词-文本矩阵
117+
k = 5 #设定话题数为5
118+
topics = do_lsa(X, k, words) #进行潜在语义分析
119+
print('Generated Topics:')
120+
for i in range(k):
121+
print('Topic {}: {}'.format(i+1, topics[i])) #打印分析后得到的每个话题
122+
end = time.time() #保存结束时间
123+
print('Time:', end-start)

0 commit comments

Comments
 (0)