为了账号安全,请及时绑定邮箱和手机立即绑定

Tensorflow1 concat 二维张量与所有按行排列

Tensorflow1 concat 二维张量与所有按行排列

哔哔one 2023-06-20 15:50:41
假设我们有两个形状为 ( n, k) 和 ( n, k) 的二维张量。我们想要将两个张量与所有行方向排列连接起来,使得所得张量的形状为 ( n, n, 2*k)。例子,A = [[a, b], [c, d]]; B = [[e, f], [g, h]]得到的张量应该是:[[[a, b, e, f], [a, b, g, h]], [[c, d, e, f], [c, d, g, h]]]假设输入张量 A 和 B 具有非静态形状,因此我们不能使用 for 循环索引tf.shape()值。任何帮助表示赞赏。非常感谢。
查看完整描述

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

tf.concattf.repeat和一起使用tf.tile

import tensorflow as tf

import numpy as np


# Input

A = tf.convert_to_tensor(np.array([['a', 'b'], ['c', 'd']]))

B = tf.convert_to_tensor(np.array([['e', 'f'], ['g', 'h']]))


# Repeat, tile and concat

C = tf.concat([tf.repeat(A, repeats=tf.shape(A)[-1], axis=0), 

               tf.tile(B, multiples=[tf.shape(A)[0], 1])], 

              axis=-1)


# Reshape to requested shape

C = tf.reshape(C, [tf.shape(A)[0], tf.shape(A)[0], -1])


print(C)


>>> <tf.Tensor: shape=(2, 2, 4), dtype=string, numpy=

>>> array([[[b'a', b'b', b'e', b'f'],

>>>         [b'a', b'b', b'g', b'h']],

>>>        [[b'c', b'd', b'e', b'f'],

>>>         [b'c', b'd', b'g', b'h']]], dtype=object)>


查看完整回答
反对 回复 2023-06-20
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

试试这样:


A = np.array([['a', 'b'], ['c', 'd']])

B = np.array([['e', 'f'], ['g', 'h']])


C = np.array([np.concatenate((a, b), axis=0) for a in A for b in B])


您可以像这样轻松地将其转换为张量流


data =tf.convert_to_tensor(C, dtype=tf.string)

输出:


<tf.Tensor: shape=(4, 4), dtype=string, numpy=

array([[b'a', b'b', b'e', b'f'],

       [b'a', b'b', b'g', b'h'],

       [b'c', b'd', b'e', b'f'],

       [b'c', b'd', b'g', b'h']], dtype=object)>

不确定列表理解部分是否对大数据最有效


查看完整回答
反对 回复 2023-06-20
  • 2 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信