2012-09-16 6 views
28

estoy recibiendo el siguiente error cuando se realiza la función de selección recursiva con validación cruzada:TypeError: sólo matrices de enteros con un elemento se pueden convertir a un índice

Traceback (most recent call last): 
    File "/Users/.../srl/main.py", line 32, in <module> 
    argident_sys.train_classifier() 
    File "/Users/.../srl/identification.py", line 194, in train_classifier 
    feat_selector.fit(train_argcands_feats,train_argcands_target) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sklearn/feature_selection/rfe.py", line 298, in fit 
    ranking_ = rfe.fit(X[train], y[train]).ranking_ 
TypeError: only integer arrays with one element can be converted to an index 

El código que genera el error es la siguiente :

def train_classifier(self): 

    # Get the argument candidates 
    argcands = self.get_argcands(self.reader) 

    # Extract the necessary features from the argument candidates 
    train_argcands_feats = [] 
    train_argcands_target = [] 

    for argcand in argcands: 
     train_argcands_feats.append(self.extract_features(argcand)) 
     if argcand["info"]["label"] == "NULL": 
      train_argcands_target.append("NULL") 
     else: 
      train_argcands_target.append("ARG") 

    # Transform the features to the format required by the classifier 
    self.feat_vectorizer = DictVectorizer() 
    train_argcands_feats = self.feat_vectorizer.fit_transform(train_argcands_feats) 

    # Transform the target labels to the format required by the classifier 
    self.target_names = list(set(train_argcands_target)) 
    train_argcands_target = [self.target_names.index(target) for target in train_argcands_target] 

    ## Train the appropriate supervised model  

    # Recursive Feature Elimination 
    self.classifier = LogisticRegression() 
    feat_selector = RFECV(estimator=self.classifier, step=1, cv=StratifiedKFold(train_argcands_target, 10)) 

    feat_selector.fit(train_argcands_feats,train_argcands_target) 

    print feat_selector.n_features_ 
    print feat_selector.support_ 
    print feat_selector.ranking_ 
    print feat_selector.cv_scores_ 

    return 

sé que también debería realizar GridSearch de los parámetros del clasificador de regresión logística, pero no creo que ese es el origen del error (o no?).

Debo mencionar que estoy probando con alrededor de 50 características, y casi todas son categóricas (es por eso que utilizo DictVectorizer para transformarlas adecuadamente).

Cualquier ayuda o guía que pueda darme es más que bienvenida. ¡Gracias!

EDITAR

He aquí algunos ejemplos de datos de entrenamiento:

train_argcands_feats = [{'head_lemma': u'Bras\xedlia', 'head': u'Bras\xedlia', 'head_postag': u'PROP'}, {'head_lemma': u'Pesquisa_Datafolha', 'head': u'Pesquisa_Datafolha', 'head_postag': u'N'}, {'head_lemma': u'dado', 'head': u'dado', 'head_postag': u'N'}, {'head_lemma': u'postura', 'head': u'postura', 'head_postag': u'N'}, {'head_lemma': u'maioria', 'head': u'maioria', 'head_postag': u'N'}, {'head_lemma': u'querer', 'head': u'quer', 'head_postag': u'V-FIN'}, {'head_lemma': u'PT', 'head': u'PT', 'head_postag': u'PROP'}, {'head_lemma': u'participar', 'head': u'participando', 'head_postag': u'V-GER'}, {'head_lemma': u'surpreendente', 'head': u'supreendente', 'head_postag': u'ADJ'}, {'head_lemma': u'Bras\xedlia', 'head': u'Bras\xedlia', 'head_postag': u'PROP'}, {'head_lemma': u'Pesquisa_Datafolha', 'head': u'Pesquisa_Datafolha', 'head_postag': u'N'}, {'head_lemma': u'revelar', 'head': u'revela', 'head_postag': u'V-FIN'}, {'head_lemma': u'recusar', 'head': u'recusando', 'head_postag': u'V-GER'}, {'head_lemma': u'maioria', 'head': u'maioria', 'head_postag': u'N'}, {'head_lemma': u'PT', 'head': u'PT', 'head_postag': u'PROP'}, {'head_lemma': u'participar', 'head': u'participando', 'head_postag': u'V-GER'}, {'head_lemma': u'surpreendente', 'head': u'supreendente', 'head_postag': u'ADJ'}, {'head_lemma': u'Bras\xedlia', 'head': u'Bras\xedlia', 'head_postag': u'PROP'}, {'head_lemma': u'Pesquisa_Datafolha', 'head': u'Pesquisa_Datafolha', 'head_postag': u'N'}, {'head_lemma': u'revelar', 'head': u'revela', 'head_postag': u'V-FIN'}, {'head_lemma': u'governo', 'head': u'Governo', 'head_postag': u'N'}, {'head_lemma': u'de', 'head': u'de', 'head_postag': u'PRP'}, {'head_lemma': u'governo', 'head': u'Governo', 'head_postag': u'N'}, {'head_lemma': u'recusar', 'head': u'recusando', 'head_postag': u'V-GER'}, {'head_lemma': u'maioria', 'head': u'maioria', 'head_postag': u'N'}, {'head_lemma': u'querer', 'head': u'quer', 'head_postag': u'V-FIN'}, {'head_lemma': u'PT', 'head': u'PT', 'head_postag': u'PROP'}, {'head_lemma': u'surpreendente', 'head': u'supreendente', 'head_postag': u'ADJ'}, {'head_lemma': u'Bras\xedlia', 'head': u'Bras\xedlia', 'head_postag': u'PROP'}, {'head_lemma': u'Pesquisa_Datafolha', 'head': u'Pesquisa_Datafolha', 'head_postag': u'N'}, {'head_lemma': u'revelar', 'head': u'revela', 'head_postag': u'V-FIN'}, {'head_lemma': u'muito', 'head': u'Muitas', 'head_postag': u'PRON-DET'}, {'head_lemma': u'prioridade', 'head': u'prioridades', 'head_postag': u'N'}, {'head_lemma': u'com', 'head': u'com', 'head_postag': u'PRP'}, {'head_lemma': u'prioridade', 'head': u'prioridades', 'head_postag': u'N'}] 

train_argcands_target = ['NULL', 'ARG', 'ARG', 'ARG', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'ARG', 'ARG', 'ARG', 'ARG', 'NULL', 'NULL', 'NULL', 'NULL', 'ARG', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'ARG', 'NULL', 'NULL', 'NULL', 'NULL', 'ARG', 'ARG', 'NULL', 'NULL'] 
+0

De acuerdo con el seguimiento de pila, el problema está dentro de su llamada 'feat_selector.fit (train_argcands_feats, train_argcands_target)'. ¿'RFECV' es una clase que creas o es una biblioteca? ¿Es posible publicar su código 'RFECV.fit()'? – acattle

+0

@acattle Es una biblioteca de scikit-learn: http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html – feralvam

+0

@acattle ¿dónde estás viendo eso? – XORcist

Respuesta

32

fin llegué a resolver el problema. Dos cosas que había que hacer:

  1. train_argcands_target es una lista y tiene que ser una matriz numpy. Me sorprende que funcionó bien antes, cuando acabo de usar el estimador directamente.
  2. Por alguna razón (aún no sé por qué), tampoco funciona si utilizo la matriz dispersa creada por DictVectorizer. Tuve que, "manualmente", transformar cada diccionario de características en una matriz de características con números enteros que representan cada valor de característica. El proceso de transformación es similar al que presento en el código para los valores objetivo.

¡Gracias a todos los que han intentado ayudar!

9

Si alguien sigue interesado,

he utilizado la CountVectorizer en algo muy similar y me dio el mismo error. Me di cuenta de que el vectorizador me da una matriz dispersa COO que es básicamente una lista de coordenadas. No se puede acceder a los elementos de las matrices de COO a través de los índices de fila. Lo mejor es convertirlo a una matriz CSR (Compressed Sparse Row) que indexa en filas. La conversión se puede hacer fácilmente coo_matrix.tocsr(). No se requiere ningún otro cambio, esto funcionó para mí.

+1

Tuve el mismo problema y esta solución funcionó para mí. Es más fácil que recuperar haciendo la respuesta aceptada aquí. Además, el motivo proporcionado (COO inaccesible a través de índices de filas) tiene mucho más sentido. – Dexter

+0

Totalmente de acuerdo. COO es el problema. –

Cuestiones relacionadas