特征选择和预测

2024-02-18

from sklearn.feature_selection import RFECV
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_predict, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_iris

我有 X 和 Y 数据。

data = load_iris()    
X = data.data
Y = data.target 

我想使用 k 倍验证方法来实现 RFECV 特征选择和预测。

从答案@更正代码https://stackoverflow.com/users/3374996/vivek-kumar https://stackoverflow.com/users/3374996/vivek-kumar

clf = RandomForestClassifier()

kf = KFold(n_splits=2, shuffle=True, random_state=0)  

estimators = [('standardize' , StandardScaler()),
              ('clf', clf)]

class Mypipeline(Pipeline):
    @property
    def coef_(self):
        return self._final_estimator.coef_
    @property
    def feature_importances_(self):
        return self._final_estimator.feature_importances_ 

pipeline = Mypipeline(estimators)

rfecv = RFECV(estimator=pipeline, cv=kf, scoring='accuracy', verbose=10)
rfecv_data = rfecv.fit(X, Y)

print ('no. of selected features =', rfecv_data.n_features_) 

编辑(对于剩余的少量):

X_new = rfecv.transform(X)
print X_new.shape

y_predicts = cross_val_predict(clf, X_new, Y, cv=kf)
accuracy = accuracy_score(Y, y_predicts)
print ('accuracy =', accuracy)

不要将 StandardScaler 和 RFECV 包装在同一管道中,而是对 StandardScaler 和 RandomForestClassifier 执行此操作,并将该管道作为估计器传递给 RFECV。在此不会泄露任何 traininf 信息。

estimators = [('standardize' , StandardScaler()),
              ('clf', RandomForestClassifier())]

pipeline = Pipeline(estimators)


rfecv = RFECV(estimator=pipeline, scoring='accuracy')
rfecv_data = rfecv.fit(X, Y)

Update: 关于错误'RuntimeError: The classifier does not expose "coef_" or "feature_importances_" attributes'

是的,这是 scikit-learn 管道中的一个已知问题。你可以看看我的另一个在这里回答 https://stackoverflow.com/a/51418655/3374996更多详细信息并使用我在那里创建的新管道。

像这样定义自定义管道:

class Mypipeline(Pipeline):
    @property
    def coef_(self):
        return self._final_estimator.coef_
    @property
    def feature_importances_(self):
        return self._final_estimator.feature_importances_ 

并使用它:

pipeline = Mypipeline(estimators)

rfecv = RFECV(estimator=pipeline, scoring='accuracy')
rfecv_data = rfecv.fit(X, Y)

Update 2:

@brute,对于您的数据和代码,算法在一分钟内即可在我的电脑上完成。这是我使用的完整代码:

import numpy as np
import glob
from sklearn.utils import resample
files = glob.glob('/home/Downloads/Untitled Folder/*') 
outs = [] 
for fi in files: 
    data = np.genfromtxt(fi, delimiter='|', dtype=float) 
    data = data[~np.isnan(data).any(axis=1)] 
    data = resample(data, replace=False, n_samples=1800, random_state=0) 
    outs.append(data) 

X = np.vstack(outs) 
print X.shape 
Y = np.repeat([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1800) 
print Y.shape

#from sklearn.utils import shuffle
#X, Y = shuffle(X, Y, random_state=0)

from sklearn.feature_selection import RFECV
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline

clf = RandomForestClassifier()

kf = KFold(n_splits=10, shuffle=True, random_state=0)  

estimators = [('standardize' , StandardScaler()),
              ('clf', RandomForestClassifier())]

class Mypipeline(Pipeline):
    @property
    def coef_(self):
        return self._final_estimator.coef_
    @property
    def feature_importances_(self):
        return self._final_estimator.feature_importances_ 

pipeline = Mypipeline(estimators)

rfecv = RFECV(estimator=pipeline, scoring='accuracy', verbose=10)
rfecv_data = rfecv.fit(X, Y)

print ('no. of selected features =', rfecv_data.n_features_) 

Update 3:对于 cross_val_predict

X_new = rfecv.transform(X)
print X_new.shape

# Here change clf to pipeline, 
# because RFECV has found features according to scaled data,
# which is not present when you pass clf 
y_predicts = cross_val_predict(pipeline, X_new, Y, cv=kf)
accuracy = accuracy_score(Y, y_predicts)
print ('accuracy =', accuracy)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

特征选择和预测 的相关文章

  • sklearn 估计器管道的参数无效

    我正在实现 O Reilly 书中的一个示例 Python 机器学习简介 使用 Python 2 7 和 sklearn 0 16 我正在使用的代码 pipe make pipeline TfidfVectorizer LogisticRe
  • 混淆矩阵不支持多标签指示符

    multilabel indicator is not supported是我在尝试运行时收到的错误消息 confusion matrix y test predictions y test is a DataFrame其形状为 Horse
  • 使用 SciKit-learn 和大型数据集进行文本分类

    首先 我昨天开始学习Python 我正在尝试使用 SciKit 和大型数据集 250 000 条推文 进行文本分类 对于该算法 每条推文都将表示为 4000 x 1 向量 因此这意味着输入为 250 000 行和 4000 列 当我尝试在
  • 精度类型

    使用 keras 库获得的精度如下 model compile optimizer sgd loss mse metrics tf keras metrics Precision sklearn 计算出的哪种精度与 keras 计算出的精度
  • 与 GridSearchCV 的并行错误,与其他方法一起工作正常

    我使用 GridSearchCV 时遇到以下问题 它在使用时给我一个并行错误n jobs gt 1 同时n jobs gt 1与 RadonmForestClassifier 等单一模型配合良好 下面是一个显示错误的简单工作示例 train
  • Scikit Learn GridSearchCV 无需交叉验证(无监督学习)

    是否可以在没有交叉验证的情况下使用 GridSearchCV 我正在尝试通过网格搜索优化 KMeans 聚类中的聚类数量 因此我不需要或想要交叉验证 The 文档 http scikit learn org stable modules g
  • 如何使用FeatureUnion转换PipeLine中的多个特征?

    我有一个 pandas 数据框 其中包含有关用户发送的消息的信息 对于我的模型 我感兴趣的是预测消息的缺失收件人 即给定消息的收件人 A B C 我想预测还有谁应该成为收件人的一部分 我正在使用 OneVsRestClassifier 和
  • 使用 joblib 加载 pickled scikit-learn 模型时出现 KeyError

    我有一个对象 其中包含两个scikit learn模型 一个IsolationForest and a RandomForestClassifier 我想对其进行 pickle 然后将其解开并用于生成预测 除了两个模型之外 该对象还包含几个
  • 生成具有相同类别的终端叶子的决策树

    我对决策树比较陌生 并且一直坚持我的决策树算法 我使用交叉验证和参数调整来优化以下示例的分类 https medium com haydar ai learning data science day 22 cross validation
  • 使用 scikit-learn 从 GridSearchCV 获取进度更新

    我目前正在 Python 中实现支持向量回归 其中我通过 GridSearchCV 估计参数 C 和 gamma 我最初从大约 400 个 C 和 gamma 的组合中进行搜索 这是一个非常详尽的搜索 现在已经在我的计算机上运行了一个多小时
  • sklearn 中组件解释的偏最小二乘方差

    我正在尝试使用 sklearn 中的代码执行 PLSRegression 并且我想保留那些解释一定程度方差的组件 例如 PCA 中的组件 有没有办法知道 PLS 中每个分量解释了多少方差 我也有计算每个组件的解释方差的相同要求 我是 PLS
  • 如何为DNA序列生成一种热编码?

    我想为一组 DNA 序列生成一个热编码 例如 序列ACGTCCA可以以转置方式表示如下 但下面的代码将以水平方式生成一种热门编码 我更喜欢以垂直方式生成 谁能帮我 ACGTCCA 1000001 A 0100110 C 0010000 G
  • 尝试校准keras模型

    我正在尝试通过 Sklearn 实现来校准我的 CNN 模型CalibratedClassifierCV 尝试将其包装为KerasClassifier并覆盖预测功能但没有成功 有人可以说我做错了什么吗 这是模型代码 def create m
  • 机器学习的周期性数据(例如度角 -> 179 与 -179 相差 2)

    我使用 Python 进行核密度估计 并使用高斯混合模型对多维数据样本的可能性进行排名 每一条数据都是一个角度 我不确定如何处理机器学习的角度数据的周期性 首先 我通过添加 360 来删除所有负角 因此所有负角都变成了正角 179 变成了
  • “KMeans”对象没有属性“k”

    我使用 Yellowbrick 包绘制数据集的肘部曲线 以使用 KMeans 作为模型找到数据集的最佳簇数 我正在使用 Scikit learn KMeans 和 Yellowbrick kelbowvisualizer 函数 生成了肘部曲
  • Sklearn SVM:SVR 和 SVC,为每个输入获得相同的预测

    这是代码的粘贴 支持向量机示例代码 http pastebin com dvWy5SpE 我查看了这个问题的其他几个答案 看起来这个问题的特定迭代有点不同 首先 我的输入被标准化 每个点有五个输入 这些值的大小都合理 健康的 0 5 秒和
  • 如何将 sklearn.naive_bayes 与(多个)分类特征一起使用? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我想学习朴素贝叶斯模型来解决类为布尔值的问题 有些特征是布尔型的 但其他特征是分类型的 并且可以采用少量值 5 如果我所有的功能都是布尔值
  • 为什么 scikit learn 的平均精度分数返回 nan?

    我的 Keras 模型旨在接收两个输入时间序列 将它们连接起来 通过 LSTM 提供它们 并在下一个时间步骤中进行多标签预测 有 50 个训练样本 每个样本有 24 个时间步 每个样本有 5625 个标签 有 12 个验证样本 每个样本有
  • 如何向 scikit-learn KD 树添加/删除数据点?

    我想知道是否可以在创建 scikit learn KDTree 实例后添加或删除数据点 例如 from sklearn neighbors import KDTree import numpy as np X np array 1 1 2
  • 使用纬度/经度对的自定义距离度量进行聚类

    我试图为 scikit learn DBSCAN 实现指定一个自定义聚类函数 def geodistance latLngA latLngB print latLngA latLngB return vincenty latLngA lat

随机推荐