Scikit learn 基于logistic回归的特征选择

Scikit learn 基于logistic回归的特征选择,scikit-learn,logistic-regression,feature-selection,Scikit Learn,Logistic Regression,Feature Selection,我正在使用逻辑回归进行特征选择(在一个包含1930388行和88个特征的数据集上)。如果我在保留的数据上测试模型,准确率略高于60%。响应变量是均匀分布的。我的问题是,如果模型的性能不好,我能考虑它所赋予的特性作为实际的重要特征吗?或者我应该尝试提高模型的准确性,尽管我的最终目标不是提高准确性,而是只获取重要的功能sklearn的GridSearchCV有一些非常简洁的方法来为您提供最佳的功能集。例如,考虑下面的代码 pipeline = Pipeline([ ('vect', Tfid

我正在使用逻辑回归进行特征选择(在一个包含1930388行和88个特征的数据集上)。如果我在保留的数据上测试模型,准确率略高于60%。响应变量是均匀分布的。我的问题是,如果模型的性能不好,我能考虑它所赋予的特性作为实际的重要特征吗?或者我应该尝试提高模型的准确性,尽管我的最终目标不是提高准确性,而是只获取重要的功能

sklearn的GridSearchCV有一些非常简洁的方法来为您提供最佳的功能集。例如,考虑下面的代码

pipeline = Pipeline([
    ('vect', TfidfVectorizer(stop_words='english',sublinear_tf=True)),
    ('clf', LogisticRegression())
    ])

    parameters = {
        'vect__max_df': (0.25, 0.5, 0.6, 0.7, 1.0),
        'vect__ngram_range': ((1, 1), (1, 2), (2,3), (1,3), (1,4), (1,5)),
        'vect__use_idf': (True, False),
        'clf__C': (0.1, 1, 10, 20, 30)
    }

这里的参数数组包含了我需要考虑的所有不同的参数。注意使用if-vect\uuu max\u df。max_df是我的矢量器使用的一个实际键,它是我的特征选择器。所以

'vect__max_df': (0.25, 0.5, 0.6, 0.7, 1.0),
实际上指定我要为我的矢量器尝试上述5个值。其他人也是如此。请注意,我是如何将向量器绑定到键“vect”和分类器绑定到键“clf”的。你能看到图案吗?继续

    traindf = pd.read_json('../../data/train.json')

    traindf['ingredients_clean_string'] = [' , '.join(z).strip() for z in traindf['ingredients']]  

    traindf['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in traindf['ingredients']]       

    X, y = traindf['ingredients_string'], traindf['cuisine'].as_matrix()

    X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)

    grid_search = GridSearchCV(pipeline, parameters, n_jobs=3, verbose=1, scoring='accuracy')
    grid_search.fit(X_train, y_train)

    print ('best score: %0.3f' % grid_search.best_score_)
    print ('best parameters set:')

    bestParameters = grid_search.best_estimator_.get_params()

    for param_name in sorted(parameters.keys()):
        print ('\t %s: %r' % (param_name, bestParameters[param_name]))

    predictions = grid_search.predict(X_test)
    print ('Accuracy:', accuracy_score(y_test, predictions))
    print ('Confusion Matrix:', confusion_matrix(y_test, predictions))
    print ('Classification Report:', classification_report(y_test, predictions))
请注意,bestParameters数组将为我提供在创建管道时指定的所有选项中最好的一组参数

希望这有帮助

编辑:获取所选功能的列表

因此,一旦您拥有了最佳的参数集,就可以使用这些参数值创建向量器和分类器

vect = TfidfVectorizer('''use the best parameters here''')
然后你基本上要再次训练这个矢量器。这样,矢量器将从您的训练集中选择某些功能

traindf = pd.read_json('../../data/train.json')

        traindf['ingredients_clean_string'] = [' , '.join(z).strip() for z in traindf['ingredients']]  

        traindf['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in traindf['ingredients']]       

        X, y = traindf['ingredients_string'], traindf['cuisine'].as_matrix()

        X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)

       termDocMatrix = vect.fit_transform(X_train, y_train)
现在,termDocMatrix具有所有选定的功能。此外,还可以使用矢量器获取要素名称。假设您想要获得前100个功能。比较的标准是卡方分数

getKbest = SelectKBest(chi2, k = 100)
现在

print(np.asarray(vect.get_feature_names())[getKbest.get_support()])

应该为您提供前100个功能。试试这个。

sklearn的GridSearchCV有一些非常简洁的方法可以为您提供最佳的功能集。例如,考虑下面的代码

pipeline = Pipeline([
    ('vect', TfidfVectorizer(stop_words='english',sublinear_tf=True)),
    ('clf', LogisticRegression())
    ])

    parameters = {
        'vect__max_df': (0.25, 0.5, 0.6, 0.7, 1.0),
        'vect__ngram_range': ((1, 1), (1, 2), (2,3), (1,3), (1,4), (1,5)),
        'vect__use_idf': (True, False),
        'clf__C': (0.1, 1, 10, 20, 30)
    }

这里的参数数组包含了我需要考虑的所有不同的参数。注意使用if-vect\uuu max\u df。max_df是我的矢量器使用的一个实际键,它是我的特征选择器。所以

'vect__max_df': (0.25, 0.5, 0.6, 0.7, 1.0),
实际上指定我要为我的矢量器尝试上述5个值。其他人也是如此。请注意,我是如何将向量器绑定到键“vect”和分类器绑定到键“clf”的。你能看到图案吗?继续

    traindf = pd.read_json('../../data/train.json')

    traindf['ingredients_clean_string'] = [' , '.join(z).strip() for z in traindf['ingredients']]  

    traindf['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in traindf['ingredients']]       

    X, y = traindf['ingredients_string'], traindf['cuisine'].as_matrix()

    X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)

    grid_search = GridSearchCV(pipeline, parameters, n_jobs=3, verbose=1, scoring='accuracy')
    grid_search.fit(X_train, y_train)

    print ('best score: %0.3f' % grid_search.best_score_)
    print ('best parameters set:')

    bestParameters = grid_search.best_estimator_.get_params()

    for param_name in sorted(parameters.keys()):
        print ('\t %s: %r' % (param_name, bestParameters[param_name]))

    predictions = grid_search.predict(X_test)
    print ('Accuracy:', accuracy_score(y_test, predictions))
    print ('Confusion Matrix:', confusion_matrix(y_test, predictions))
    print ('Classification Report:', classification_report(y_test, predictions))
请注意,bestParameters数组将为我提供在创建管道时指定的所有选项中最好的一组参数

希望这有帮助

编辑:获取所选功能的列表

因此,一旦您拥有了最佳的参数集,就可以使用这些参数值创建向量器和分类器

vect = TfidfVectorizer('''use the best parameters here''')
然后你基本上要再次训练这个矢量器。这样,矢量器将从您的训练集中选择某些功能

traindf = pd.read_json('../../data/train.json')

        traindf['ingredients_clean_string'] = [' , '.join(z).strip() for z in traindf['ingredients']]  

        traindf['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in traindf['ingredients']]       

        X, y = traindf['ingredients_string'], traindf['cuisine'].as_matrix()

        X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)

       termDocMatrix = vect.fit_transform(X_train, y_train)
现在,termDocMatrix具有所有选定的功能。此外,还可以使用矢量器获取要素名称。假设您想要获得前100个功能。比较的标准是卡方分数

getKbest = SelectKBest(chi2, k = 100)
现在

print(np.asarray(vect.get_feature_names())[getKbest.get_support()])

应该为您提供前100个功能。试试这个。

什么是您的功能选择器?什么是您的功能选择器?感谢您对GridSearch的详细解释。但这并不能回答我的问题。我的问题是,如果我使用任何算法进行特征选择,我是否应该更多地关注模型的准确性?例如,sk学习特征选择方法()将随机森林、逻辑回归等列为标准方法。如何在两种基于模型的特征选择方法之间进行选择?根据准确度进行选择?准确度是一个很好的衡量标准,但您还应该查看其他参数,如ROC曲线、精度、召回率和f度量。根据您试图解决的问题,其中一个或多个参数可能很重要。这就是为什么它有助于创建管道,以便您可以比较不同的模型。准确性是最直接的一个。顺便问一下,你想解决哪个问题?您的用例是什么?另外,当您说“最终目标不是提高准确性,而是只获得重要的特性”时,您是否真的希望获得性能最佳的模型所选择的特性?i、 你想找出表现最好的模型所关注的“事物”吗?这是我的用例:我的响应变量是二进制的。我的功能是数字的(它们是特定的产品功能,属性值是用户使用这些属性的次数),我希望找到那些影响响应变量的功能为1。我不打算在将来将用户分类为1或0。我只是对模型返回的重要特性进行分类。我还没有尝试实现您建议的功能,但快速的观察告诉我,所有这些都与文本分析有关。我的问题不是文本分析问题,感谢GridSearch的详细解释。但这并不能回答我的问题。我的问题是,如果我使用任何算法进行特征选择,我是否应该更多地关注模型的准确性?例如,sk学习特征选择方法()将随机森林、逻辑回归等列为标准方法。如何在两种基于模型的特征选择方法之间进行选择?根据准确度进行选择?准确度是一个很好的衡量标准,但您还应该查看其他参数,如ROC曲线、精度、召回率和f度量。根据您试图解决的问题,其中一个或多个参数可能很重要。这就是为什么它有助于创建管道,以便您可以比较不同的模型。准确性是最直接的一个。顺便问一下,你想解决哪个问题?你的使用案例是什么?还有,当你说“最终目标不是提高准确性,而是只获得重要的特性”时,你是这样说的吗