2017-01-30 15 views
1

Um Tensorflow zu verwenden, brauche ich einen einzigen heißen Vektor für meine Klassen.Python Broadcasting: Wie entfaltet NumPy Geschwindigkeit beim Ausfüllen eines One-Hot-Vektor?

Ich habe den folgenden Code, um einen One-Hot-Vektor zu erstellen, aber es scheint, wie es für numpy Broadcasting reif sein sollte.

def classVector2oneHot(classVector): 
    uniques = np.asarray(list(set(classVector))) 
    one_hot_array = np.zeros(shape=(classVector.shape[0],uniques.shape[0]),dtype=np.float32) 

    starting_index = np.min(uniques) 

    # where broadcasting seems like it should be possible, somehow... 
    for i in range(len(one_hot_array)): 
     one_hot_array[i,classVector[i]-starting_index] = 1 



    return one_hot_array 

Antwort

2

Hier ist ein Ansatz mit broadcasting -

(classVector[:,None] == uniques).astype(float) 

Probelauf -

In [47]: classVector 
Out[47]: array([15, 16, 24, 20, 14, 12, 14, 19, 12, 21]) 

In [48]: uniques = np.unique(classVector) 

In [49]: uniques 
Out[49]: array([12, 14, 15, 16, 19, 20, 21, 24]) 

In [50]: (classVector[:,None] == uniques).astype(float) 
Out[50]: 
array([[ 0., 0., 1., 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 1., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 0., 0., 0., 1.], 
     [ 0., 0., 0., 0., 0., 1., 0., 0.], 
     [ 0., 1., 0., 0., 0., 0., 0., 0.], 
     [ 1., 0., 0., 0., 0., 0., 0., 0.], 
     [ 0., 1., 0., 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 1., 0., 0., 0.], 
     [ 1., 0., 0., 0., 0., 0., 0., 0.], 
     [ 0., 0., 0., 0., 0., 0., 1., 0.]]) 
Verwandte Themen