python - 在张量流中生成这样的张量
问题描述
假设我有一个向量
[3, 2, 4]
我想生成一个对应的张量
[[1,1,1,0], [1,1,0,0],[1,1,1,1]]
你能告诉我们怎么做吗?谢谢
解决方案
这应该有效:
import tensorflow as tf
sess = tf.Session()
# Input tensor
indices = tf.placeholder_with_default([3, 2, 4], shape=(None,))
max_index = tf.reduce_max(indices)
def to_ones(index):
ones = tf.ones((index, ), dtype=indices.dtype)
zeros = tf.zeros((max_index - index, ), dtype=indices.dtype)
return tf.concat([ones, zeros], axis=0)
# Output tensor
result = tf.map_fn(to_ones, indices)
print(result)
:
Tensor("map/TensorArrayStack/TensorArrayGatherV3:0", shape=(?, ?), dtype=int32)
print(sess.run(result))
:
[[1 1 1 0]
[1 1 0 0]
[1 1 1 1]]
print(sess.run(result, feed_dict={indices: [1, 3, 3, 7]}))
:
[[1 0 0 0 0 0 0]
[1 1 1 0 0 0 0]
[1 1 1 0 0 0 0]
[1 1 1 1 1 1 1]]
推荐阅读
- angular - 父组件监听子组件中包含的输入
- angular - 如何在 angular4 中设置页面刷新或页面更改时的日期时间选择器的日期
- javascript - 一个一个地从多边形中删除所有点
- mongodb - 无法使用 ODM 进行基本地理空间查询
- javascript - JavaScript 将字符串拆分为多个数组
- javascript - 当我们在控制台浏览器中打开代码时,所有的手机号码都应该显示我不想要这个?如何从控制台隐藏这个?
- javascript - reactnavigation隐藏状态栏在标题上方留下空间
- c# - 在 if/else 语句中定义变量时,是否可以使用 var?
- python - 获取字符串python中所有出现的正则表达式
- php - 将项目的模板引擎从 savant2 更改为 Plates