【问题标题】:Tensorflow 2.x: Create tensor with None dimension and final dimension of oneTensorflow 2.x:创建无维度和最终维度为一的张量
【发布时间】:2020-12-14 22:19:17
【问题描述】:

我有一个形状为 [None, n_steps, n_filt] 的张量,我需要将一个新的“标量”特征连接到该张量(称之为 x)。它的维度为[None, 1]。该标量应作为新的特征值附加,为每一步添加相同的常数值并生成形状为[None, n_steps, n_filt+1] 的新张量。理想情况下,我会创建一个新张量并将新张量连接到它:

new_feat = tf.ones([None, n_steps, 1]) * x 
tf.concat([orig_tensor, new_feat], axis=2)

但我无法创建一个无形状的张量。我收到以下错误:

ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.

经过一番折腾,我发现了ones_like() 方法,它复制了原始张量的形状。但是我需要将最后一个维度减少到一个,并且使用切片会破坏该维度。我可以重新创建它,但它是一团糟。 我构建了以下行,它可以满足我的需求,但看起来不必要地冗长。有没有更好的方法来做到这一点:

new_feat = tf.expand_dims(tf.ones_like(orig_tensor)[:,:,0],axis=-1)*x
tf.concat([orig_tensor, new_feat], axis=2)

编辑:即使上面的代码编译,它也不会运行。叹息。

Incompatible shapes: [1000,156,1] vs. [1000,1]

编辑 2:这是另一个尝试。从维度 = [None, 1] 的原始特征开始,使用expand_dim() 插入新维度,然后使用gather() 复制中间维度:

tf.gather(tf.expand_dims(x, axis=1), indices=[0]*n_steps, axis=1)

编辑 3:这是另一种选择:

tf.tile(tf.expand_dims(x, axis=1), multiples=[1,n_steps,1])

【问题讨论】:

    标签: python-3.x tensorflow2.0 tensor


    【解决方案1】:

    以最简单的方式,您可以定义两个输入层,然后将它们连接在一起:

    import tensorflow as tf
    import numpy as np
    
    n_steps = 3
    n_filt = 5
    input_0 = tf.keras.layers.Input((n_steps, n_filt))
    input_1 = tf.keras.layers.Input((n_steps, ))
    new_feat = tf.keras.layers.Reshape((n_steps, 1))(input_1)
    cat = tf.keras.layers.Concatenate(axis=-1)([input_0, new_feat])
    
    model = tf.keras.Model(inputs=[input_0, input_1], outputs=cat)
    model.summary()
    
    batch_size = 2
    scalar_value = 1
    inp_0 = np.random.rand(batch_size, n_steps, n_filt)
    inp_1 = np.full((batch_size, n_steps), scalar_value)
    out_cat  = model([inp_0, inp_1])
    print(out_cat)
    

    【讨论】:

    • @"Mr. For Example" 我花了一些时间处理您的代码并对其进行扩展。首先,输入张量input_1 需要有维度[None, 1]。输入的代码是[None, n_steps],在这种情况下,一个简单的重塑确实可以解决问题。但是对于[None, 1],标量需要与n_step 沿新插入的轴=1 复制。我更深入地研究了 API,发现了 tf.tile(),它的功能类似于 tf.gather(),并沿选定的维度分发副本。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多