Gridsearch for NLP-如何结合CountVec和其他功能



我正在做一个关于情绪分析的基本NLP项目,我想使用GridsearchCV来优化我的模型。

下面的代码显示了我正在使用的一个示例数据帧Content是要传递给CountVectorizer的列,label是要预测的y列,feature_1和feature_2也是我希望包含在模型中的列。

'content': 'Got flat way today Pot hole Another thing tick crap thing happen week list',
'feature_1': '1', 
'feature_2': '34', 
'label':1}, 
{'content': 'UP today Why doe head hurt badly',
'feature_1': '5', 
'feature_2': '142', 
'label':1},
{'content': 'spray tan fail leg foot Ive scrubbing foot look better ',
'feature_1': '7', 
'feature_2': '123', 
'label':0},])

我正在遵循一个stackoverflow的答案:使用管道和网格搜索进行功能选择

from sklearn.pipeline import FeatureUnion, Pipeline
from sklearn.base import TransformerMixin, BaseEstimator
class CustomFeatureExtractor(BaseEstimator, TransformerMixin):
def __init__(self, feature_1=True, feature_2=True):
self.feature_1=feature_1
self.feature_2=feature_2

def extractor(self, tweet):
features = []
if self.feature_2:

features.append(df['feature_2'])
if self.feature_1:
features.append(df['feature_1'])


return np.array(features)
def fit(self, raw_docs, y):
return self
def transform(self, raw_docs):

return np.vstack(tuple([self.extractor(tweet) for tweet in raw_docs]))

下面是我试图将数据帧放在上面的网格搜索:

lr = LogisticRegression()
# Pipeline
pipe = Pipeline([('features', FeatureUnion([("vectorizer", CountVectorizer(df['content'])),
("extractor", CustomFeatureExtractor())]))
,('classifier', lr())
])
But yields results: TypeError: 'LogisticRegression' object is not callable

不知道是否还有其他更简单的方法可以做到这一点?

然而,我已经提到了以下主题,但没有任何效果:如何将TFIDF功能与其他功能相结合使用管道和网格搜索进行特征选择

您不能执行lr()LogisticRegression实际上是不可调用的,它有一些用于lr对象的方法。

改为尝试(不带括号的lr(:

lr = LogisticRegression()
pipe = Pipeline([('features', FeatureUnion([("vectorizer", CountVectorizer(df['content'])),
("extractor", CustomFeatureExtractor())]))
,('classifier', lr)
])

并且您的错误消息应该会消失。

最新更新