python - 在 Keras 中正确构建 YOLOv2 的 Classifier 模型(Darknet19)
问题描述
我正在尝试阅读一篇论文并从头开始构建分类器部分,但我似乎遇到了一个错误,并且不确定我是否正确构建它:
这是论文: https ://pjreddie.com/media/files/papers/YOLO9000.pdf
import keras
from keras.layers import Conv2D, Input, concatenate
from keras.layers import LeakyReLU, MaxPooling2D, BatchNormalization,GlobalAveragePooling2D
from keras.models import Model
from keras.activations import softmax
from functools import partial
#First train body for image classification
#Then train head
new_conv = partial(Conv2D ,padding = "same")
def _base_block(out,x):
"(3,3), Leaky, Batch"
x =new_conv(out, (3,3))(x)
x =LeakyReLU(alpha=0.1)(x)
x =BatchNormalization()(x)
return x
def _block_1(out, x):
"""
output follows:
out//2, out
"""
x = new_conv(out//2, (1,1))(x)
x =LeakyReLU(alpha=0.1)(x)
x = BatchNormalization()(x)
x = _base_block(out,x)
return x
def _block_2(out, x):
"""
output follows:
out, out//2, out
"""
x =_base_block(out,x)
x = _block_1(out, x)
return x
def Darknet19():
input_layer = Input((img_size, img_size, 3))
x = _base_block(32,input_layer)
x = MaxPooling2D((2,2),strides = 2)(x)
x = _base_block(64,x)
x = MaxPooling2D((2,2),strides = 2)(x)
x = _block_2(128, x)
x = MaxPooling2D((2,2),strides = 2)(x)
x = _block_2(256, x)
x = MaxPooling2D((2,2),strides = 2)(x)
x = _block_2(512, x)
x = _block_1(512, x)
x = MaxPooling2D((2,2),strides = 2)(x)
x =_block_2(1024, x)
x = _block_1(512, x)
x = new_conv(1, (1,1), activation = "linear")(x)
model = Model(inputs = input_layer, outputs = x)
return model
def Darknet_classifier():
base_model = Darknet19()
x = base_model.output
x = GlobalAveragePooling2D()(x)
output = softmax(x)
model = Model(inputs = base_model.inputs, outputs = output)
return model
img_size = 426 #multiple of 30
model = Darknet19()
model =Darknet_classifier()
print(model.summary())
我收到的错误:
'Found: ' + str(x)) ValueError: 模型的输出张量必须是 Keras 的输出
Layer
(因此保存过去的层元数据)。找到:Tensor("Softmax:0", shape=(?, 1), dtype=float32)
看来我不能从 GAP 转到 softmax。我对模型的解释不正确吗?
解决方案
您没有正确应用 softmax,您可以使用该Activation
层:
from keras.layers import Activation
output = Activation("softmax")(x)
推荐阅读
- python-3.x - 从 Bitbucket 部署到 Digital Ocean 会导致 Bitbucket 管道出错或 Digital Ocean 上出现密码提示
- javascript - 如何在 react-native 的 fetch api 中将响应作为字符串进行管理
- python - 无法识别使用硒“点击”下一页的内容
- javascript - Discord.js 创建带有服务器信息的 JSON 文件
- integer-overflow - 为什么我的程序的输出是秘密的值?
- javascript - 访问 HTMLRewriter 中的嵌套元素 - Cloudflare Workers
- javascript - 如何使用反应类组件创建 algolia 自动完成自定义渲染器
- angular - PrimeNg 组织结构图:删除选定节点
- arrays - 将对象数组转换为 csv
- javascript - Javascript:使用 x-www-form 在对象中获取和发布数组