Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tf idf匹配列表与列表,而不是一个列表_Python_String Matching_Tf Idf - Fatal编程技术网

Python Tf idf匹配列表与列表,而不是一个列表

Python Tf idf匹配列表与列表,而不是一个列表,python,string-matching,tf-idf,Python,String Matching,Tf Idf,我正在试验tf idf匹配。我遵循了文章中的教程。我想知道我是否可以将一个输入列表与另一个已处理数据列表进行匹配,然后让这个脚本将输出作为输入列表中每个项目的现有第二个列表的潜在匹配项返回 我希望你们中的一个能帮我找到正确的方向!谢谢 import pandas as pd pd.set_option('display.max_colwidth', -1) names = pd.read_csv('sample-data/descriptions_1.csv') import re def

我正在试验tf idf匹配。我遵循了文章中的教程。我想知道我是否可以将一个输入列表与另一个已处理数据列表进行匹配,然后让这个脚本将输出作为输入列表中每个项目的现有第二个列表的潜在匹配项返回

我希望你们中的一个能帮我找到正确的方向!谢谢

import pandas as pd

pd.set_option('display.max_colwidth', -1)
names = pd.read_csv('sample-data/descriptions_1.csv')


import re
def ngrams(string, n=4):
    string = re.sub(r'[,-./]|\sBD', r'', str(string))
    ngrams = zip(*[string[i:] for i in range(n)])
    return [''.join(ngram) for ngram in ngrams]

from sklearn.feature_extraction.text import TfidfVectorizer

company_names = names['name']
comparer_names = comparer['name']
vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)
tf_idf_matrix = vectorizer.fit_transform(company_names)

import numpy as np
from scipy.sparse import csr_matrix
import sparse_dot_topn.sparse_dot_topn as ct


def awesome_cossim_top(A, B, ntop, lower_bound=0):
    # force A and B as a CSR matrix.
    # If they have already been CSR, there is no overhead
    A = A.tocsr()
    B = B.tocsr()
    M, _ = A.shape
    _, N = B.shape

    idx_dtype = np.int32

    nnz_max = M * ntop

    indptr = np.zeros(M + 1, dtype=idx_dtype)
    indices = np.zeros(nnz_max, dtype=idx_dtype)
    data = np.zeros(nnz_max, dtype=A.dtype)

    ct.sparse_dot_topn(
        M, N, np.asarray(A.indptr, dtype=idx_dtype),
        np.asarray(A.indices, dtype=idx_dtype),
        A.data,
        np.asarray(B.indptr, dtype=idx_dtype),
        np.asarray(B.indices, dtype=idx_dtype),
        B.data,
        ntop,
        lower_bound,
        indptr, indices, data)

    return csr_matrix((data, indices, indptr), shape=(M, N))

import time
t1 = time.time()
matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 30, 0.5)
t = time.time()-t1
print("SELFTIMED:", t)


def get_matches_df(sparse_matrix, name_vector, top=100):
    non_zeros = sparse_matrix.nonzero()

    sparserows = non_zeros[0]
    sparsecols = non_zeros[1]

    if top:
        nr_matches = top
    else:
        nr_matches = sparsecols.size

    left_side = np.empty([nr_matches], dtype=object)
    right_side = np.empty([nr_matches], dtype=object)
    similairity = np.zeros(nr_matches)

    for index in range(0, nr_matches):
        left_side[index] = name_vector[sparserows[index]]
        right_side[index] = name_vector[sparsecols[index]]
        similairity[index] = sparse_matrix.data[index]

    return pd.DataFrame({'left_side': left_side,
                         'right_side': right_side,
                         'similairity': similairity})

matches_df = get_matches_df(matches, company_names, top=1000)
matches_df = matches_df[matches_df['similairity'] < 0.99999] # Remove all exact matches
print(matches_df.sample(20))

file_name = str("hallo.csv")
matches_df.to_csv(file_name, sep=',', encoding='utf-8')
将熊猫作为pd导入
pd.set_选项('display.max_colwidth',-1)
name=pd.read\u csv('sample-data/descriptions\u 1.csv'))
进口稀土
def ngrams(字符串,n=4):
string=re.sub(r'[,-./]|\sBD',r'',str(string))
ngrams=zip(*[string[i:]表示范围(n)中的i)
return[''。在ngram中加入(ngram)以获得ngram]
从sklearn.feature\u extraction.text导入TfidfVectorizer
公司名称=名称['name']
比较器名称=比较器['name']
矢量器=TFIDF矢量器(最小值df=1,分析仪=ngrams)
tf_idf_矩阵=矢量器.拟合变换(公司名称)
将numpy作为np导入
从scipy.sparse导入csr_矩阵
导入稀疏点。稀疏点作为ct
def awesome_cossim_top(A、B、ntop、下限=0):
#强制A和B作为CSR矩阵。
#如果他们已经完成了CSR,则没有管理费用
A=A.tocsr()
B=B.tocsr()
M、 形状
_,N=B.形状
idx_dtype=np.int32
nnz_max=M*ntop
indptr=np.zero(M+1,dtype=idx\u dtype)
索引=np.0(nnz_max,dtype=idx_dtype)
数据=np.0(nnz_max,dtype=A.dtype)
ct.sparse\u dot\u topn(
M、 N,np.asarray(A.indptr,dtype=idx_dtype),
np.asarray(A.index,dtype=idx_dtype),
A.数据,
np.asarray(B.indptr,dtype=idx_dtype),
np.asarray(B.index,dtype=idx_dtype),
B.数据,
ntop,
下界,
indptr、索引、数据)
返回csr_矩阵((数据,指数,indptr),形状=(M,N))
导入时间
t1=时间。时间()
matches=awesome_cossim_top(tf_idf_矩阵,tf_idf_矩阵.transpose(),30,0.5)
t=time.time()-t1
打印(“自定时:”,t)
def get_matches_df(稀疏矩阵,名称向量,top=100):
非零=稀疏矩阵。非零()
sparserows=非零[0]
sparsecols=非零[1]
如果顶部:
nr_匹配=顶部
其他:
nr_匹配=sparsecols.size
左侧=np.empty([nr\u匹配],数据类型=对象)
右侧=np.empty([nr\u匹配],dtype=object)
相似性=np.零(nr_匹配)
对于范围内的索引(0,nr_匹配):
左侧[index]=名称向量[sparserows[index]]
右侧[index]=名称向量[sparsecols[index]]
相似性[索引]=稀疏矩阵。数据[索引]
返回pd.DataFrame({'left_side':left_side,
“右侧”:右侧,
“相似性”:相似性})
匹配项\u df=获取匹配项\u df(匹配项,公司名称,top=1000)
matches_df=matches_df[matches_df['similarity']<0.99999]#删除所有精确匹配
打印(与样品(20)匹配)
文件名=str(“hallo.csv”)
将_df.匹配到_csv(文件名,sep=',',编码='utf-8')

我通过对中链接的方法进行一些修改,就能够解决这个问题。关键是要做以下修改:

vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)
first_idf_matrix = vectorizer.fit_transform(first_lines)
second_idf_matrix = vectorizer.transform(second_lines)
matches = awesome_cossim_top(first_idf_matrix, second_idf_matrix, 1, 0)
这意味着函数
get\u matches\u df
不再有用,而是要为第一个列表中的每一行提取匹配行,我们执行以下操作:

for dirty_idx, _ in enumerate(first_lines):
    second_idx = matches[dirty_idx].argmax()

我想你需要先把
的idx
改成
脏的idx