word2vec中文词向量结合PCA算法在二维空间下可视化分析-代码
2023-06-13 09:16:13 时间
记录下
%matplotlib inline
from jupyterthemes import jtplot
jtplot.style(theme='grade3') #选择一个绘图主题
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import PCA
import adjustText
from gensim.models.keyedvectors import KeyedVectors
word_vectors = KeyedVectors.load_word2vec_format(\
'C:/Users/yue/Desktop/1.bin', \
binary = False, limit = 1000000)
def plot_2d_representation_of_words(
word_list,
word_vectors,
flip_x_axis = False,
flip_y_axis = False,
label_x_axis = "x",
label_y_axis = "y",
label_label = "fruit"):
pca = PCA(n_components = 2)
word_plus_coordinates=[]
for word in word_list:
current_row = []
current_row.append(word)
current_row.extend(word_vectors[word])
word_plus_coordinates.append(current_row)
word_plus_coordinates = pd.DataFrame(word_plus_coordinates)
coordinates_2d = pca.fit_transform(
word_plus_coordinates.iloc[:,1:300])
coordinates_2d = pd.DataFrame(
coordinates_2d, columns=[label_x_axis, label_y_axis])
coordinates_2d[label_label] = word_plus_coordinates.iloc[:,0]
if flip_x_axis:
coordinates_2d[label_x_axis] = \
coordinates_2d[label_x_axis] * (-1)
if flip_y_axis:
coordinates_2d[label_y_axis] = \
coordinates_2d[label_y_axis] * (-1)
plt.figure(figsize = (5, 3))
p1=sns.scatterplot(
data=coordinates_2d, x=label_x_axis, y=label_y_axis)
x = coordinates_2d[label_x_axis]
y = coordinates_2d[label_y_axis]
label = coordinates_2d[label_label]
texts = [plt.text(x[i], y[i], label[i]) for i in range(len(x))]
adjustText.adjust_text(texts)
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['STZhongsong'] # 指定默认字体:解决plot不能显示中文问题
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
#fruits = ['apple','orange','banana','lemon','car','tram','boat','bicycle','cherry','mango','grape','durian','watermelon','train','motorbike','ship', 'peach','pear','pomegranate','strawberry','bike','bus','truck','subway','airplane']
fruits = ['苹果', '自行车', '香蕉', '汽车', '人']
plot_2d_representation_of_words(
word_list = fruits,
word_vectors = word_vectors,
flip_y_axis = True)
这是在jupyter notebook运行的,使用的是腾讯AI Lab的中文词向量,下载压缩包下来解压,最里面的txt改成bin文件
可以看到寓意之间的关系
相关文章
- NSGA2 算法MATLAB完整代码 中文注释详解
- PaddleNLP通用信息抽取技术UIE【一】产业应用实例:信息抽取{实体关系抽取、中文分词、精准实体标。情感分析等}、文本纠错、问答系统、闲聊机器人、定制训练
- 盘点一个JS逆向过程中中文编解码的小案例
- SAP Business ByDesign 中文技术开发资料
- PTA 数据结构与算法题目集(中文) 7-10 公路村村通 (30分) 最小生成树(kruskal算法)
- PTA 数据结构与算法题目集(中文)7-44 基于词频的文件相似度 (30分)
- 字节跳动《算法中文手册》完整版 PDF 开放下载!
- 虚拟机VMware Workstation 17 Pro V17.0.1 中文最新完整版(附永久key+教程) VMware安装教程VMware下载虚拟机VM
- AutoCAD 2023官方中文版,CAD2022安装,AutoCAD 2023 中文激活版
- 关于responseBody注解中文乱码的问题解决详解编程语言
- 解决MySQL中文乱码的方法(mysql中中文乱码)
- MYSQL中文截取:实现中文字符的准确截取技巧(mysql中文截取)
- MySQL 中文全文检索技术指南(mysql中文全文检索)
- MySQL中文版下载:解决数据库问题(mysql中文下载)
- 解决Linux下Oracle中文乱码的正确方法(linux oracle 中文乱码)
- 输入Linux环境下如何实现中文输入(linux环境中文)
- 解开Oracle的中文之谜破解之殇(oracle 中文破解)
- 取得一定长度的内容,处理中文
- js日期转换成中文格式的函数