【发布时间】:2020-04-28 12:23:45
【问题描述】:
我正在对文本数据执行多标签分类。
我希望使用tfidf 的组合功能和类似于示例here 使用FeatureUnion 的自定义语言功能。
我已经生成了自定义语言特征,它们采用字典的形式,其中键代表标签,(列表)值代表特征。
custom_features_dict = {'contact':['contact details', 'e-mail'],
'demographic':['gender', 'age', 'birth'],
'location':['location', 'geo']}
训练数据结构如下:
text contact demographic location
--- --- --- ---
'provide us with your date of birth and e-mail' 1 1 0
'contact details and location will be stored' 1 0 1
'date of birth should be before 2004' 0 1 0
上面的dict怎么能合并到FeatureUnion里面呢?我的理解是,应该调用一个用户定义的函数,该函数返回与训练数据中是否存在字符串值(来自custom_features_dict)相对应的布尔值。
对于给定的训练数据,这给出了以下 list 或 dict:
[
{
'contact':1,
'demographic':1,
'location':0
},
{
'contact':1,
'demographic':0,
'location':1
},
{
'contact':0,
'demographic':1,
'location':0
},
]
上面的list如何实现fit和transform?
代码如下:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction import DictVectorizer
#from sklearn.metrics import accuracy_score
from sklearn.multiclass import OneVsRestClassifier
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from io import StringIO
data = StringIO(u'''text,contact,demographic,location
provide us with your date of birth and e-mail,1,1,0
contact details and location will be stored,0,1,1
date of birth should be before 2004,0,1,0''')
df = pd.read_csv(data)
custom_features_dict = {'contact':['contact details', 'e-mail'],
'demographic':['gender', 'age', 'birth'],
'location':['location', 'geo']}
my_features = [
{
'contact':1,
'demographic':1,
'location':0
},
{
'contact':1,
'demographic':0,
'location':1
},
{
'contact':0,
'demographic':1,
'location':0
},
]
bow_pipeline = Pipeline(
steps=[
("tfidf", TfidfVectorizer(stop_words=stop_words)),
]
)
manual_pipeline = Pipeline(
steps=[
# This needs to be fixed
("custom_features", my_features),
("dict_vect", DictVectorizer()),
]
)
combined_features = FeatureUnion(
transformer_list=[
("bow", bow_pipeline),
("manual", manual_pipeline),
]
)
final_pipeline = Pipeline([
('combined_features', combined_features),
('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
]
)
labels = ['contact', 'demographic', 'location']
for label in labels:
final_pipeline.fit(df['text'], df[label])
【问题讨论】:
标签: python scikit-learn nlp text-classification multilabel-classification