sas文本挖掘案例:如何使用SAS计算Word Mover的距离

简介: sas文本挖掘案例:如何使用SAS计算Word Mover的距离

Word Mover的距离(WMD)是用于衡量两个文档之间差异的距离度量,它在文本分析中的应用是由华盛顿大学的一个研究小组在2015年引入的。


Word Mover距离的定义

WMD是两个文档之间的距离,作为将所有单词从一个文档移动到另一个文档所需的最小(加权)累积成本。通过解决以下线性程序问题来计算距离。


T ij表示文档d中的单词i在文档d'中移动到单词j的多少;

C(1; j)的表示从文件d中的单词我到文件d '中的单词J‘行进’的费用; 这里的成本是word2vec嵌入空间中的两个词'欧几里德距离;

如果字我出现Ç我在文档d次,我们记


WMD是Word Mover距离度量(EMD)的一个特例,这是一个众所周知的问题。


如何用SAS计算Word Mover的距离?


SAS / OR是解决问题的工具。图1显示了一个带有四个节点和节点之间距离的传输示例,我从这个Earth Mover的距离文档中复制了这些节点。目标是找出从{x1 ,x2}到{y1,y2}的最小流量。现在让我们看看如何使用SAS / OR解决这个运输问题。

节点的权重和节点之间的距离如下。

datax_set;input_node_ $ _sd_;datalines;
x10.74x20.26;datay_set;
input_node_ $ _sd_;
datalines;
y10.23y20.51;
dataarcdata;input_tail_ $ _head_ $ _cost_;datalines;
x1 y1155.7x1 y2252.3x2 y1292.9x2 y2198.2;proc optmodel;
setxNODES;
num w{xNODES};
setyNODES;
num u{yNODES};set<str,str> ARCS;
num arcCost{ARCS}; 
readdatax_setintoxNODES=[_node_]w=_sd_;
readdatay_setintoyNODES=[_node_]u=_sd_;
readdataarcdataintoARCS=[_tail_ _head_]arcCost=_cost_;
varflow{<i,j>inARCS}>=0;
impvar sumY =sum{jinyNODES}u[j];
minobj =(sum{<i,j>inARCS}arcCost[i,j]* flow[i,j])/sumY;
con con_y{jinyNODES}:sum{<i,(j)>inARCS}flow[i,j]= u[j];
con con_x{iinxNODES}:sum{<(i),j>inARCS}flow[i,j]<= w[i];
 solve with lp / algorithm=ns scale=none logfreq=1;
 print flow;
 quit;


图-1运输问题

SAS / OR的解决方案如表-1所示,EMD是目标值:203.26756757。



表-1 EMD用SAS / OR计算

我用SAS / OR表2得到的流量数据显示如下,与上述地球移动器距离文档中公布的图表相同。


表-2 SAS / OR的流量数据


图-2运输问题流程图


如何用SAS计算Word Mover的距离

本文从Word嵌入到文档距离,通过删除WMD的第二个约束来减少计算,提出了一个名为放松的Word Mover距离(RWMD)的新度量。由于我们需要读取文字嵌入数据,因此我将向您展示如何使用SAS Viya计算两个文档的RWMD。

/* start CAS server */cas casauto host="host.example.com"port=5570;libnamesascas1 cas;/* load documents into CAS */datasascas1.documents;infiledatalines delimiter='|'missover;lengthtext varchar(300);inputtext$ did;datalines;Obama speaks to the mediainIllinois.|1The President greets the pressinChicago.|2;run;/* create stop list*/datasascas1.stopList;infiledatalines missover;lengthterm $20;inputterm$;datalines;thetoin;run;/* load word embedding model */proc cas;loadtable path='datasources/glove_100d_tab_clean.txt'caslib="CASTestTmp"importOptions={fileType="delimited",delimiter='\t',getNames=True,guessRows=2.0,varChars=True}casOut={name='glove'replace=True};run;quit;%macrocalculateRWMD(textDS=documents,documentID=did,text=text,language=English,stopList=stopList,word2VectDS=glove,doc1_id=1,doc2_id=2);/* text parsing and aggregation */proc cas;textParse.tpParse/table={name="&textDS",where="&documentID=&doc1_id or &documentID=&doc2_id"}docId="&documentID",language="&language",stemming=False,nounGroups=False,tagging=False,offset={name="outpos",replace=1},text="&text";run; textparse.tpaccumulate/parent={name="outparent1",replace=1}language="&language",offset='outpos',stopList={name="&stoplist"},terms={name="outterms1",replace=1},child={name="outchild1",replace=1},reduce=1,cellweight='none',termWeight='none';run;quit;/* terms of the two test documents */proc cas;loadactionset"fedsql";execdirect casout={name="doc_terms",replace=true}query="

select outparent1.*,_term_

from outparent1

left join outterms1

on outparent1._termnum_ = outterms1._termnum_

where _Document_=&doc1_id or _Document_=&doc2_id;

";run;quit;/* term vectors and counts of the two test documents */proc cas;loadactionset"fedsql";execdirect casout={name="doc1_termvects",replace=true}query="

select word2vect.*

from &word2VectDS word2vect, doc_terms

where _Document_=&doc2_id and lowcase(term) = _term_;

";run; execdirect casout={name="doc1_terms",replace=true}query="

select doc_terms.*

from &word2VectDS, doc_terms

where _Document_=&doc2_id and lowcase(term) = _term_;

";run; simple.groupBy /table={name="doc1_terms"}inputs={"_Term_","_Count_"}aggregator="n"casout={name="doc1_termcount",replace=true};run;quit;proc cas;loadactionset"fedsql";execdirect casout={name="doc2_termvects",replace=true}query="

select word2vect.*

from &word2VectDS word2vect, doc_terms

where _Document_=&doc1_id and lowcase(term) = _term_;

";run; execdirect casout={name="doc2_terms",replace=true}query="

select doc_terms.*

from &word2VectDS, doc_terms

where _Document_=&doc1_id and lowcase(term) = _term_;

";run; simple.groupBy /table={name="doc2_terms"}inputs={"_Term_","_Count_"}aggregator="n"casout={name="doc2_termcount",replace=true};run;quit;/* calculate Euclidean distance between words */datadoc1_termvects;setsascas1.doc1_termvects;run;datadoc2_termvects;setsascas1.doc2_termvects;run;proc iml;use doc1_termvects;read allvar_char_intolterm;read allvar_num_intox;closedoc1_termvects; use doc2_termvects;read allvar_char_intorterm;read allvar_num_intoy;closedoc2_termvects; d = distance(x,y); lobs=nrow(lterm);robs=nrow(rterm);d_out=j(lobs*robs, 3, ' ');doi=1to lobs;doj=1to robs;d_out[(i-1)*robs+j,1]=lterm[i];d_out[(i-1)*robs+j,2]=rterm[j];d_out[(i-1)*robs+j,3]=cats(d[i,j]);end;end;createdistancefromd_out;appendfromd_out;closedistance;run;quit;/* calculate RWMD between documents */datax_set;setsascas1.doc1_termcount;rename_term_=_node_;_weight_=_count_;run;datay_set;setsascas1.doc2_termcount;rename_term_=_node_;_weight_=_count_;run;dataarcdata;setdistance;renamecol1=_tail_;renamecol2=_head_;length_cost_8;_cost_= col3;run;proc optmodel;setxNODES;num w{xNODES};setyNODES;num u{yNODES};set<str,str> ARCS;num arcCost{ARCS}; readdatax_setintoxNODES=[_node_]w=_weight_;readdatay_setintoyNODES=[_node_]u=_weight_;readdataarcdataintoARCS=[_tail_ _head_]arcCost=_cost_;varflow{<i,j>inARCS}>=0;impvar sumY =sum{jinyNODES}u[j];minobj =(sum{<i,j>inARCS}arcCost[i,j]* flow[i,j])/sumY;con con_y{jinyNODES}:sum{<i,(j)>inARCS}flow[i,j]= u[j];/* con con_x {i in xNODES}: sum {<(i),j> in ARCS} flow[i,j] <= w[i];*/solve with lp / algorithm=ns scale=none logfreq=1;callsymput('obj', strip(put(obj,best.)));createdataflowDatafrom[i j]={<i, j="">inARCS: flow[i,j].sol >0}col("cost")=arcCost[i,j]col("flowweight")=flow[i,j].sol;run;quit;%putRWMD=&obj;%mendcalculateRWMD; %calculateRWMD(textDS=documents,documentID=did,text=text,language=English,stopList=stopList,word2VectDS=glove,doc1_id=1,doc2_id=2);

<str,str>

<str,str>proc printdata=flowdata;run;quit;



WMD方法不仅可以测量文档的相似性,还可以通过可视化流数据来解释为什么这两个文档是相似的。

 

相关文章
|
12月前
|
监控 搜索推荐 算法
2026新风向丨专业1688运营必须精通的5个焕新实战操作!
本文详解1688店铺权重提升五大核心:新灯塔分维护、新品打标策略、买家行为分析、收藏加购优化与转化率提升,结合数据运营与实操步骤,助力商家系统化提效。
|
8月前
|
Python
Python开发飞机大战全教程(四)
教程来源 https://bncne.cn 本教程基于Pygame实现经典“飞机大战”游戏,含玩家控制、子弹射击、敌机生成与碰撞检测等核心功能。代码结构清晰,支持键盘操作(方向键移动、空格射击、R键重开),并提供图像替换、爆炸动画、滚动星空背景及动态难度提升等扩展方案,助你从零掌握游戏开发全流程。
|
人工智能 算法 搜索推荐
电商API的“AI革命”:全球万亿市场如何被算法重新定义?
AI+电商API正引领智能商业变革,通过智能推荐、动态定价与自动化运营三大核心场景,大幅提升转化率、利润率与用户体验。2025年,75%电商API将具备个性化能力,90%业务实现智能决策,AI与API的深度融合将成为未来电商竞争的关键基石。
|
监控 前端开发 安全
74.8K star!这个开源图标库让界面设计效率提升10倍!
Font Awesome 是全球最受欢迎的图标库和工具包,提供超过2000个免费图标和7000+专业图标,支持网页、桌面应用、移动端等多平台使用。开发者只需几行代码就能为项目添加精美矢量图标,设计师可直接下载SVG进行二次创作。
788 4
|
存储 运维 Kubernetes
Kubernetes HPA 的三个误区与避坑指南
云计算带来的优势之一便是弹性能力,云原生场景下Kubernetes提供了水平弹性扩容能力(HPA),让应用可以随着实时指标进行扩/缩。然而HPA的实际工作情况可能和我们直观预想的情况是不一样的,这里面存在一些认知误区。本文总结了一下 EDAS 用户在使用 HPA 时常遇到的三个认知误区
3368 126
Kubernetes HPA 的三个误区与避坑指南
|
安全 Java API
【Java性能优化】Map.merge()方法:告别繁琐判空,3行代码搞定统计累加!
在日常开发中,我们经常需要对Map中的值进行累加统计。}else{代码冗长,重复调用get()方法需要显式处理null值非原子操作,多线程下不安全今天要介绍的方法,可以让你用一行代码优雅解决所有这些问题!方法的基本用法和优势与传统写法的对比分析多线程安全版本的实现Stream API的终极优化方案底层实现原理和性能优化建议一句话总结是Java 8为我们提供的Map操作利器,能让你的统计代码更简洁、更安全、更高效!// 合并两个列表});简单累加。
1342 0
|
传感器 数据中心
|
前端开发 数据可视化 API
Python实现智能家居设备的统一控制平台
【10月更文挑战第6天】 Python实现智能家居设备的统一控制平台
1148 11
|
前端开发 UED
长轮询(Long Polling)的缺点有哪些?
【10月更文挑战第8天】
775 2