2014-06-16 1 views
7

ho trovato prossimo esempio sui documenti sklearn sito:Come posso vectorize elenco utilizzando sklearn DictVectorizer

>>> measurements = [ 
...  {'city': 'Dubai', 'temperature': 33.}, 
...  {'city': 'London', 'temperature': 12.}, 
...  {'city': 'San Fransisco', 'temperature': 18.}, 
... ] 

>>> from sklearn.feature_extraction import DictVectorizer 
>>> vec = DictVectorizer() 

>>> vec.fit_transform(measurements).toarray() 
array([[ 1., 0., 0., 33.], 
     [ 0., 1., 0., 12.], 
     [ 0., 0., 1., 18.]]) 

>>> vec.get_feature_names() 
['city=Dubai', 'city=London', 'city=San Fransisco', 'temperature'] 

E ho bisogno di vettorizzare dict che assomiglia:

>>> measurements = [ 
...  {'city': ['Dubai','London'], 'temperature': 33.}, 
...  {'city': ['London','San Fransisco'], 'temperature': 12.}, 
...  {'city': ['San Fransisco'], 'temperature': 18.}, 
... ] 

per ottenere risultato successivo:

array([[ 1., 1., 0., 33.], 
     [ 0., 1., 1., 12.], 
     [ 0., 0., 1., 18.]]) 

Intendo dire che il valore di dict dovrebbe essere una lista (o tupla ecc.).

Posso farlo utilizzando DictVectorizer o in altro modo?

+1

'DictVectorizer' fa una hot-codifica per le variabili stringa, e galleggiante altrimenti. Quindi no, non puoi farlo con DictVectorizer. Se è il tuo caso, andrei a scrivere qualcosa da solo. – Korem

+1

@TalKremerman È perfettamente fattibile, vedere la mia risposta. –

risposta

17

cambiare la rappresentazione di

>>> measurements = [ 
...  {'city=Dubai': True, 'city=London': True, 'temperature': 33.}, 
...  {'city=London': True, 'city=San Fransisco': True, 'temperature': 12.}, 
...  {'city': 'San Fransisco', 'temperature': 18.}, 
... ] 

Poi il risultato è esattamente come ci si aspetta:

>>> vec.fit_transform(measurements).toarray() 
array([[ 1., 1., 0., 33.], 
     [ 0., 1., 1., 12.], 
     [ 0., 0., 1., 18.]])