小编pra*_*nth的帖子

如何通过scikit-learn TfidfVectorizer计算TF-IDF

我运行以下代码将文本矩阵转换为TF-IDF矩阵.

text = ['This is a string','This is another string','TFIDF computation calculation','TfIDF is the product of TF and IDF']

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(max_df=1.0, min_df=1, stop_words='english',norm = None)

X = vectorizer.fit_transform(text)
X_vovab = vectorizer.get_feature_names()
X_mat = X.todense()
X_idf = vectorizer.idf_
Run Code Online (Sandbox Code Playgroud)

我得到以下输出

X_vovab =

[u'calculation',
 u'computation',
 u'idf',
 u'product',
 u'string',
 u'tf',
 u'tfidf']
Run Code Online (Sandbox Code Playgroud)

和X_mat =

  ([[ 0.        ,  0.        ,  0.        ,  0.        ,  1.51082562,
      0.        ,  0.        ],
    [ 0.        ,  0.        ,  0.        ,  0.        ,  1.51082562,
      0.        , …
Run Code Online (Sandbox Code Playgroud)

nlp tf-idf scikit-learn

15
推荐指数
2
解决办法
7451
查看次数

Spark中的潜在Dirichlet分配(LDA)

我正在尝试在Spark中编写一个progor来执行Latent Dirichlet分配(LDA).此Spark文档页面提供了一个很好的示例,用于在示例数据上执行LDA.以下是该计划

from pyspark.mllib.clustering import LDA, LDAModel
from pyspark.mllib.linalg import Vectors

# Load and parse the data
data = sc.textFile("data/mllib/sample_lda_data.txt")
parsedData = data.map(lambda line: Vectors.dense([float(x) for x in line.strip().split(' ')]))
# Index documents with unique IDs
corpus = parsedData.zipWithIndex().map(lambda x: [x[1], x[0]]).cache()

# Cluster the documents into three topics using LDA
ldaModel = LDA.train(corpus, k=3)

# Output topics. Each is a distribution over words (matching word count vectors)
print("Learned topics (as distributions over vocab of " + str(ldaModel.vocabSize()) …
Run Code Online (Sandbox Code Playgroud)

python lda pyspark

9
推荐指数
1
解决办法
5439
查看次数

为什么list.append(x)比list + = l [x]更有效?

附加到列表可能有两种方式:

1)

mat = []
for i in range(10):
    mat.append(i)
Run Code Online (Sandbox Code Playgroud)

要么

2)

mat = []
for i in range(10):
    mat += [i]
Run Code Online (Sandbox Code Playgroud)

官方Python文档:

示例中显示的方法append()是为列表对象定义的; 它在列表的末尾添加了一个新元素.在此示例中,它等效于result = result + [a],但效率更高.

文档表明方法1更有效.为什么会这样?

python list

5
推荐指数
1
解决办法
295
查看次数

使用fuzzywuzzy 的字符串匹配——是使用Levenshtein 距离还是Ratcliff/Obershelp 模式匹配算法?

Fuzzywuzzy是一个非常流行的字符串匹配库。根据库的文档,提到它使用 Levenshtein 距离来计算序列之间的差异。但是仔细检查后,我发现它实际上使用SequenceMatcherdifflib库中的函数。根据文档,此函数使用 Ratcliff/Obershelp 模式匹配算法。

根据定义,Levenshtein 距离是将一个字符串转换为另一个字符串所需的最小编辑次数,Ratcliff/Obershelp 模式匹配算法计算匹配字符的两倍数除以两个字符串中的字符总数。比较两者的密切相关帖子

当我运行一个例子时,我得到了 Fuzzywuzzy 中 SequenceMatcher 和 ratio 函数的相同结果。

from difflib import SequenceMatcher
from fuzzywuzzy import fuzz
s = SequenceMatcher(None, "abcd", "bcde")
s.ratio()
# 0.75
fuzz.ratio("abcd", "bcde")
# 75
Run Code Online (Sandbox Code Playgroud)

如果我手动计算两个字符串之间的 Levenshtein 距离,我想它只会是 2。在这种情况下,它如何像贡献者在文档中所写的那样使用 Levenshtein 距离?

python string-matching levenshtein-distance

5
推荐指数
1
解决办法
2831
查看次数