【问题标题】:Reshaping Keras tensor重塑 Keras 张量
【发布时间】:2017-05-05 13:15:52
【问题描述】:

如何在不指定初始输入形状的情况下将 Keras 张量从形状 (1,1,10) 重塑为形状 (10)? 使用 Flatten()(作为命令)给出

 <tf.Tensor 'flatten_11/Reshape:0' shape=(?, ?) dtype=float32>

作为输出 并在模型中使用时出错

model = Sequential()
    model.add(Convolution1D(filters=self.nb_filters,
                            kernel_size=self.n_gram,
                            padding='valid',
                            activation='relu',
                            input_shape=(None,3*self.vecsize)))
    model.add(MaxPooling1D(pool_size=3*self.vecsize-self.n_gram+1))
    model.add(Flatten())
    model.add(Dense(num_categories, activation='softmax'))

它说: “Flatten”的输入形状未完全定义(得到 (None, 10)。确保将完整的“input_shape”或“batch_input_shape”参数传递给模型的第一层。

初始输入形状是1*任意维度*vecsize,我强烈不想事先指定任意维度。

使用 Flatten((1,1,10)) 而不是 Flatten() 也会产生错误:

TypeError: __init__() 接受 1 个位置参数,但给出了 2 个

那么我应该怎么做才能让它工作呢?

【问题讨论】:

  • 根据给出的消息,听起来您的输出(None,10) 已经完全符合Dense 所需的形状。似乎不需要重塑。

标签: python python-3.x keras


【解决方案1】:

在给第一层的input_shape时,一定不能加上None部分。这是为批量大小保留的,将在训练或预测时自动推断。

因此,在定义您的第一个 Convolution1D 时,如果您最后使用频道,则您的 input_shape 应该只是 input_shape = (3*self.vecsize,1),如果您先使用频道,则应该是 (1,3*self.vecsize)

【讨论】:

  • 在将其添加到模型而不是 Flatten 时,它会抛出 TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
  • 啊,现在我知道出了什么问题了。您传递到第一层的input_shape 不应考虑None 部分。
【解决方案2】:

这当然是 N​​umPy 的假设。我们都熟悉使用 np.reshape(-1,224,224,3) 重塑数组。那是 NumPy 格式。但是,我直接将 Keras 文档中的代码发布给您。

as first layer in a Sequential model
model = Sequential()
model.add(Reshape((3, 4), input_shape=(12,)))
now: model.output_shape == (None, 3, 4)
note: `None` is the batch dimension

intermediate layer in a Sequential model
model.add(Reshape((6, 2)))
now: model.output_shape == (None, 6, 2)

also supports shape inference using `-1` as dimension
model.add(Reshape((-1, 2, 2)))
now: model.output_shape == (None, 3, 2, 2)

可以看到它的格式是

model.add(Reshape((targetsize)))

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2019-07-22
    • 2017-08-20
    • 2016-10-18
    • 2018-10-27
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多