sklearn:sklearn.feature_selection的SelectFromModel函数的简介、使用方法之详细攻略(二)

简介: sklearn:sklearn.feature_selection的SelectFromModel函数的简介、使用方法之详细攻略

2、L1-based feature selection


>>> from sklearn.svm import LinearSVC

>>> from sklearn.datasets import load_iris

>>> from sklearn.feature_selection import SelectFromModel

>>> X, y = load_iris(return_X_y=True)

>>> X.shape

(150, 4)

>>> lsvc = LinearSVC(C=0.01, penalty="l1", dual=False).fit(X, y)

>>> model = SelectFromModel(lsvc, prefit=True)

>>> X_new = model.transform(X)

>>> X_new.shape

(150, 3)


3、Tree-based feature selection


>>> from sklearn.ensemble import ExtraTreesClassifier

>>> from sklearn.datasets import load_iris

>>> from sklearn.feature_selection import SelectFromModel

>>> X, y = load_iris(return_X_y=True)

>>> X.shape

(150, 4)

>>> clf = ExtraTreesClassifier(n_estimators=50)

>>> clf = clf.fit(X, y)

>>> clf.feature_importances_  

array([ 0.04...,  0.05...,  0.4...,  0.4...])

>>> model = SelectFromModel(clf, prefit=True)

>>> X_new = model.transform(X)

>>> X_new.shape              

(150, 2)



SelectFromModel函数的使用方法


1、SelectFromModel的原生代码

class SelectFromModel Found at: sklearn.feature_selection.from_model

class SelectFromModel(BaseEstimator, SelectorMixin, MetaEstimatorMixin):

   """Meta-transformer for selecting features based on importance weights.

 

   .. versionadded:: 0.17

 

   Parameters

   ----------

   estimator : object

   The base estimator from which the transformer is built.

   This can be both a fitted (if ``prefit`` is set to True)

   or a non-fitted estimator. The estimator must have either a

   ``feature_importances_`` or ``coef_`` attribute after fitting.

 

   threshold : string, float, optional default None

   The threshold value to use for feature selection. Features whose

   importance is greater or equal are kept while the others are

   discarded. If "median" (resp. "mean"), then the ``threshold`` value is

   the median (resp. the mean) of the feature importances. A scaling

   factor (e.g., "1.25*mean") may also be used. If None and if the

   estimator has a parameter penalty set to l1, either explicitly

   or implicitly (e.g, Lasso), the threshold used is 1e-5.

   Otherwise, "mean" is used by default.

 

   prefit : bool, default False

   Whether a prefit model is expected to be passed into the constructor

   directly or not. If True, ``transform`` must be called directly

   and SelectFromModel cannot be used with ``cross_val_score``,

   ``GridSearchCV`` and similar utilities that clone the estimator.

   Otherwise train the model using ``fit`` and then ``transform`` to do

   feature selection.

 

   norm_order : non-zero int, inf, -inf, default 1

   Order of the norm used to filter the vectors of coefficients below

   ``threshold`` in the case where the ``coef_`` attribute of the

   estimator is of dimension 2.

 

   Attributes

   ----------

   estimator_ : an estimator

   The base estimator from which the transformer is built.

   This is stored only when a non-fitted estimator is passed to the

   ``SelectFromModel``, i.e when prefit is False.

 

   threshold_ : float

   The threshold value used for feature selection.

   """

   def __init__(self, estimator, threshold=None, prefit=False,

    norm_order=1):

       self.estimator = estimator

       self.threshold = threshold

       self.prefit = prefit

       self.norm_order = norm_order

 

   def _get_support_mask(self):

   # SelectFromModel can directly call on transform.

       if self.prefit:

           estimator = self.estimator

       elif hasattr(self, 'estimator_'):

           estimator = self.estimator_

       else:

           raise ValueError(

               'Either fit SelectFromModel before transform or set "prefit='

               'True" and pass a fitted estimator to the constructor.')

       scores = _get_feature_importances(estimator, self.norm_order)

       threshold = _calculate_threshold(estimator, scores, self.threshold)

       return scores >= threshold

 

   def fit(self, X, y=None, **fit_params):

       """Fit the SelectFromModel meta-transformer.

       Parameters

       ----------

       X : array-like of shape (n_samples, n_features)

           The training input samples.

       y : array-like, shape (n_samples,)

           The target values (integers that correspond to classes in

           classification, real numbers in regression).

       **fit_params : Other estimator specific parameters

       Returns

       -------

       self : object

           Returns self.

       """

       if self.prefit:

           raise NotFittedError(

               "Since 'prefit=True', call transform directly")

       self.estimator_ = clone(self.estimator)

       self.estimator_.fit(X, y, **fit_params)

       return self

 

   @property

   def threshold_(self):

       scores = _get_feature_importances(self.estimator_, self.norm_order)

       return _calculate_threshold(self.estimator, scores, self.threshold)

 

   @if_delegate_has_method('estimator')

   def partial_fit(self, X, y=None, **fit_params):

       """Fit the SelectFromModel meta-transformer only once.

       Parameters

       ----------

       X : array-like of shape (n_samples, n_features)

           The training input samples.

       y : array-like, shape (n_samples,)

           The target values (integers that correspond to classes in

           classification, real numbers in regression).

       **fit_params : Other estimator specific parameters

       Returns

       -------

       self : object

           Returns self.

       """

       if self.prefit:

           raise NotFittedError(

               "Since 'prefit=True', call transform directly")

       if not hasattr(self, "estimator_"):

           self.estimator_ = clone(self.estimator)

       self.estimator_.partial_fit(X, y, **fit_params)

       return self



相关文章
|
8月前
|
机器学习/深度学习 算法 PyTorch
从零开始深度学习:全连接层、损失函数与梯度下降的详尽指南
在深度学习的领域,全连接层、损失函数与梯度下降是三块重要的基石。如果你正在踏上深度学习的旅程,理解它们是迈向成功的第一步。这篇文章将从概念到代码、从基础到进阶,详细剖析这三个主题,帮助你从小白成长为能够解决实际问题的开发者。
|
11月前
|
NoSQL 容灾 MongoDB
MongoDB主备副本集方案:两台服务器使用非对称部署的方式实现高可用与容灾备份
在资源受限的情况下,为了实现MongoDB的高可用性,本文探讨了两种在两台服务器上部署MongoDB的方案。方案一是通过主备身份轮换,即一台服务器作为主节点,另一台同时部署备节点和仲裁节点;方案二是利用`priority`设置实现自动主备切换。两者相比,方案二自动化程度更高,适合追求快速故障恢复的场景,而方案一则提供了更多的手动控制选项。文章最后对比了这两种方案与标准三节点副本集的优缺点,指出三节点方案在高可用性和数据一致性方面表现更佳。
855 5
|
机器学习/深度学习 人工智能 算法
【果蔬识别系统】Python+卷积神经网络算法+人工智能+深度学习+计算机毕设项目+Django网页界面平台
【果蔬识别系统】Python+卷积神经网络算法+人工智能+深度学习+计算机毕设项目+Django网页界面平台。果蔬识别系统,本系统使用Python作为主要开发语言,通过收集了12种常见的水果和蔬菜('土豆', '圣女果', '大白菜', '大葱', '梨', '胡萝卜', '芒果', '苹果', '西红柿', '韭菜', '香蕉', '黄瓜'),然后基于TensorFlow库搭建CNN卷积神经网络算法模型,然后对数据集进行训练,最后得到一个识别精度较高的算法模型,然后将其保存为h5格式的本地文件方便后期调用。再使用Django框架搭建Web网页平台操作界面,实现用户上传一张果蔬图片识别其名称。
321 0
【果蔬识别系统】Python+卷积神经网络算法+人工智能+深度学习+计算机毕设项目+Django网页界面平台
|
关系型数据库 MySQL Apache
Discuz贴吧建站的搭建及维护(windows系统)
Discuz贴吧建站的搭建及维护(windows系统)
394 0
|
数据采集 数据可视化 数据挖掘
Python爬虫之Pandas数据处理技术详解
Python爬虫之Pandas数据处理技术详解
|
NoSQL Java Redis
Redis 从入门到精通之Redis操作删除指定Key
删除redis 可以使用Del、unlinke。推荐使用unlink。Redis是一个内存数据库,删除key会立即释放内存,因此要慎重删除,避免误删重要数据。
6966 124
|
Linux Go 调度
谈谈对 GMP 的简单认识
犹记得最开始学习 golang 的时候,大佬们分享 GMP 模型的时候,总感觉云里雾里,听了半天,并没有一个很清晰的概念,不知 xmd 是否会有这样的体会
282 0
|
Web App开发 设计模式 前端开发
实战,Spring Boot整合GraphQL实现动态字段接口!
实战,Spring Boot整合GraphQL实现动态字段接口!
641 0
|
C++
C++ 控制台窗口中MessageBox() 的用法
C++ 控制台窗口中MessageBox() 的用法
508 0
|
缓存 并行计算 算法
浅析 Fork/Join 基本概念和实战
在 JDK 1.7 版本中提供了 Fork/Join 并行执行任务框架,它主要的作用是把大任务分割成若干个小任务,再对每个小任务得到的结果进行汇总,此种开发方法也叫做分治编程,分治编程可以极大的利用 CPU 资源,提高任务执行效率。
289 0
浅析 Fork/Join 基本概念和实战