使用 SKLearn 构建模型时忽略列 [英] Ignore a column while building a model with SKLearn

查看:51
本文介绍了使用 SKLearn 构建模型时忽略列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With R, one can ignore a variable (column) while building a model with the following syntax:

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

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

It's very handy when your data set contains indexes or ID.

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

How would you do that with SKlearn in python, assuming your data are Pandas data frames ?

推荐答案

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

So this is from my own code I used to do some prediction on StackOverflow last year:

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])

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

So if we wanted a subset of the features for classification I could have done this:

# 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数据帧中列的子集,因此我们可以构建一个新列表或删除一个值并将其用于选择

So the idea here is that a list can be used to select a subset of the columns in the pandas dataframe, as such we can construct a new list or remove a value and use this for selection

我不确定如何使用 numpy 数组轻松完成此操作,因为索引的方式不同.

I'm not sure how you could do this easily using numpy arrays as indexing is done differently.

这篇关于使用 SKLearn 构建模型时忽略列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆