python - 组合任意形状的张量
问题描述
我想组合两个可变长度张量。
由于它们的形状不匹配,我不能使用 tf.concat 或 tf.stack。
所以我想我会把一个展平,然后将它附加到另一个的每个元素上——但我不知道该怎么做。
例如,
a = [ [1,2], [3,4] ]
flat_b = [5, 6]
combine(a, flat_b) would be [ [ [1,5,6], [2,5,6] ],
[ [3,5,6], [4,5,6] ] ]
有没有这样的方法?
解决方案
使用tf.map_fn
with tf.concat
,示例代码:
import tensorflow as tf
a = tf.constant([ [1,2], [3,4] ])
flat_b = [5, 6]
flat_a = tf.reshape(a, (tf.reduce_prod(a.shape).numpy(), ))[:, tf.newaxis]
print(flat_a)
c = tf.map_fn(fn=lambda t: tf.concat([t, flat_b], axis=0), elems=flat_a)
c = tf.reshape(c, (-1, a.shape[1], c.shape[1]))
print(c)
输出:
tf.Tensor(
[[1]
[2]
[3]
[4]], shape=(4, 1), dtype=int32)
tf.Tensor(
[[[1 5 6]
[2 5 6]]
[[3 5 6]
[4 5 6]]], shape=(2, 2, 3), dtype=int32)
推荐阅读
- python - 在 pandas 数据帧上应用函数来执行情绪分析
- python - 使用正则表达式将结构化但非表格文本解析为 pandas
- vhdl - 如何在 case-when 中修复“可能从不完整的 case 或 if 语句生成锁存器”消息?
- flutter - Flutter 应用程序仅在 iOS 模拟器上热重启时崩溃
- javascript - 如何在输入前添加来自选择选项的值?MERN 堆栈
- javascript - 在 javascript 中使用 Promise 来允许非链式更新
- powershell - 停止除默认共享、远程 IPC 和远程管理员之外的共享文件夹
- javascript - SQL 变量从查询返回空白
- apache-spark - 如何存储配置单元表的创建日期
- php - Wordpress 无法访问管理员登录