账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    tensorflow 不同维度的 tensor 如何合并?
    40
    0

    我的 scv 文件中每行一个样本,假设一个样本只有两个特征 x1, x2。
    reader 按行读之后可以用 tf.stack 合并成 [x1, x2]
    现在想要将所有的样本合并成一个 m*2 的 tensor,也就是这样:
    [[x1^(1), x2^(1)]
    [x1^(2), x2^(2)]
    ...
    [x1^(m), x2^(m)]]
    但是不同维度的 tensor 好像无法合并..
    比如:
    [[x1^(1), x2^(1)]
    [x1^(2), x2^(2)]]

    [[x1^(3), x2^(3)]]
    合并会报错:
    From merging shape 0 with other shapes. for 'stack_1' (op: 'Pack') with input shapes: [2,2], [1,2].
    求解...

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 上君 普通会员 1楼

      在TensorFlow中,合并不同维度的Tensor主要有以下几种方法:

      1. tf.concat: 用于沿着指定轴(axis)拼接张量。例如:

      ```python import tensorflow as tf

      假设我们有两个不同维度的tensor

      t1 = tf.constant([1, 2, 3]) t2 = tf.constant([[4, 5], [6, 7]])

      我们可以通过在新维度上堆叠它们来合并

      t_concat = tf.concat([t1[tf.newaxis, :], t2], axis=0)

      或者如果希望在列方向合并,可以使用

      t_concat = tf.concat([tf.expand_dims(t1, 1), t2], axis=1)

      输出:

      t_concat = [[1, 2, 3],

      [4, 5],

      [6, 7]]

      ```

      1. tf.stack: 将一串张量“堆叠”到一个新的维度上。

      ```python t_stack = tf.stack([t1, t2], axis=0)

      输出:

      t_stack = [[[1], [2], [3]],

      [[4, 5],

      [6, 7]]]

      ```

      1. tf.reshape: 如果两个张量的元素数量相同,你可以通过重塑(reshape)一个或两个张量以匹配维度,然后进行拼接。

      ```python

      将t1重塑为与t2相同的维度

      t1_reshaped = tf.reshape(t1, (1, -1)) # 形状为(1, 3) t_concat = tf.concat([t1_reshaped, t2], axis=0)

      输出:

      t_concat = [[1, 2, 3],

      [4, 5],

      [6, 7]]

      ```

      注意:在实际操作中,需要根据具体的需求和数据结构选择合适的合并方式。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部