簡體   English   中英

如何使用Spark為文本分類創建TF-IDF?

[英]How can I create a TF-IDF for Text Classification using Spark?

我有一個CSV文件,格式如下:

product_id1,product_title1
product_id2,product_title2
product_id3,product_title3
product_id4,product_title4
product_id5,product_title5
[...]

product_idX是一個整數,product_titleX是一個String,例如:

453478692, Apple iPhone 4 8Go

我正在嘗試從我的文件創建TF-IDF,所以我可以將它用於MLlib中的朴素貝葉斯分類器。

到目前為止,我正在使用Spark for Scala並使用我在官方頁面和Berkley AmpCamp 34上找到的教程。

所以我正在讀文件:

val file = sc.textFile("offers.csv")

然后我將它映射到元組RDD[Array[String]]

val tuples = file.map(line => line.split(",")).cache

在我將元組轉換成對RDD[(Int, String)]

val pairs = tuples.(line => (line(0),line(1)))

但我被困在這里,我不知道如何從它創建Vector將其變成TFIDF。

謝謝

為了自己這樣做(使用pyspark),我首先從語料庫中創建兩個數據結構。 第一個是關鍵的價值結構

document_id, [token_ids]

第二個是反向索引

token_id, [document_ids]

我將分別稱為語料庫和inv_index。

為了得到這個,我們需要計算每個文檔中每個標記的出現次數。 所以

from collections import Counter
def wc_per_row(row):
    cnt = Counter()
    for word in row:
        cnt[word] += 1
    return cnt.items() 

tf = corpus.map(lambda (x, y): (x, wc_per_row(y)))

df只是每個術語倒排索引的長度。 由此我們可以計算出idf。

df = inv_index.map(lambda (x, y): (x, len(y)))
num_documnents = tf.count()

# At this step you can also apply some filters to make sure to keep
# only terms within a 'good' range of df. 
import math.log10
idf = df.map(lambda (k, v): (k, 1. + log10(num_documents/v))).collect()

現在我們只需要在term_id上進行連接:

def calc_tfidf(tf_tuples, idf_tuples):
    return [(k1, v1 * v2) for (k1, v1) in tf_tuples for
        (k2, v2) in idf_tuples if k1 == k2]

tfidf = tf.map(lambda (k, v): (k, calc_tfidf(v, idf)))

不過,這不是一個特別高效的解決方案。 調用collect將idf帶入驅動程序,以便它可用於連接似乎是錯誤的事情。

當然,它需要首先標記並創建從詞匯表中的每個uniq標記到某個token_id的映射。

如果有人能改進這一點,我很感興趣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM