我正在尝试通过预处理、生成 tf-idf 矩阵,然后应用 K 均值来完成文本文档聚类的经典工作。但是,在经典 20NewsGroup 数据集上测试此工作流程会导致大多数文档聚集到一个集群中。(我最初尝试对 20 个组中的 6 个组中的所有文档进行聚类 - 因此希望聚类成 6 个簇)。
我正在 Apache Spark 中实现此功能,因为我的目的是在数百万个文档上利用此技术。以下是在 Databricks 上用 Pyspark 编写的代码:
#declare path to folder containing 6 of 20 news group categories
path = "/mnt/%s/20news-bydate.tar/20new-bydate-train-lessFolders/*/*" %
MOUNT_NAME
#read all the text files from the 6 folders. Each entity is an entire
document.
text_files = sc.wholeTextFiles(path).cache()
#convert rdd to dataframe
df = text_files.toDF(["filePath", "document"]).cache()
from pyspark.ml.feature import HashingTF, IDF, Tokenizer, CountVectorizer
#tokenize the document text
tokenizer = Tokenizer(inputCol="document", outputCol="tokens") …Run Code Online (Sandbox Code Playgroud) 使用gensim:
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
sent0 = "The quick brown fox jumps over the lazy brown dog .".lower().split()
sent1 = "Mr brown jumps over the lazy fox .".lower().split()
dataset = [sent0, sent1]
vocab = Dictionary(dataset)
corpus = [vocab.doc2bow(sent) for sent in dataset]
model = TfidfModel(corpus)
# To retrieve the same pd.DataFrame format.
documents_tfidf_lol = [{vocab[word_idx]:tfidf_value for word_idx, tfidf_value in sent} for sent in model[corpus]]
documents_tfidf = pd.DataFrame(documents_tfidf_lol)
documents_tfidf.fillna(0, inplace=True)
documents_tfidf
Run Code Online (Sandbox Code Playgroud)
[出去]:
dog mr quick …Run Code Online (Sandbox Code Playgroud) 我有一个有 5000 条评论的文档。我对该文档应用了 tf-idf 。这里的sample_data包含5000条评论。我正在对具有一克范围的sample_data应用tf-idf向量化器。现在我想从样本数据中获取具有最高 tf-idf 值的前 1000 个单词。谁能告诉我如何获得最热门的单词?
from sklearn.feature_extraction.text import TfidfVectorizer
tf_idf_vect = TfidfVectorizer(ngram_range=(1,1))
tf_idf_vect.fit(sample_data)
final_tf_idf = tf_idf_vect.transform(sample_data)
Run Code Online (Sandbox Code Playgroud) tf-idf python-3.x scikit-learn sklearn-pandas tfidfvectorizer
我有一个网站元描述列表(128k 描述;每个描述平均有 20-30 个单词),并且正在尝试构建一个相似度排名器(如:向我显示与此网站元描述最相似的 5 个网站)
它与 TF-IDF uni- 和 bigram 配合得非常好,我认为我还可以通过添加预先训练的词嵌入(准确地说是 spacy“en_core_web_lg”)来改进它。情节扭曲:根本行不通。从字面上没有得到一个好的猜测,它突然吐出完全随机的建议。
下面是我的代码。有什么想法我可能哪里出了问题吗?我是否在监督一些高度直观的事情?
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import sys
import pickle
import spacy
import scipy.sparse
from scipy.sparse import csr_matrix
import math
from sklearn.metrics.pairwise import linear_kernel
nlp=spacy.load('en_core_web_lg')
""" Tokenizing"""
def _keep_token(t):
return (t.is_alpha and
not (t.is_space or t.is_punct or
t.is_stop or t.like_num))
def _lemmatize_doc(doc):
return [ t.lemma_ for t in doc if _keep_token(t)]
def _preprocess(doc_list):
return [_lemmatize_doc(nlp(doc)) for doc in doc_list]
def dummy_fun(doc): …Run Code Online (Sandbox Code Playgroud) 我可以通过计算文档中的Term数量来轻松获取TF,并且我想知道如何计算文档频率,即包含该术语的文档数量
到目前为止我所获得的是查询solr的大量行并重新计算结果,但这非常耗费时间和内存.我只想算上条款
SolrQuery q = new SolrQuery();
q.setQuery("tweet_text:"+kw);
q.addField("tweet_text");
q.setRows(40000000);
SolrDocumentList results = null ;
try {
QueryResponse rsp = solrServer.query(q);
results = rsp.getResults();
} catch (SolrServerException e) {
e.printStackTrace();
}
ArrayList<String> tweets = new ArrayList<String>();
for (SolrDocument doc : results)
{
tweets.add(doc.getFieldValue("tweet_text").toString());
}
Run Code Online (Sandbox Code Playgroud) 我正在学习多标签分类,并尝试从scikit学习中实施tfidf教程。我正在处理文本语料库以计算其tf-idf分数。我为此目的使用模块sklearn.feature_extraction.text。使用CountVectorizer和TfidfTransformer,现在我为每个词汇集了语料库矢量和tfidf。问题是我现在有一个稀疏矩阵,例如:
(0, 47) 0.104275891915
(0, 383) 0.084129133023
.
.
.
.
(4, 308) 0.0285015996586
(4, 199) 0.0285015996586
Run Code Online (Sandbox Code Playgroud)
我想将此sparse.csr.csr_matrix转换为列表列表,以便可以摆脱上述csr_matrix的文档ID,并获得tfidf和vocabularyId对,例如
47:0.104275891915 383:0.084129133023
.
.
.
.
308:0.0285015996586
199:0.0285015996586
Run Code Online (Sandbox Code Playgroud)
有什么方法可以转换为列表列表,或者可以通过其他方式更改格式以获得tfidf-vocabularyId对吗?
我正在研究大约10万篇研究论文.我正在考虑三个领域:
我使用TfIdfVectorizer获取明文字段的TfIdf表示,并将由此产生的词汇反馈到标题和摘要的矢量化器中,以确保所有三个表示都在同一个词汇上工作.我的想法是,由于明文字段比其他两个字段大得多,它的词汇很可能涵盖其他字段中的所有字词.但是,如果情况并非如此,那么TfIdfVectorizer如何处理新的单词/代币呢?
这是我的代码示例:
vectorizer = TfidfVectorizer(min_df=2)
plaintexts_tfidf = vectorizer.fit_transform(plaintexts)
vocab = vectorizer.vocabulary_
# later in an another script after loading the vocab from disk
vectorizer = TfidfVectorizer(min_df=2, vocabulary=vocab)
titles_tfidf = vectorizer.fit_transform(titles)
Run Code Online (Sandbox Code Playgroud)
词汇有~90万字.
在矢量化期间,我没有遇到任何问题,但后来当我想使用sklearn.metrics.pairwise.cosine_similarity比较矢量化标题之间的相似性时,我遇到了这个错误:
>> titles_sim = cosine_similarity(titles_tfidf)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-237-5aa86fe892da> in <module>()
----> 1 titles_sim = cosine_similarity(titles)
/usr/local/lib/python3.5/dist-packages/sklearn/metrics/pairwise.py in cosine_similarity(X, Y, dense_output)
916 Y_normalized = normalize(Y, copy=True)
917
--> 918 K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output)
919
920 return K
/usr/local/lib/python3.5/dist-packages/sklearn/utils/extmath.py in safe_sparse_dot(a, …Run Code Online (Sandbox Code Playgroud) 我使用sklearn来获取tf-idf值,如下所示。
from sklearn.feature_extraction.text import TfidfVectorizer
myvocabulary = ['life', 'learning']
corpus = {1: "The game of life is a game of everlasting learning", 2: "The unexamined life is not worth living", 3: "Never stop learning"}
tfidf = TfidfVectorizer(vocabulary = myvocabulary, ngram_range = (1,3))
tfs = tfidf.fit_transform(corpus.values())
Run Code Online (Sandbox Code Playgroud)
我试图做到如下。
idf = tfidf.idf_
dic = dict(zip(tfidf.get_feature_names(), idf))
print(dic)
Run Code Online (Sandbox Code Playgroud)
但是,然后得到如下输出。
{'life': 1.2876820724517808, 'learning': 1.2876820724517808}
Run Code Online (Sandbox Code Playgroud)
请帮我。
我有一个文档,我被标记,然后我采取另一个文件,我通过计算它们的余弦相似性来比较两者.
但是,在我计算它们的相似度之前,我想提前增加其中一个词的权重.我想通过加倍那个词的数量来做到这一点,但我不知道该怎么做.
假设我有以下......
text = [
"This is a test",
"This is something else",
"This is also a test"
]
test = ["This is something"]
Run Code Online (Sandbox Code Playgroud)
接下来,我定义停用词并调用CountVectorizer两组文档.
stopWords = set(stopwords.words('english'))
vectorizer = CountVectorizer(stop_words=stopWords)
trainVectorizerArray = vectorizer.fit_transform(text).toarray()
testVectorizerArray = vectorizer.transform(test).toarray()
Run Code Online (Sandbox Code Playgroud)
在下一部分中,我计算余弦相似度 ......
cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)
for vector in trainVectorizerArray:
print(vector)
for testV in testVectorizerArray:
print(testV)
cosine = cosine_function(vector, testV)
print(cosine)
Run Code Online (Sandbox Code Playgroud)
但是,在我计算相似度之前,我怎样才能增加其中一个词的权重.假设在这个例子中我想增加重量something,我该怎么做?我认为你通过增加字数来做到这一点,但我不知道如何增加它.
我试图预测输入消息的不同类别,并且我使用波斯语。我使用Tfidf和Naive-Bayes对输入数据进行分类。这是我的代码:
import pandas as pd
df=pd.read_excel('dataset.xlsx')
col=['label','body']
df=df[col]
df.columns=['label','body']
df['class_type'] = df['label'].factorize()[0]
class_type_df=df[['label','class_type']].drop_duplicates().sort_values('class_type')
class_type_id = dict(class_type_df.values)
id_to_class_type = dict(class_type_df[['class_type', 'label']].values)
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer()
features=tfidf.fit_transform(df.body).toarray()
classtype=df.class_type
print(features.shape)
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
X_train,X_test,y_train,y_test=train_test_split(df['body'],df['label'],random_state=0)
cv=CountVectorizer()
X_train_counts=cv.fit_transform(X_train)
tfidf_transformer=TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
clf = MultinomialNB().fit(X_train_tfidf, y_train)
print(clf.predict(cv.transform(["???? ? ???? ????? ?????? ?? ????"])))
Run Code Online (Sandbox Code Playgroud)
但是,当我运行上面的代码时,当我期望在输出中给我“ ads”类时,它将引发以下异常:
追溯(最近一次通话最近):X_train_counts = cv.fit_transform(X_train)中的文件“ ... / multiclass-main.py”,第27行,文件“ ... \ sklearn \ feature_extraction \ text.py”,行1012 (在fit_transform …
tf-idf ×10
python ×7
scikit-learn ×6
nlp ×3
apache-spark ×1
gensim ×1
java ×1
k-means ×1
python-3.x ×1
scipy ×1
solr ×1
spacy ×1