【问题标题】:How to concatenate tensors after expanding dimension using Keras Functional API?使用 Keras 功能 API 扩展维度后如何连接张量?
【发布时间】:2021-03-14 18:19:31
【问题描述】:

我正在尝试扩展维度:

import tensorflow as tf
inp = tf.keras.layers.Input(shape=(1,))
inp = inp[..., tf.newaxis]
decoder_input = inp
output = tf.concat([inp, decoder_input], 1)
model = tf.keras.models.Model(inp, output )

但我在最后一行得到一个错误:

发生异常:ValueError 图表已断开:无法获取 张量值 Tensor("input_1:0", shape=(None, 1), dtype=float32) 在“tf_op_layer_strided_slice”层。以下之前的图层 访问没有问题:[]

【问题讨论】:

  • 我无法理解您希望模型做什么。 “扩展维度”是指从形状 (a,b)->(a,b,1) 重塑还是什么?
  • @krenerd 是的,重塑 (a, b) -> (a, b, 1)
  • 改用tf.expand_dims
  • @今天我试过了 - 效果不佳
  • 你是如何使用tf.expand_dims的?编辑您的问题并添加代码 sn-p。可能您仍在修改inp(您根本不应该这样做,因为这是模型的输入,不应该被修改)。

标签: tensorflow keras


【解决方案1】:

这是你想要做的吗?似乎你有一个变量冲突。您将decoder_input 设置为reshape 层而不是input 层。更改reshape 层的名称可以修复它。

import tensorflow as tf
inp = tf.keras.layers.Input(shape=(1,))

x = tf.keras.layers.Reshape((-1,1))(inp) #Use any of the 3
#x = tf.expand_dims(inp, axis=-1)
#x = inp[...,tf.newaxis]

decoder_input = inp
output = tf.concat([inp, decoder_input], 1)
model = tf.keras.models.Model(inp, output)

model.summary()
Model: "functional_8"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_7 (InputLayer)            [(None, 1)]          0                                            
__________________________________________________________________________________________________
tf_op_layer_concat_4 (TensorFlo [(None, 2)]          0           input_7[0][0]                    
                                                                 input_7[0][0]                    
==================================================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0

【讨论】:

    【解决方案2】:

    如果您希望模型从 (a, b) -> (a, b, 1) 重塑张量,您可以使用tf.keras.layers.Reshape 层。

    inp = tf.keras.layers.Input(shape=(1,))
    ...
    decoder_input = inp
    output=tf.keras.layers.Reshape((a,b,1))(decoder_input ) #Replace (a,b,1) with your desired shape.
    ...
    
    

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 2017-11-26
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多