首页 > 解决方案 > Keras 将 Image 视为数组数组而不是单个图片

问题描述

所以我在课堂上有一个NN

      self.model = Sequential()
      self.model.add(Conv2D(50, (3, 3), activation='relu', input_shape=(240,256,3)))
      self.model.add(Dense(264,activation='relu'))
      self.model.add(Dense(7,activation='relu'))
      self.model.compile(optimizer=Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy'])

我有一个形状为 (240, 256, 3) 的数组

print(picture.shape) #(240, 256, 3)
picture = np.reshape(picture,(1,240,256,3))

然后尝试

self.model.predict(picture,verbose=1)

[ 0. 25.21973 0. 0. 0. 1.8569145 0.]我得到的不是这样的输出

[[[[ 0.         25.21973     0.         ...  0.          1.8569145
     0.        ]
   [ 0.         25.21973     0.         ...  0.          1.8569145
     0.        ]
   [ 0.         25.21973     0.         ...  0.          1.8569145
     0.        ]
   ...
  [[ 0.         14.3257885   0.         ...  1.7455587   0.
     0.        ]
   [ 0.         25.417042    0.         ...  0.          7.501096
     0.        ]
   [ 0.         24.028965    0.         ... 14.10364     0.
     0.        ]
   ...
   [ 0.         17.480661    0.         ...  3.4586341   0.
     0.        ]]

  [[ 0.         21.477276    0.         ...  0.          0.
     0.        ]
   [ 0.         15.683931    0.         ...  0.          0.
     0.        ]
   [ 0.         10.419488    0.         ...  0.          0.29006004
     0.        ]
   ...

   [ 0.          7.038389    0.         ...  0.          0.
     0.        ]]

  [[ 0.         18.099554    0.         ...  0.          0.
     0.        ]
   [ 0.          8.225699    0.         ...  0.751534    0.
     0.        ]
   [ 0.         13.256775    0.         ...  0.          2.1235647
     0.        ]]]]

你能告诉我有什么问题吗?

标签: pythonpython-3.xkeras

解决方案


默认情况下,Keras 的Dense层对输入的最后一个维度进行操作,因此当您输入图像时,您会得到另一张图像作为输出。问题出在你的模型上。如果您使用model.summary(),您会看到模型的输出形状实际上就是您所看到的形状predict

解决方法很简单,Flatten在最后一层之后加一层Conv2D

self.model = Sequential()
self.model.add(Conv2D(50, (3, 3), activation='relu', input_shape=(240,256,3)))
self.model.add(Flatten())
self.model.add(Dense(264,activation='relu'))
self.model.add(Dense(7,activation='relu'))

然后您的模型将按预期运行。


推荐阅读