如何从 Tensorflow 中的分类分布中采样唯一数字张量
How to sample unique number tensors from a categorical distribution in Tensorflow
我想从分类分布中抽样值,而不会在 return
中重复
我尝试使用tf.random.categorial,但似乎我想做的事是不可能的...
tf.random.categorical(tf.math.log([[0.2,0.3,0.2,0.1,0.2]]), 4)
好的结果:[[3,2,4,1]]
// 意外的结果 [[1,2,2,3]]
目前我已经这样解决了我的问题,但是性能很差(慢了10倍)
score_batch = tf.nn.softmax(score_batch, axis=-1)
batch_size = batch.shape[0]
indexes_array = tf.TensorArray(dtype=tf.int32, size=batch_size)
for idx in tf.range(batch_size):
logits = tf.math.log(tf.expand_dims(score_batch[idx], axis=0))
current_indexes = tf.random.categorical(logits, 4, dtype=tf.int32)
current_indexes = tf.squeeze(current_indexes)
while tf.math.not_equal(current_indexes.shape[0], tf.shape(tf.unique(current_indexes)[0])[0]):
current_indexes = tf.random.categorical(logits, 4, dtype=tf.int32)
current_indexes = tf.squeeze(current_indexes)
indexes_array = indexes_array.write(idx, current_indexes)
indexes = indexes_array.stack()
更新:
经过测试,建议的解决方案运行良好,可以让我做我想做的事
我找不到只使用 tensorflow
的方法,也许它正在考虑,禁止重复 classes,你在搞乱概率,因为 [= =22=]被选中,再次被选中的概率为0
但是您可以使用 numpy
使用 numpy.random.choice()
轻松做到这一点
numpy.random.choice(np.arange(0,5),size=4,replace=False,p=[0.2,0.3,0.2,0.1,0.2])
如果你想将它转换为张量,只需使用 tf.convert_to_tensor
:
tf.convert_to_tensor(numpy.random.choice(np.arange(0,5),size=4,replace=False,p=[0.2,0.3,0.2,0.1,0.2]))
我想从分类分布中抽样值,而不会在 return
中重复我尝试使用tf.random.categorial,但似乎我想做的事是不可能的...
tf.random.categorical(tf.math.log([[0.2,0.3,0.2,0.1,0.2]]), 4)
好的结果:[[3,2,4,1]]
// 意外的结果 [[1,2,2,3]]
目前我已经这样解决了我的问题,但是性能很差(慢了10倍)
score_batch = tf.nn.softmax(score_batch, axis=-1)
batch_size = batch.shape[0]
indexes_array = tf.TensorArray(dtype=tf.int32, size=batch_size)
for idx in tf.range(batch_size):
logits = tf.math.log(tf.expand_dims(score_batch[idx], axis=0))
current_indexes = tf.random.categorical(logits, 4, dtype=tf.int32)
current_indexes = tf.squeeze(current_indexes)
while tf.math.not_equal(current_indexes.shape[0], tf.shape(tf.unique(current_indexes)[0])[0]):
current_indexes = tf.random.categorical(logits, 4, dtype=tf.int32)
current_indexes = tf.squeeze(current_indexes)
indexes_array = indexes_array.write(idx, current_indexes)
indexes = indexes_array.stack()
更新:
经过测试,建议的解决方案运行良好,可以让我做我想做的事
我找不到只使用 tensorflow
的方法,也许它正在考虑,禁止重复 classes,你在搞乱概率,因为 [= =22=]被选中,再次被选中的概率为0
但是您可以使用 numpy
使用 numpy.random.choice()
numpy.random.choice(np.arange(0,5),size=4,replace=False,p=[0.2,0.3,0.2,0.1,0.2])
如果你想将它转换为张量,只需使用 tf.convert_to_tensor
:
tf.convert_to_tensor(numpy.random.choice(np.arange(0,5),size=4,replace=False,p=[0.2,0.3,0.2,0.1,0.2]))