我的代碼:
h_table = tf.lookup.StaticHashTable(
initializer=tf.lookup.KeyValueTensorInitializer(
keys=[0, 1, 2, 3, 4, 5],
values=[12.3, 11.1, 51.5, 34.3, 87.3, 57.8]
),
default_value=tf.constant(-1),
name="h_table"
)
我想按值對這個 h_table 進行排序,以便新的哈希表是:
鍵 = [4, 5, 2, 3, 0, 1] 值 = [87.3, 57.8, 51.5, 34.3, 12.3, 11.1]
python中的等效程序是:
h_table = { 0: 12.3, 1: 11.1, 2: 57.8, 3: 34.3, 4: 87.3, 5: 57.8}
h_sorted = dict(sorted(h_table.items(), key=lambda x: x[1], reverse=True))
我想要的只是用張量在張量流中實作這種型別的字典操作?
uj5u.com熱心網友回復:
您將不得不創建一個新的tf.lookup.StaticHashTable,因為它在初始化后是不可變的:
import tensorflow as tf
h_table = tf.lookup.StaticHashTable(
initializer=tf.lookup.KeyValueTensorInitializer(
keys=[0, 1, 2, 3, 4, 5],
values=[12.3, 11.1, 51.5, 34.3, 87.3, 57.8]
),
default_value=tf.constant(-1.),
name="h_table"
)
keys = h_table._initializer._keys
values = h_table._initializer._values
value_indices = tf.argsort(tf.reverse(values, axis=[0]), -1)
keys = tf.gather(keys, value_indices)
new_h_table = tf.lookup.StaticHashTable(
initializer=tf.lookup.KeyValueTensorInitializer(
keys=keys,
values=h_table.lookup(keys)
),
default_value=tf.constant(-1.),
name="new_h_table"
)
print(new_h_table._initializer._keys)
print(new_h_table._initializer._values)
tf.Tensor([4 5 2 3 0 1], shape=(6,), dtype=int32)
tf.Tensor([87.3 57.8 51.5 34.3 12.3 11.1], shape=(6,), dtype=float32)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432296.html
