我想知道為什么我的 TF-IDF 的 Pandas 實(shí)現(xiàn)顯示的結(jié)果與 sklearn 實(shí)現(xiàn)略有不同。這是我的實(shí)現(xiàn):text = ["aa bb cc dd ee", "bb cc dd dd"]terms = [Counter(t.split(' ')) for t in text]tf = pd.DataFrame(terms)tf = tf.fillna(0)num_docs = len(text)idf = np.log(num_docs / tf[tf >= 1].count()) + 1 tf_idf = tf * idfnorm = np.sqrt((tf_idf ** 2).sum(axis=1))norm_tf_idf = tf_idf.div(norm, axis=0)>>> norm_tf_idf aa bb cc dd ee0 0.572929 0.338381 0.338381 0.338381 0.5729291 0.000000 0.408248 0.408248 0.816497 0.000000但是,如果我使用 sklearn:tf = TfidfVectorizer(smooth_idf=False, stop_words=None, sublinear_tf=True)x = tf.fit_transform(text)sk = pd.DataFrame(x.toarray())sk.columns = tf.get_feature_names()sk>>> sk aa bb cc dd ee0 0.572929 0.338381 0.338381 0.338381 0.5729291 0.000000 0.453295 0.453295 0.767495 0.000000或者,如果我們減去它們:>>> norm_tf_idf - sk aa bb cc dd ee0 0.0 0.000000 0.000000 0.000000 0.01 0.0 -0.045046 -0.045046 0.049002 0.0
1 回答

慕婉清6462132
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
我真笨。在 sklearn 源代碼中潛水后,我注意到了該sublinear_tf
參數(shù)。將此參數(shù)設(shè)置為 True 時(shí),術(shù)語頻率被替換為log(TF) + 1
,恰好是我將此參數(shù)設(shè)置為True
:)
要在熊貓中實(shí)現(xiàn)次線性 TF,這應(yīng)該有效:
tf[tf > 0] = np.log(tf[tf > 0] ) + 1
添加回答
舉報(bào)
0/150
提交
取消