最近爬取了一些国外的图片,由于标签都是英文,对文本检索不友好,所以就搞了这个单词翻译工具;很多推荐算法在计算物品与物品相似距离时经常用到同现矩阵,那么举一反三 该算法是否同样可以应用在求解中英单词相似距离上呢?
算法背景
同现矩阵计算公式

- 通过案例说明
N(i)与N(j)分别表示喜欢 i 物品的人数与喜欢 j 物品的人数,上述公式大致意思是求解喜欢物品 i 的人中又同时喜欢物品 j 的占比是多少,比值越大越能说明两个物品的关联度高,那么当其它用户去购买物品 i 时将在很大程度上喜欢物品 j ;不过需要注意的时如果物品 j 是一个热门物品,那么很多人都会喜欢物品 j,极端情况下所有喜欢物品 i 的用户都喜欢物品 j , 那么计算出的物品 i 与物品 j 就是高度相似的,为了避免热门物品的影响,在分母上对热门物品进行了惩罚,当N(j)很大时,相识度就会很低。
另外该方式还有另一个优势,那就是在计算相似度时不需要额外收集评分数据
基于python实现
- 数据处理
import re
# import jieba
import unicodedata
from LAC import LAC
lac = LAC(mode='seg')
def unicode_to_ascii(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def preprocess_eng(w):
w = unicode_to_ascii(w.lower().strip())
# creating a space between a word and the punctuation following it
# eg: "he is a boy." => "he is a boy ."
# Reference:- https://stackoverflow.com/questions/3645931/
# python-padding-punctuation-with-white-spaces-keeping-punctuation
# w = re.sub(r"([?.!,])", r" \1 ", w)
w = re.sub(r"([?.!,])", r" ", w)
# replace several spaces with one space
w = re.sub(r'[" "]+', " ", w)
# replacing everything with space except (a-z, A-Z, ".", "?", "!", ",")
w = re.sub(r"[^a-zA-Z?.!,]+", " ", w)
w = w.rstrip().strip()
# adding a start and an end token to the sentence
# so that the model know when to start and stop predicting.
# w = '<start> ' + w + ' <end>'
return w.split(' ')
def preprocess_chinese(w):
w = unicode_to_ascii(w.lower().strip())
w = re.sub(r'[" "]+', "", w)
w = w.rstrip().strip()
# w = " ".join(list(w)) # add the space between words
# w = '<start> ' + w + ' <end>'
return list(lac.run(w))
input_texts = open('D:/Download/英中机器文本翻译/ai_challenger_translation_train_20170904/translation_train_data_20170904/train.en', 'r', encoding='UTF-8').read().splitlines()
target_texts = open('D:/Download/英中机器文本翻译/ai_challenger_translation_train_20170904/translation_train_data_20170904/train.zh', 'r', encoding='UTF-8').read().splitlines()
input_texts_d = []
target_texts_d = []
i = 1
for it, tt in zip(input_texts, target_texts):
input_texts_d.append(preprocess_eng(it))
target_texts_d.append(preprocess_chinese(tt))
- 计算相似性
mydic = {}
kvdic = {}
for it_ks, tt_ks in zip(input_texts_d, target_texts_d):
for en_k in it_ks:
en_v = {}
if en_k in mydic:
en_v = mydic.get(en_k)
for zh_k in tt_ks:
if zh_k in en_v:
en_v[zh_k] += 1
else:
en_v[zh_k] = 1
mydic[en_k] = en_v
if en_k in kvdic:
kvdic[en_k] += 1
else:
kvdic[en_k] = 1
for zh_k in tt_ks:
if zh_k in kvdic:
kvdic[zh_k] += 1
else:
kvdic[zh_k] = 1
res = {}
for k, v in mydic.items():
zh_dic = {}
for zh, cn in v.items():
zh_dic[zh] = round(cn/(kvdic[zh]*kvdic[k])**0.5, 5)
res[k] = sorted(zh_dic.items(), key= lambda kv: kv[1], reverse=True)[:5]
效果展示


写在最后
现实生活中对一件物品或商品进行描述时往往会有很多词汇和短语,如 “红薯” 和 “地瓜” ;大家可以尝试使用上面算法来挖掘内容中的同义词...
网友评论