【问题标题】:Ignore a column while building a model with SKLearn使用 SKLearn 构建模型时忽略列
【发布时间】:2014-06-17 19:34:37
【问题描述】:

使用 R,可以在使用以下语法构建模型时忽略变量(列):

model = lm(dependant.variable ~ . - ignored.variable, data=my.training,set)

当您的数据集包含索引或 ID 时非常方便。

假设您的数据是 Pandas 数据框,您将如何在 python 中使用 SKlearn 来做到这一点?

【问题讨论】:

  • 您传递的数据将是 numpy 数组或者可能是 pandas(分解为 numpy 数组),您可以索引并选择感兴趣的列并将这些传递给 lm 函数参见 numpy docspandas docs
  • 嗯,我有 300 多列。如果我必须手动继续,我宁愿忽略 1 列而不是添加 299。
  • 在 pandas 中你可以做 list(df.columns) - ignore_col 这不会太冗长
  • 如何将保留列的列表输入到 SKlearn 中?
  • 您通常调用 fit 将数据和标签作为 X、y 参数传递,例如clf = LogisticRegression() 然后 clf.fit(X,y),如果使用 pandas,那么最后一行将变为 clf.fit(df[list(df.columns) - ignoreCol].values, df.target.values),这是一个伪示例,但它应该演示我的意思,这里有一个使用带有 sklearn 的 pandas 的示例:python.dzone.com/articles/python-making-scikit-learn-and

标签: python scikit-learn


【解决方案1】:

所以这是我自己的代码,我去年在 StackOverflow 上做过一些预测:

from __future__ import division
from pandas import *
from sklearn import cross_validation
from sklearn import metrics
from sklearn.ensemble import GradientBoostingClassifier

basic_feature_names = [ 'BodyLength'
                      , 'NumTags'
                      , 'OwnerUndeletedAnswerCountAtPostTime'
                      , 'ReputationAtPostCreation'
                      , 'TitleLength'
                      , 'UserAge' ]

fea = # extract the features - removed for brevity
# construct our classifier
clf = GradientBoostingClassifier(n_estimators=num_estimators, random_state=0)
# now fit
clf.fit(fea[basic_feature_names], orig_data['OpenStatusMod'].values)
# now 
priv_fea = # this was my test dataset
# now calculate the predicted classes
pred = clf.predict(priv_fea[basic_feature_names])

因此,如果我们想要分类特征的子集,我可以这样做:

# want to train using fewer features so remove 'BodyLength'
basic_feature_names.remove('BodyLength')

clf.fit(fea[basic_feature_names], orig_data['OpenStatusMod'].values)

所以这里的想法是可以使用列表来选择 pandas 数据框中列的子集,因此我们可以构建一个新列表或删除一个值并使用它进行选择

我不确定如何使用 numpy 数组轻松做到这一点,因为索引的完成方式不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 2019-12-16
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多