2016-11-09 53 views
1

我目前有一種編碼我想使用嵌入的編碼。然而,當我打電話使用onehot編碼的Tensorflow嵌入查找

embed=tf.nn.embedding_lookup(embeddings, train_data) 
print(embed.get_shape()) 

embed data shape (11, 32, 729, 128)

這種形狀應爲(11,32,128),但它給了我錯了尺寸,因爲train_data是onehot編碼。

train_data2=tf.matmul(train_data,tf.range(729)) 

給我的錯誤:

ValueError: Shape must be rank 2 but is rank 3 

幫我請了!謝謝。

回答

2

一個小的修復,以你的例子:

encoding_size = 4 
one_hot_batch = tf.constant([[0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]]) 
one_hot_indexes = tf.matmul(one_hot_batch, np.array([range(encoding_size)], 
    dtype=np.int32).T) 

with tf.Session() as session: 
    print one_hot_indexes.eval() 

另一種方法:在這兩種情況下

batch_size = 3 
one_hot_batch = tf.constant([[0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]]) 
one_hot_indexes = tf.where(tf.not_equal(one_hot_batch, 0)) 
one_hot_indexes = one_hot_indexes[:, 1] 
one_hot_indexes = tf.reshape(one_hot_indexes, [batch_size, 1]) 
with tf.Session() as session: 
    print one_hot_indexes.eval() 

結果:

[[3] 
[1] 
[0]] 
+0

試圖頂一個不知道你是否可以只使用NP像那樣在裏面。 – Rik