2017-01-30 1 views
1

テンソルフローを使用するには、クラス用に1つのホットベクトルが必要です。Python Broadcasting:One-Hotベクトルを埋め込む際にNumPyの速度を引き出す方法は?

私はワンホットベクトルを作成するために次のコードを持っていますが、それはnumpy放送のために熟しているようです。

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 

答えて

2

は、ここで使用して一つの手法だbroadcasting -

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

サンプル実行 -

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.]]) 
関連する問題