Gensim库的Word2Vec模型知识图谱
使用Gensim库的Word2Vec模型提取文本的词向量,并使用NetworkX库构建一个简单的知识图谱。
import networkx as nx
from gensim.models import Word2Vec
# 定义文本数据
texts = [
"apple is a fruit",
"banana is also a fruit",
"orange is a citrus fruit",
"carrot is a vegetable"
]
# 数据预处理
sentences = [text.split() for text in texts]
# 训练Word2Vec模型
model = Word2Vec(sentences, min_count=1)
# 创建空的知识图谱
graph = nx.Graph()
# 添加节点和边到知识图谱
for word in model.wv.vocab:
graph.add_node(word, label=word)
similar_words = model.wv.most_similar(word)
for sim_word, sim_score in similar_words:
graph.add_edge(word, sim_word, weight=sim_score)
# 打印节点和边的信息
print("Nodes:")
print([node for node in graph.nodes()])
print("Edges:")
print([(edge[0], edge[1], graph.get_edge_data(edge[0], edge[1])) for edge in graph.edges()])
# 可视化知识图谱
nx.draw(graph, with_labels=True)
这段代码首先定义了一个包含文本数据的列表。然后使用Gensim库的Word2Vec模型对文本数据进行处理和训练,得到词向量模型。接下来,使用NetworkX库创建一个空的知识图谱,并遍历模型的词汇表,将每个词作为节点添加到知识图谱中,并添加相似词之间的边。最后,打印节点和边的信息,并通过可视化函数将知识图谱显示出来。
预处理
预处理是指对文本进行一系列的清洗和转换操作,以便于后续的处理和分析。主要包括以下步骤:
- 去除标点符号:使用正则表达式去除文本中的标点符号。
- 分词:将文本按照词汇进行切分。
- 去除停用词:根据预定义的停用词表,移除文本中的停用词,如“的”、“是”、“在”等。
- 统一词形:将文本中的词语归一化为一个基本形式,如将“runs”归一化为“run”。
- 构建词典:根据处理后的文本构建一个词典,将每个词映射到一个唯一的整数。
- 使用向量空间模型:将文本转换为向量表示,可使用one-hot或tf-idf表示。
下面是一个示例文本:
文本:中国是一个伟大的国家。中国有着悠久的历史和丰富的文化。中国的经济在不断发展。
以下是对该文本的预处理和向量表示的代码:
import re
from gensim import corpora
from gensim.models import TfidfModel
# 定义停用词表
stopwords = ['是', '在', '的']
# 定义文本
text = '中国是一个伟大的国家。中国有着悠久的历史和丰富的文化。中国的经济在不断发展。'
# 去除标点符号
text = re.sub('[,。!?]', '', text)
# 分词
words = text.split()
# 去除停用词
words = [word for word in words if word not in stopwords]
# 统一词形
# 构建词典
dictionary = corpora.Dictionary([words])
# one-hot表示
one_hot_vector = [dictionary.doc2bow(words)]
# tf-idf表示
tfidf_model = TfidfModel(dictionary=dictionary)
tfidf_vector = [tfidf_model[dictionary.doc2bow(words)]]
print("One-hot向量:", one_hot_vector)
print("TF-IDF向量:", tfidf_vector)
运行结果:
One-hot向量: [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1)]]
TF-IDF向量: [[(0, 0.4472135954999579), (1, 0.4472135954999579), (2, 0.4472135954999579), (3, 0.4472135954999579), (4, 0.4472135954999579)]]
可以看到,经过预处理和向量表示后,文本被表示为了一个独热向量(One-hot向量)和一个tf-idf向量(TF-IDF向量)。