2017-08-10 31 views
1

这是我的数据[作为熊猫DF]:字典散列存储器错误和特征散列浮子错误

打印(X_train [numeric_predictors + categorical_predictors]。头()):

 bathrooms bedrooms price      building_id \ 
10   1.5  3.0 3000.0 53a5b119ba8f7b61d4e010512e0dfc85 
10000   1.0  2.0 5465.0 c5c8a357cba207596b04d1afd1e4f130 
100004  1.0  1.0 2850.0 c3ba40552e2120b0acfc3cb5730bb2aa 
100007  1.0  1.0 3275.0 28d9ad350afeaab8027513a3e52ac8d5 
100013  1.0  4.0 3350.0         0 

99993   1.0  0.0 3350.0 ad67f6181a49bde19218929b401b31b7 
99994   1.0  2.0 2200.0 5173052db6efc0caaa4d817112a70f32 


           manager_id 
10  5ba989232d0489da1b5f2c45f6688adc 
10000 7533621a882f71e25173b27e3139d83d 
100004 d9039c43983f6e564b1482b273bd7b01 
100007 1067e078446a7897d2da493d2f741316 
100013 98e13ad4b495b9613cef886d79a6291f 
... 
99993 9fd3af5b2d23951e028059e8940a55d7 
99994 d7f57128272bfd82e33a61999b5f4c42 

最后两列是分类预测指标。

同样,在打印熊猫系列X_train [目标]:

10  medium 
10000  low 
100004  high 
100007  low 
100013  low 
... 
99993  low 
99994  low 

我试图用一个管道模板,并用散列vectorizers得到一个错误。

首先,这里是我的字典散列器,给了我一个的MemoryError:

from sklearn.feature_extraction import DictVectorizer 

dv = DictVectorizer(sparse=False) 
feature_dict = X_train[categorical_predictors].to_dict(orient='records') 
dv.fit(feature_dict) 
out = pd.DataFrame(
    dv.transform(feature_dict), 
    columns = dv.feature_names_ 
) 

所以在下一个单元中,我使用下面的代码作为我的特点散列编码器:

from sklearn.feature_extraction import FeatureHasher 

fh = FeatureHasher(n_features=2) 
feature_dict = X_train[categorical_predictors].to_dict(orient='records') 
fh.fit(feature_dict) 
out = pd.DataFrame(fh.transform(feature_dict).toarray()) 
#print out.head() 

的评论out print line为我提供了一个DataFrame,其中包含每行2个单元格中包含-1.0,0.0或1.0浮点数的特征行。

这里是我的矢量器放在一起字典&功能散列:

from sklearn.base import BaseEstimator, TransformerMixin 
from sklearn.feature_extraction import FeatureHasher, DictVectorizer 

class MyVectorizer(BaseEstimator, TransformerMixin): 
    """ 
    Vectorize a set of categorical variables 
    """ 

    def __init__(self, cols, hashing=None): 
     """ 
     args: 
      cols: a list of column names of the categorical variables 
      hashing: 
       If None, then vectorization is a simple one-hot-encoding. 
       If an integer, then hashing is the number of features in the output. 
     """ 
     self.cols = cols 
     self.hashing = hashing 

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

     data = X[self.cols] 

     # Choose a vectorizer 
     if self.hashing is None: 
      self.myvec = DictVectorizer(sparse=False) 
     else: 
      self.myvec = FeatureHasher(n_features = self.hashing) 

     self.myvec.fit(X[self.cols].to_dict(orient='records')) 
     return self 

    def transform(self, X): 

     # Vectorize Input 
     if self.hashing is None: 
      return pd.DataFrame(
       self.myvec.transform(X[self.cols].to_dict(orient='records')), 
       columns = self.myvec.feature_names_ 
      ) 
     else: 
      return pd.DataFrame(
       self.myvec.transform(X[self.cols].to_dict(orient='records')).toarray() 
      ) 

我把它一起在我的流水线:

from sklearn.pipeline import Pipeline 
from sklearn.preprocessing import StandardScaler 
from sklearn.pipeline import FeatureUnion 

pipeline = Pipeline([ 
    ('preprocess', FeatureUnion([ 
     ('numeric', Pipeline([ 
      ('scale', StandardScaler()) 
     ]) 
     ), 
     ('categorical', Pipeline([ 
      ('vectorize', MyVectorizer(cols=['categorical_predictors'], hashing=None)) 
     ]) 
     ) 
    ])), 
    ('predict', MultinomialNB(alphas)) 
]) 

和alpha参数:

alphas = { 
    'predict__alpha': [.01, .1, 1, 2, 10] 
} 

和使用gridsearchCV,当我在这里的第三行得到一个错误时:

print X_train.head(), train_data[target] 
grid_search = GridSearchCV(pipeline, param_grid=alphas,scoring='accuracy') 
grid_search.fit(X_train[numeric_predictors + categorical_predictors], X_train[target]) 
grid_search.best_params_ 

ValueError异常:无法将字符串转换为float:d7f57128272bfd82e33a61999b5f4c42

+1

你可以添加一些发生此错误的示例数据吗?另请编辑代码以提供完整的代码,并按顺序使用,以便我们轻松复制粘贴和调试。 –

+0

嗨,我按你的建议。请看看,让我知道,谢谢! –

+0

请帮助我仍然收到此错误。 –

回答

2

的错误是由于StandardScaler。您正在将所有数据发送给它,这是错误的。在您的管线中,在FeatureUnion部分中,您已选择MyVectorizer的分类列,但未对StandardScaler进行任何选择,因此所有列都进入该列,这些列正在导致错误。另外,由于内部管线仅由单个步骤组成,因此不需要管线。

作为第一步,改变管道:

pipeline = Pipeline([ 
    ('preprocess', FeatureUnion([ 
     ('scale', StandardScaler()), 
     ('vectorize', MyVectorizer(cols=['categorical_predictors'], hashing=None)) 
    ])), 
    ('predict', MultinomialNB()) 
]) 

这将仍然抛出了同样的错误,但其寻找更复杂了。

现在我们所需要的是可以选择要提供给StandardScaler的列(数字列)的东西,以便不抛出错误。

我们可以在很多方面做到这一点,但我会遵循您的编码风格,并且会随着更改而创建一个新类MyScaler

class MyScaler(BaseEstimator, TransformerMixin): 

    def __init__(self, cols): 
     self.cols = cols 

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

     self.scaler = StandardScaler() 
     self.scaler.fit(X[self.cols]) 
     return self 

    def transform(self, X): 
     return self.scaler.transform(X[self.cols]) 

,然后更改管道:

numeric_predictors=['bathrooms','bedrooms','price'] 
categorical_predictors = ['building_id','manager_id'] 

pipeline = Pipeline([ 
    ('preprocess', FeatureUnion([ 
     ('scale', MyScaler(cols=numeric_predictors)), 
     ('vectorize', MyVectorizer(cols=['categorical_predictors'], hashing=None)) 
    ])), 
    ('predict', MultinomialNB()) 
]) 

还是那么它会抛出错误,因为你给categorical_predictors作为一个字符串MyVectorizer,而不是作为一个列表。将其更改为喜欢我的MyScaler做了:改变

MyVectorizer(cols=['categorical_predictors'], hashing=None)) 

到: -

MyVectorizer(cols=categorical_predictors, hashing=None) 

现在你的代码是准备好语法执行。但是现在您已经使用MultinomialNB()作为您的预测因子,它只需要特征中的正值。但是,由于StandardScaler将数据缩放为零的意思,它会将一些值转换为负值,并且您的代码再次失效。这件事你需要决定怎么做..也许把它改成MinMaxScaler。

+0

您好,我已经清理了一下,并且仍然遇到类似的问题:https://stackoverflow.com/questions/45723699/valueerror-in-pipeline-featurehasher-not-working –