python - 使用索引提取张量的行和列
问题描述
我有一个 2-D tensor x
,它是一个 placeholder x = tf.placeholder(tf.int32, shape=[None, 100])
。现在在图中,我想随机提取50%
x 行。这是我尝试过的:
idxs = tf.range(tf.shape(x)[0])
ridxs = tf.random_shuffle(idxs)[: int(tf.shape(x)[0] * 0.5)]
x = tf.gather(x, ridxs, axis=0)
它抛出以下错误:
Traceback (most recent call last):
File "main_gcn_random_sampling.py", line 76, in <module>
model = GCN_RANDOM_SAMPLING(FLAGS.learning_rate, num_input, num_classes, hidden_dimensions=hidden_sizes, act=tf.nn.relu)
File "/home/tiendh/Projects/EPooling/gcn_random_sampling.py", line 63, in __init__
ridxs = tf.random_shuffle(idxs)[: int(tf.shape(x)[0] * 0.5)]
TypeError: unsupported operand type(s) for *: 'Tensor' and 'float'
我可以为预定义的索引声明另一个占位符,但它看起来很难看。还有什么建议吗?
解决方案
这几乎是正确的,但是:
tf.shape(x)[0]
在乘以之前,您必须强制转换为浮动0.5
。- 您不能使用
int
转换张量数据类型,您需要使用tf.cast
.
idxs = tf.range(tf.shape(x)[0])
num_half_idx = tf.cast(tf.cast(tf.shape(x)[0], tf.float32) * 0.5, tf.int32)
ridxs = tf.random_shuffle(idxs)[: num_half_idx]
x = tf.gather(x, ridxs, axis=0)
请注意,如果您总是获得 50% 的行,您也可以简单地执行以下操作:
idxs = tf.range(tf.shape(x)[0])
ridxs = tf.random_shuffle(idxs)[: tf.shape(x)[0] // 2]
x = tf.gather(x, ridxs, axis=0)
推荐阅读
- jquery - 使用 jQuery 计算 div 的数量和隐藏按钮
- html - 为什么它只是改变表中第一个数字的第一种格式
- kdb - 使用功能选择获取附加列
- java - 如何在不重新绘制我的 JLabel 的情况下执行 setLocation
- python - Gimp 自动化(Scripz Fu/Python Fu)
- javascript - Laravel 7 jQuery UI datepicker: Uncaught TypeError: $(...).datepicker is not a function
- javascript - JavaScript 从另一个对象创建对象
- java - Selenium WebDriver 无耻地返回不正确的 WebElement 高度
- python - Django Listview FormMixin
- ansible - ansible playbook 执行并且没有显示错误,但没有在主机上执行预期的操作