python - 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. ]]]]
你能告诉我有什么问题吗?
解决方案
默认情况下,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'))
然后您的模型将按预期运行。
推荐阅读
- javascript - 这是 React 中高阶组件(HOC)的有效实现吗?
- wso2 - WSO2 API 管理器版本 3.0 中针对 openAPI 规范的模式验证
- c# - C# 中是否有“直通”属性的简写?
- python - 如何在数据框中就地替换1列中的数字?
- android - Android - 位图缩放 [QS 面板背景]
- python-3.x - 如何在 antlr4 中仅查找被覆盖的方法
- python - Keras predict_on_batch 和 predict 相当慢
- android - 如何对 Flowable.interval 进行单元测试?
- sql - db.Query with sql join error 列上的扫描错误
- ios - 从 iCloud 上传文件不起作用 Alamofire Multipart