Skip to main content
 首页 » 编程设计

python之如何在当前的词袋分类中添加另一个文本特征在 Scikit-learn 中

2024年12月31日14jackei

这是我的输入矩阵 enter image description here

我的示例代码:

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 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.metrics import accuracy_score 
 
X_train, X_test, y_train, y_test = train_test_split(data['Extract'],  
data['Expense Account code Description'], random_state = 0) 
 
from sklearn.pipeline import Pipeline , FeatureUnion 
text_clf = Pipeline([('vect', CountVectorizer(ngram_range=(1,1))), 
              ('tfidf', TfidfTransformer(use_idf = False)), 
              ('clf', RandomForestClassifier(n_estimators =100,  
 max_features='log2',criterion = 'entropy')), 
 ]) 
 text_clf = text_clf.fit(X_train, y_train) 

我在这里为“提取”列应用词袋模型对“费用帐户代码描述”进行分类,在这里我得到大约 92% 的准确度,但如果我想包含“供应商名称”作为另一个集合输入功能我该怎么做。有什么办法可以和词袋一起做吗? ,

请您参考如下方法:

您可以使用 FeatureUnion。 您还需要创建一个新的 Transformer 类,其中包含您需要采取的必要操作,即包括供应商名称、获取虚拟对象。

Feature Union 将适合您的管道。

供引用。

class get_Vendor(BaseEstimator,TransformerMixin): 
 
    def transform(self, X,y): 
        return  
 
lr_tfidf = Pipeline([('features',FeatureUnion([('other',get_vendor()), 
        ('vect', tfidf)])),('clf', RandomForestClassifier())])