Skip to main content
 首页 » 编程设计

python之reshape Keras 张量

2024年10月01日7EasonJim

如何在不指定初始输入形状的情况下将 Keras 张量从形状 (1,1,10) reshape 为形状 (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__() takes 1 positional argument but 2 were given

那么我应该怎么做才能让它发挥作用呢?

请您参考如下方法:

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

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