这是我的输入矩阵 输入图像描述
我的示例代码:
from sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_scoreX_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 , FeatureUniontext_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)
在这里,我对’Extract’列应用了词袋模型来分类’Expense Account code Description’,我得到了大约92%的准确率。但是,如果我想包括’Vendor name’作为另一组输入特征,我该怎么做呢?有没有办法在词袋模型中同时使用这个特征?
回答:
你可以使用FeatureUnion。另外,你需要创建一个新的Transformer类,包含你需要执行的必要操作,例如包含供应商名称,生成虚拟变量。
Feature Union将适应你的pipeline。
供参考。
class get_Vendor(BaseEstimator,TransformerMixin): def transform(self, X,y): return lr_tfidf = Pipeline([('features',FeatureUnion([('other',get_vendor()), ('vect', tfidf)])),('clf', RandomForestClassifier())])