python - 从张量中随机移除

标签 python tensorflow

我试图从张量中随机删除一行。到目前为止我看到的最简单的方法如下(引用 here ):

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
a_vecs = tf.unstack(a, axis=1)
val = tf.constant(1)
del a_vecs[val]
a_new = tf.stack(a_vecs, 1)

我想传递给“del”一个基于张量运算的随机整数。但是当我使用时:

ran = tf.random_uniform((1,), minval=0, maxval=val, dtype=tf.int32)

我返回一个数组,但 del 不接受数组。另外,如果有更简单的方法从数组中删除,请告诉我。

最佳答案

您可以使用您需要的任何尺寸和形状的tf.boolean_mask。使用 np.random.choice

创建所需形状的 bool 值的 numpy 数组
#your_shape = int or array
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
ran = tf.random_uniform((1,), minval=0, maxval=2, dtype=tf.int32)
a_vecs = tf.unstack(a, axis=1)
rm = np.random.choice([True, False], your_shape)
a_new = tf.boolean_mask(a_vecs, rm)

或者您可以使用 np.asscalar 将数组转换为标量,但它需要在 session 中运行。

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
ran = tf.random_uniform((1,), minval=0, maxval=2, dtype=tf.int32)
a_vecs = tf.unstack(a, axis=1)
with tf.Session() as sess:
    r = ran.eval()
    val = np.asscalar(r)
    del a_vecs[val]
    a_new = tf.stack(a_vecs, 1)

关于python - 从张量中随机移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727889/

相关文章:

python - 将 for 循环集成到 if 语句中

python - 将前 N 行与 pandas 列中的当前行进行比较

python - tensorflow GPU错误: InvalidArgumentError: Cannot assign a device for operation 'MatMul'

python - 你能将 opencv SIFT 与 tensorflow 模型集成吗?

python - bazel构建tensorflow/工具/graph_transforms :transform_graph ERROR

tensorflow - GPU tensorflow 安装问题

tensorflow - 内存使用指标 `nvidia-smi dmon` 与 `nvidia-smi` 之间有何差异

python - 使用 python 3 和 OSX 或 Linux 连接到 Wonderware Historian OLE DB

python - pyparsing - 同一条语句的第二次执行抛出异常

python - 使用 Percona 安装 mysql-python