簡體   English   中英

從數據框中提取文本特征

[英]Extract text features from dataframe

我有帶有兩個文本字段和其他功能的數據框,例如這種格式:

 message            feature_1      feature_2       score        text
 'This is the text'     4             7            10          extra text
 'This is more text'    3             2            8           and this is another text

現在我的目標是預測分數,當嘗試將此數據幀轉換為特征矩陣以將其輸入到我的機器學習模型中時,這是我所做的:

    # Create vectorizer for function to use
    vectorizer = TfidfVectorizer()
    # combine the numerical features with the TFIDF generated matrix
    X = sp.sparse.hstack( (vectorizer.fit_transform(df.message),
                      df[['feature_1', 'feature_2']].values, vectorizer.fit_transform(df.text)),
                      format='csr')

現在,在打印 X 矩陣的形狀時,我得到了 2x13,但是當我像這樣檢查 X_columsn 時:

X_columns = vectorizer.get_feature_names() + df[['feature_1', 'feature_2']].columns.tolist()

我沒有得到語料庫中的所有單詞,它只給我帶來了df.text存在的單詞,而其他特征屬性沒有df.message中的df.message

['and', 'another', 'extra', 'is', 'text', 'this', 'feature_1', 'feature_2']

我怎樣才能讓 X 包含我所有的數據框功能!!

作為一般規則,在整個文本語料庫上安裝向量化器來計算詞匯量,然后將所有文本轉換為向量。

您要擬合向量化器兩次,因此第二次調用fit_transform覆蓋第一次並相應地更新詞匯表。 首先嘗試擬合兩個文本字段以計算整個語料庫的詞匯量,然后轉換每個文本字段,如下所示:

from sklearn.feature_extraction.text import TfidfVectorizer
import scipy as sp

vectorizer = TfidfVectorizer()
vectorizer.fit(df.message.append(df.text))
X = sp.sparse.hstack( (vectorizer.transform(df.message),
                 df[['feature_1', 'feature_2']].values, vectorizer.transform(df.text)),
                 format='csr')

X_columns = vectorizer.get_feature_names() + df[['feature_1', 'feature_2']].columns.tolist()

這給了我:

X_columns
Out[51]: ['and', 'another', 'extra', 'is', 'more', 'text', 'the', 'this', 'feature_1', 'feature_2']

那是你追求的嗎?

暫無
暫無

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

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