【问题标题】:Keras tensorflow modify model NN to CNNKeras tensorflow 将模型 NN 修改为 CNN
【发布时间】:2020-07-16 15:29:15
【问题描述】:

我正在尝试重写用于对卫星图像进行分类的神经网络模型, 我想在那个模型中使用一些卷积层,比如 #keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding = 'same',input_shape=(1,nBands)), 但我无法正确获取input_shape 参数,谁能帮帮我?

之前的NN模型是这样的:

# Print the shape of reshaped data
print(xTrain.shape, xTest.shape, featuresHyderabad.shape)
#(2519025, 1, 6) (1679351, 1, 6) (1391808, 1, 6)
# Define the parameters of the model
model = keras.Sequential([

    #keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding = 'same',input_shape=(1,nBands)),
    keras.layers.Flatten(input_shape=(1, nBands)), 
    keras.layers.Dense(128, activation='relu',kernel_initializer='glorot_normal'),
    keras.layers.Dense(2, activation='softmax')])

# Define the accuracy metrics and parameters
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

# Run the model
model.fit(xTrain, yTrain, epochs=2,batch_size=10)

【问题讨论】:

    标签: python tensorflow machine-learning keras neural-network


    【解决方案1】:

    输入的形状必须是图像的形状。例如,如果您使用 48x48 黑白图像训练模型,则输入形状将为 (48,48, 1) 或 (1, 48, 48),如果将 chanel 值放在高度和宽度之前。

    【讨论】:

    • 谢谢!!不过图片已经改版了,原文是here
    • 好的,所以图像是一维展平的,所以您必须使用具有相同输入形状的 conv1D(而不是 conv2D),否则您将不得不删除重塑步骤,以便图像仍为 2D
    • 谢谢!我尝试像这样使用 Conv1D 层:keras.layers.Conv1D(filters=64, kernel_size=(3), activation='relu', padding = 'same',input_shape=(2519025, 6)), ,但我得到了这个警告:WARNING:tensorflow:Model was constructed with shape (None, 2519025, 6) for input Tensor("conv1d_input:0", shape=(None, 2519025, 6), dtype=float32), but it was called on an input with incompatible shape (None, 1, 6).,我该如何解决这个问题?
    • 2519025 是多少?
    【解决方案2】:

    很好的问题,我认为您会发现 CNN 的性能要比在扁平图像上训练 NN 好得多。对于Conv2D 层中的输入形状,形状可以以两种形式之一给出:

    1. “Channels last”(Keras 默认使用这个):(image height, image width, 6),其中6 指通道数(3 用于 RGB,1 用于灰度)。

    2. “Channels first”(定义Conv2D层时可以通过设置data_option="channels_first"来选择此选项):(6, image height, image width)

    更直观地说,您可以将输入大小视为您提供给网络的图像大小,即(image height, image width, number of bands)。我发现 Keras 的这份文档也很有帮助:https://keras.io/api/layers/convolution_layers/convolution2d/

    【讨论】:

    • 谢谢!!原始卫星图像大小为 2054 *2044,我相信它有 6 个通道,但它已被重新整形为二维阵列,然后重新整形为三维,这样每一行代表一个单独的像素。我尝试了所有可能的数字,如 (2054, 2044,6),(2519025, 1, 6) 仍然得到相同的错误结果,原文在这里:towardsdatascience.com/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多