Similarity Queries for Security Name by Gensim

Introduction of Gensim

Gensim is a free Python library designed to automatically extract semantic topics from documents, as efficiently (computer-wise) and painlessly (human-wise) as possible.

Gensim is designed to process raw, unstructured digital texts (“plain text”). The algorithms in gensim, such as Latent Semantic Analysis, Latent Dirichlet Allocation and Random Projections discover semantic structure of documents by examining statistical co-occurrence patterns of the words within a corpus of training documents. These algorithms are unsupervised, which means no human input is necessary – you only need a corpus of plain text documents.

Once these statistical patterns are found, any plain text documents can be succinctly expressed in the new, semantic representation and queried for topical similarity against other documents.

Flowchart Diagram

(original flowchart diagram, no related diagram in Gensim official website)


2018-05-17 10_53_55-Similarity Queries for Security Name by Gensim - Data Collection Technology - Mo.png

Code Example

Train data sample:
F1234567OX~Undrly Alba (Crus) Gth Prop 2 Life~Undrly Alba (Crus) Gth Prop 2 Life
F7654321OY~Undrly Alba (Crus) Mixed Pen~Undrly Alba (Crus) Mixed Pen
FABCDEF9P0~Undrly Alba (Crus) Nth Am Pen~Undrly Alba (Crus) Nth Am Pen
FFEDCBA9P4~Undrly Alba (Crus) Secure Inc Pen~Undrly Alba (Crus) Secure Inc Pen
F1234567P5~Undrly Alba (Crus) UK Pen~Undrly Alba (Crus) UK Pen
It means: security id~security name~security legal name
The code splits every single line via character '~', and only apply security legal name to construct dictionary and model.

print('Begin read data source')
data_train = []
    for security in open(securitynamepath, encoding='utf-8'):
        if len(security.split('~')) == 3:
            data_train.append([word for word in security.split('~')[2].lower().split()
                   if word not in stoplist])
print('End read data source')

To get similarity of security name, the POC applies tf-idf algorithm to build model.

The sample code is less than 100 lines,
To initial dictionary and model like this,it will spend less than one second to get query result.

import time
from gensim import corpora, models, similarities
from collections import defaultdict
import os
 
dictpath = './data/model/security.dict'
modelpath = './data/model/security.mm'
securitynamepath = './data/security/securityname.txt'
start = time.time()
alltext = [security for security in open(securitynamepath, encoding='utf-8')]
end = time.time()
print('Read security name list cost: ', end - start)
 
def startjob(regeneratemodel=False, usertext='DSP BlackRock FMP Sr 229 51 Mn Dir Gr'):
    if regeneratemodel or (not os.path.exists(dictpath) or not os.path.exists(modelpath)):
        generatemodel()
 
    time_start = time.time()
    print('Load model start')
    load_start = time.time()
    corpus = corpora.MmCorpus(modelpath)
    dictionary = corpora.Dictionary.load(dictpath)
    tfidf_model = models.TfidfModel(corpus)
    index = similarities.SparseMatrixSimilarity(
        tfidf_model[corpus],
        num_features=len(dictionary.keys()))
    load_end = time.time()
    print('Load model cost: ', load_end - load_start)
    print('Load model end')
    ###############By LSI#####################
    # corpus_tfidf = tfidf_model[corpus]
    # dictionary = corpora.Dictionary.load(dictpath)
    # lsi_model = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2)
    # corpus_lsi = lsi_model[corpus_tfidf]
    # corpus_simi_matrix = similarities.MatrixSimilarity(corpus_lsi)
    # 计算一个新的文本与既有文本的相关度
    # test_text = usertext.lower().split()
    # test_bow = dictionary.doc2bow(test_text)
    # test_tfidf = tfidf_model[test_bow]
    # test_lsi = lsi_model[test_tfidf]
    # test_simi = corpus_simi_matrix[test_lsi]
    # test_simi = sorted(enumerate(test_simi), key=lambda item: -item[1])
    ###############By LSI#####################
 
    ###############By tfidf#####################
    print('Query start')
    query_start = time.time()
    test_text = usertext.lower().split()
    doc_test_vec = dictionary.doc2bow(test_text)
    
    test_simi = index[tfidf_model[doc_test_vec]]
    test_simi = sorted(enumerate(test_simi), key=lambda item: -item[1])
    ###############By tfidf#####################
 
    outputlist = [test for test in test_simi if test[1] > 0.3]
    for output in outputlist:
        print(alltext[output[0]], output[1])
        if len(alltext[output[0]].split('~')) == 3 and alltext[output[0]].split('~')[1] == usertext:
            print("Congratulations, you find the right answer!")
            break
    time_end = time.time()
    print('Query cost: ', time_end - query_start)
    print('Totally cost: ', time_end - time_start)
    print('Query end')
 
def generatemodel():
    print('Begin genertate model')
    stoplist = set('for a of the and to in'.split())
    print('Begin read data source')
    data_train = []
    count = 0
    for security in open(securitynamepath, encoding='utf-8'):
        if len(security.split('~')) == 3:
            data_train.append([word for word in security.split('~')[2].lower().split()
                   if word not in stoplist])
        count += 1
        print(count)
    print('End read data source')
    #去除只出现一次的单词,查询security name相似度的需求不需要这个特性
    # frequency = defaultdict(int)
    # for text in data_train:
    #     for token in text:
    #         frequency[token] += 1
    # data_train = [[token for token in text if frequency[token] > 1]
    #               for text in data_train]
    print(data_train)
    dictionary = corpora.Dictionary(data_train)
    dictionary.save(dictpath)
    corpus = [dictionary.doc2bow(text) for text in data_train]
    corpora.MmCorpus.serialize(modelpath, corpus)
    print('End genertate model')
 
if __name__ == '__main__':
    startjob(False, u'Undrly Alba LASPEN Property')

Output Analyzation

The run console output is:


2018-05-11 11_22_06-similarsecurity - [D__GIT_researchinit_similarsecurity] - ..._main.py - PyCharm .png

The information of output:

"Using TensorFlow backend": does it means Gensim using TensorFlow? But there is no official description about it

There is time cost information in output list:

Load security name cost (amount: 599214 records): 0.26 second

Load dictionary and model: 8.94 seconds

Similarity query for test text: 19.87 seconds

User test text:

Undrly Alba LASPEN Property

Similarity query result:

The result from gensim is key:value structure: Index:Probability, such as: 10:0.9348, means the probalility of the security name which index is 10, is 0.9348

To be easy to get full information, output security id, security name with abbreviation and security legal name by result index.

The result sorts in descending order by probility, such as:

F1234567PM~Undrly Alba LASPEN Property PP~Undrly Alba LASPEN Property PP
0.9348221
F7654321PI~Undrly Alba LASPEN UK Equity PP~Undrly Alba LASPEN UK Equity PP
0.83671427

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,102评论 0 10
  • 文|逆旅人 人生路上,步履不停。总有那么一点来不及。——《步履不停》是枝裕和 如果一定要有那么一点“来不及”存在,...
    逆旅人阅读 388评论 0 0
  • 多长时间了 还没有遇见你 没关系 我还可以再继续等下去 也许 我躺着绿野上熟睡的时候 你策马而过 大地只留有马蹄的...
    谎言之躯阅读 220评论 2 1
  • 今天有点事,心情乱了,画自然也乱了。
    刘家姥姥阅读 169评论 1 2