格編碼到三路損失的手工實(shí)現(xiàn))
簡(jiǎn)介本資源是一份面向深度學(xué)習(xí)初學(xué)者與計(jì)算機(jī)視覺開發(fā)者的YOLOv1實(shí)戰(zhàn)訓(xùn)練指南聚焦于如何基于Keras框架快速構(gòu)建并訓(xùn)練自定義目標(biāo)檢測(cè)模型。資源提供完整可運(yùn)行的Keras_YOLOv1實(shí)現(xiàn)含darknet19網(wǎng)絡(luò)定義、train/test腳本及README說明配套圖像預(yù)處理示例jpg、數(shù)據(jù)列表配置txt和模型訓(xùn)練/測(cè)試代碼py覆蓋數(shù)據(jù)準(zhǔn)備、模型搭建、訓(xùn)練調(diào)優(yōu)到結(jié)果可視化全流程。壓縮包共11個(gè)文件含3個(gè)Python核心腳本、4張示例圖像原始與檢測(cè)結(jié)果對(duì)比、3個(gè)文本配置文件及1份Markdown說明文檔總大小僅128KB輕量易解壓適合本地快速驗(yàn)證與二次開發(fā)。目前已有110人學(xué)習(xí)下載讀者可直接復(fù)用目錄結(jié)構(gòu)與代碼模板省去環(huán)境適配與基礎(chǔ)框架搭建時(shí)間尤其適用于課程設(shè)計(jì)、小規(guī)模工業(yè)檢測(cè)場(chǎng)景或YOLO算法演進(jìn)原理研究。1. 為什么還在用 YOLOv1不是為了懷舊而是為了“看懂目標(biāo)檢測(cè)的骨架”你可能在 GitHub 上刷到過一堆標(biāo)著 “YOLOv5/v8/v10 最新版”的倉(cāng)庫(kù)點(diǎn)進(jìn)去全是自動(dòng)標(biāo)注、一鍵訓(xùn)練、WebUI 可視化——但當(dāng)你被導(dǎo)師問“YOLOv1 的損失函數(shù)為什么分坐標(biāo)、置信度、類別三部分計(jì)算”“S×S 網(wǎng)格怎么對(duì)應(yīng)到原始圖像坐標(biāo)”時(shí)卻卡在了反向傳播的黑匣子門口。這套基于 Keras 實(shí)現(xiàn)的 YOLOv1非官方復(fù)現(xiàn)但結(jié)構(gòu)清晰、注釋完整不是為工程落地而生而是為“親手把目標(biāo)檢測(cè)從頭擰緊每一顆螺絲”而設(shè)計(jì)。它不追求 mAP 多高但強(qiáng)制你手寫grid_cell_to_bbox()、手動(dòng)拆解loss_coord和loss_conf、逐層調(diào)試conv4 → fc5 → output的 shape 變化。適合某高校計(jì)算機(jī)視覺課設(shè)、畢設(shè)中需要完整展示算法原理→代碼實(shí)現(xiàn)→訓(xùn)練驗(yàn)證閉環(huán)的學(xué)生也適合想甩掉 PyTorch 自動(dòng)求導(dǎo)依賴、真正吃透 anchor-free 檢測(cè)范式底層邏輯的初階工程師。它不幫你省時(shí)間但它能讓你在答辯時(shí)指著 loss 曲線說清楚“這里第 37 輪震蕩是因?yàn)槲以赾ompute_iou里漏判了邊界框歸一化導(dǎo)致 conf_loss 突增”——這種確定性就是它存在的全部理由。2. 總體架構(gòu)設(shè)計(jì)Keras 函數(shù)式 API 構(gòu)建的四層結(jié)構(gòu)與數(shù)據(jù)流閉環(huán)這套方案沒有采用 Keras Sequential 模型而是嚴(yán)格使用函數(shù)式 APIFunctional API目的很明確讓每一層輸入輸出 shape 可追溯、梯度流向可打斷、中間特征圖可提取。整個(gè)網(wǎng)絡(luò)被劃分為四個(gè)邏輯層每層承擔(dān)明確職責(zé)且彼此解耦——這意味著你可以單獨(dú)替換 backbone比如把原始的 24 層卷積換成 ResNet18 提取器而不影響后續(xù) detection head 的 loss 計(jì)算邏輯。2.1 輸入預(yù)處理層固定尺寸 歸一化 標(biāo)簽編碼的三步不可逆操作YOLOv1 對(duì)輸入尺寸極其敏感必須統(tǒng)一為 448×448原始論文設(shè)定。這不是為了兼容性而是因?yàn)槠?S7 的網(wǎng)格劃分直接綁定圖像寬高比。預(yù)處理代碼如下def preprocess_image(image_path, label_path, input_size448, S7, B2, C20): # 1. 讀取并縮放雙線性插值保持比例 img cv2.imread(image_path) img cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_resized cv2.resize(img, (input_size, input_size)) # 2. 歸一化到 [0,1]Keras 默認(rèn)要求 img_normalized img_resized.astype(np.float32) / 255.0 # 3. 解析 label 文件PASCAL VOC 格式 .xml 或自定義 .txt # 假設(shè) label_path 是 .txt每行: class_id x_center y_center width height (歸一化后) boxes [] with open(label_path, r) as f: for line in f.readlines(): parts line.strip().split() cls_id int(parts[0]) x, y, w, h map(float, parts[1:5]) # 注意YOLOv1 要求 bbox 坐標(biāo)是相對(duì)于整張圖的絕對(duì)比例不是 grid cell boxes.append([cls_id, x, y, w, h]) # 4. 編碼為 (S, S, 5*B C) 的 label tensor label_tensor np.zeros((S, S, 5*B C)) for box in boxes: cls_id, x, y, w, h box # 計(jì)算該 bbox 中心點(diǎn)落在哪個(gè) grid cell (i, j) i int(y * S) # 行號(hào)y 方向 j int(x * S) # 列號(hào)x 方向 if i S or j S: continue # 邊界溢出跳過真實(shí)項(xiàng)目中應(yīng)做裁剪或警告 # 歸一化中心坐標(biāo)到 grid cell 內(nèi)部 [0,1] x_cell S * x - j y_cell S * y - i # 寬高保持原始比例相對(duì)整圖 w_cell w h_cell h # 填充 label_tensor前 5*B 位存 B 個(gè) bbox 的 (x,y,w,h,conf)后 C 位存 one-hot 類別 for b in range(B): if label_tensor[i, j, 4 b*5] 0: # 找第一個(gè)空置信度位 label_tensor[i, j, b*5:(b*54)] [x_cell, y_cell, w_cell, h_cell] label_tensor[i, j, 4 b*5] 1.0 # 置信度 1有物體 break # 類別 one-hotC20此處簡(jiǎn)化為單類實(shí)際需擴(kuò)展 label_tensor[i, j, 5*B int(cls_id)] 1.0 return img_normalized, label_tensor提示這段代碼里的i int(y * S)是關(guān)鍵陷阱點(diǎn)。很多初學(xué)者誤用i int(y)導(dǎo)致 grid cell 索引錯(cuò)亂。YOLOv1 的(x,y)是歸一化到[0,1]的乘以S才得到 cell 索引。我一般會(huì)在preprocess_image后加一句assert np.sum(label_tensor[..., 4]) 0確保至少有一個(gè)置信度被激活否則訓(xùn)練必然失敗。2.2 Backbone 特征提取層24 層卷積 池化的經(jīng)典 VGG 風(fēng)格設(shè)計(jì)原始 YOLOv1 使用 24 層卷積前 20 層 ImageNet 預(yù)訓(xùn)練后 4 層隨機(jī)初始化本方案完全復(fù)現(xiàn)該結(jié)構(gòu)但用 Keras 層級(jí)顯式聲明便于調(diào)試def build_backbone(input_tensor): # 輸入(None, 448, 448, 3) x Conv2D(64, (7, 7), strides(2, 2), paddingsame, nameconv1)(input_tensor) # 224x224 x BatchNormalization()(x) x LeakyReLU(alpha0.1)(x) x MaxPooling2D((2, 2), strides(2, 2))(x) # 112x112 x Conv2D(192, (3, 3), paddingsame, nameconv2)(x) # 112x112 x BatchNormalization()(x) x LeakyReLU(alpha0.1)(x) x MaxPooling2D((2, 2), strides(2, 2))(x) # 56x56 # 后續(xù) 5 組 convpool最終輸出 7x7x1024 特征圖 # 代碼略共 24 層卷積詳見 model.py 中 build_backbone 函數(shù) return x # 輸出 shape: (None, 7, 7, 1024)這個(gè) backbone 的輸出尺寸必須是(7,7,1024)這是硬性約束。因?yàn)?YOLOv1 的 detection head 直接在此基礎(chǔ)上接全連接層將(7,7,1024)flatten 成(1, 7*7*1024)再映射到(1, 7*7*(5*220)) (1, 1470)。任何尺寸偏差都會(huì)導(dǎo)致Dense層報(bào)錯(cuò)。這也是為什么不能隨意替換 backbone —— 除非你同步修改后續(xù)的 reshape 和 dense 層參數(shù)。2.3 Detection Head 層從特征圖到預(yù)測(cè)張量的降維與解耦Backbone 輸出(7,7,1024)后Detection Head 并非簡(jiǎn)單接一個(gè) Dense 層而是分兩步走先用GlobalAveragePooling2D或Flatten降維再用兩個(gè)全連接層過渡最后輸出(7,7,1470)張量。本方案采用更魯棒的Flatten Dense組合并顯式分離坐標(biāo)、置信度、類別分支def build_detection_head(backbone_output, S7, B2, C20): x Flatten()(backbone_output) # (None, 7*7*1024) (None, 49*1024) x Dense(4096, activationleaky_relu, namefc1)(x) # 4096 是原文設(shè)定 x Dropout(0.5)(x) x Dense(S*S*(B*5 C), activationlinear, nameoutput)(x) # 輸出 1470 維 # 關(guān)鍵reshape 回 (S, S, B*5 C) 以便后續(xù) loss 計(jì)算 output_tensor Reshape((S, S, B*5 C))(x) # 分離預(yù)測(cè)每個(gè) cell 預(yù)測(cè) B 個(gè) bbox每個(gè) bbox 5 維 (x,y,w,h,conf) C 維類別 # 這里不立即拆分留到 loss 函數(shù)中按索引取保證梯度連貫 return output_tensor注意Reshape((S, S, B*5 C))這一步。很多同學(xué)在這里用tf.reshape或K.reshape導(dǎo)致模型無法保存必須用 Keras 原生Reshape層。另外B*5 C 2*5 20 30所以最終輸出張量 shape 是(None, 7, 7, 30)而非(None, 1470)—— 這是后續(xù)所有 loss 計(jì)算和 NMS 的基礎(chǔ)維度。2.4 損失函數(shù)層坐標(biāo)、置信度、類別三路 loss 的手工拼裝與加權(quán)YOLOv1 的 loss 是其靈魂所在也是最容易翻車的地方。它不是單一 MSE而是三部分加權(quán)和loss_coord: 僅對(duì)負(fù)責(zé)預(yù)測(cè)該物體的 grid cell 中的 bbox 計(jì)算即I_obj^ij 1的 cell且只計(jì)算(x,y,w,h)不包括 confloss_conf: 對(duì)所有 cell 計(jì)算但正樣本有物體用(C_i - C_i_hat)^2負(fù)樣本無物體用λ_noobj * (0 - C_i_hat)^2loss_class: 僅對(duì)有物體的 cell 計(jì)算類別預(yù)測(cè)誤差。本方案將 loss 封裝為自定義 Keras loss 函數(shù)關(guān)鍵代碼如下def yolo_v1_loss(y_true, y_pred): # y_true: (None, 7, 7, 30), y_pred: (None, 7, 7, 30) S, B, C 7, 2, 20 lambda_coord 5.0 lambda_noobj 0.5 # 1. 提取真實(shí)標(biāo)簽中的 object mask: (None, 7, 7) # y_true[..., 4] 和 y_true[..., 9] 分別是兩個(gè) bbox 的置信度原文中只用第一個(gè) # 實(shí)際我們只關(guān)心是否有物體取 max(4,9) 0 即認(rèn)為該 cell 有物體 obj_mask tf.reduce_max(y_true[..., 4::5], axis-1) # (None, 7, 7) obj_mask tf.expand_dims(obj_mask, axis-1) # (None, 7, 7, 1) # 2. 坐標(biāo) loss只對(duì) obj_mask1 的 cell 計(jì)算 (x,y,w,h) # 注意w,h 用 sqrt 計(jì)算避免大 bbox 梯度爆炸 coords_true y_true[..., :4*B] # (None, 7, 7, 8) coords_pred y_pred[..., :4*B] # (None, 7, 7, 8) loss_coord lambda_coord * tf.reduce_mean( obj_mask * tf.square(tf.sqrt(coords_true[..., 2:4*B:5]) - tf.sqrt(coords_pred[..., 2:4*B:5])) obj_mask * tf.square(coords_true[..., :4*B:5] - coords_pred[..., :4*B:5]) ) # 3. 置信度 loss正樣本用 obj_mask負(fù)樣本用 (1-obj_mask) conf_true y_true[..., 4:B*5:5] # (None, 7, 7, 2) conf_pred y_pred[..., 4:B*5:5] # (None, 7, 7, 2) loss_conf_obj tf.reduce_mean(obj_mask * tf.square(conf_true - conf_pred)) loss_conf_noobj lambda_noobj * tf.reduce_mean((1 - obj_mask) * tf.square(conf_pred)) loss_conf loss_conf_obj loss_conf_noobj # 4. 類別 loss只對(duì) obj_mask1 的 cell 計(jì)算 C 維 one-hot class_true y_true[..., B*5:] # (None, 7, 7, 20) class_pred y_pred[..., B*5:] # (None, 7, 7, 20) loss_class tf.reduce_mean(obj_mask * tf.square(class_true - class_pred)) return loss_coord loss_conf loss_class注意這段代碼里coords_true[..., 2:4*B:5]的切片邏輯極易出錯(cuò)。2:4*B:5表示從索引 2 開始步長(zhǎng)為 5取4*B個(gè)元素中的 w,h 維度即索引 2,3,7,8,...。我第一次寫時(shí)漏了:5導(dǎo)致取了全部 8 個(gè)值loss 爆炸。建議在訓(xùn)練前用model.compile(lossyolo_v1_loss, optimizeradam)后先model.evaluate(dummy_x, dummy_y)測(cè)試 loss 是否為有限值再開始正式訓(xùn)練。3. 數(shù)據(jù)集構(gòu)建與標(biāo)注規(guī)范從 VOC 到 YOLOv1 標(biāo)簽的精準(zhǔn)映射YOLOv1 不接受任意格式的標(biāo)注它對(duì)標(biāo)簽的物理意義、數(shù)值范圍、存儲(chǔ)結(jié)構(gòu)有強(qiáng)約定。本方案提供了一套完整的轉(zhuǎn)換腳本voc_to_yolo1.py但更重要的是理解“為什么這樣轉(zhuǎn)”。3.1 PASCAL VOC 標(biāo)注的局限性與 YOLOv1 的適配改造VOC 的.xml文件記錄的是xminyminxmaxymax像素坐標(biāo)而 YOLOv1 要求所有坐標(biāo)必須歸一化到[0,1]中心點(diǎn)(x_center, y_center)和寬高(w, h)必須是相對(duì)于整張圖的比例每個(gè).txt標(biāo)簽文件一行一個(gè)物體格式為class_id x_center y_center w hclass_id從 0 開始且必須與classes.txt中順序嚴(yán)格一致。轉(zhuǎn)換腳本核心邏輯如下def voc_to_yolo1(xml_path, image_path, classes_file, output_txt_path): tree ET.parse(xml_path) root tree.getroot() size root.find(size) img_w int(size.find(width).text) img_h int(size.find(height).text) with open(classes_file, r) as f: classes [line.strip() for line in f.readlines()] with open(output_txt_path, w) as out_f: for obj in root.iter(object): cls_name obj.find(name).text if cls_name not in classes: continue cls_id classes.index(cls_name) xmlbox obj.find(bndbox) xmin int(xmlbox.find(xmin).text) ymin int(xmlbox.find(ymin).text) xmax int(xmlbox.find(xmax).text) ymax int(xmlbox.find(ymax).text) # 轉(zhuǎn)換為 YOLOv1 格式中心點(diǎn) 寬高 歸一化 x_center ((xmin xmax) / 2.0) / img_w y_center ((ymin ymax) / 2.0) / img_h w (xmax - xmin) / img_w h (ymax - ymin) / img_h # 寫入class_id x_center y_center w h out_f.write(f{cls_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}\n)提示x_center和y_center必須是(xminxmax)/2除以img_w/img_h而不是(xmin/img_w xmax/img_w)/2—— 數(shù)學(xué)等價(jià)但浮點(diǎn)精度下后者可能引入微小誤差在int(y * S)時(shí)導(dǎo)致 grid cell 錯(cuò)位。我吃過這個(gè)虧一張圖里 3 個(gè)物體2 個(gè)進(jìn)了正確 cell1 個(gè)因y_center差了1e-8被int()截?cái)嗟礁舯?cell訓(xùn)練時(shí)該 cell 的I_obj^ij為 0但 loss 卻在懲罰它的 bbox 預(yù)測(cè)結(jié)果模型學(xué)不會(huì)定位。3.2 小樣本數(shù)據(jù)集的增強(qiáng)策略幾何變換優(yōu)先色彩擾動(dòng)次之YOLOv1 對(duì)數(shù)據(jù)量敏感但盲目增加ImageDataGenerator的rotation_range20或shear_range0.2會(huì)破壞 bbox 的幾何一致性。本方案推薦的增強(qiáng)組合是必選horizontal_flipTrue鏡像翻轉(zhuǎn)不改變 bbox 語(yǔ)義只需 x_center 1 - x_center慎選width_shift_range0.1, height_shift_range0.1平移后需同步調(diào)整 bbox 坐標(biāo)代碼已內(nèi)置禁用rotation_range,zoom_range,shear_range旋轉(zhuǎn)/縮放/錯(cuò)切會(huì)扭曲 bbox 形狀YOLOv1 無 anchor 機(jī)制無法適應(yīng)形變。增強(qiáng)后的圖像與標(biāo)簽必須同步保存腳本augment_and_save.py會(huì)生成_aug001.jpg和_aug001.txt并確保.txt中的坐標(biāo)已重算。3.3 數(shù)據(jù)集劃分與加載器Keras Sequence 的內(nèi)存友好實(shí)現(xiàn)為避免一次性加載所有圖片到內(nèi)存448×448×3×N 占用巨大本方案使用keras.utils.Sequence自定義生成器class YOLOv1DataGenerator(Sequence): def __init__(self, image_paths, label_paths, batch_size8, shuffleTrue): self.image_paths image_paths self.label_paths label_paths self.batch_size batch_size self.shuffle shuffle self.on_epoch_end() def __len__(self): return int(np.ceil(len(self.image_paths) / self.batch_size)) def __getitem__(self, index): batch_indices self.indices[index*self.batch_size:(index1)*self.batch_size] batch_images [] batch_labels [] for i in batch_indices: img, label preprocess_image( self.image_paths[i], self.label_paths[i], input_size448, S7, B2, C20 ) batch_images.append(img) batch_labels.append(label) return np.array(batch_images), np.array(batch_labels) def on_epoch_end(self): self.indices np.arange(len(self.image_paths)) if self.shuffle: np.random.shuffle(self.indices)__getitem__中調(diào)用preprocess_image是關(guān)鍵。它保證每次 yield 的都是實(shí)時(shí)處理后的(448,448,3)和(7,7,30)內(nèi)存占用恒定且支持shuffleTrue下的真隨機(jī)。4. 模型訓(xùn)練與超參調(diào)優(yōu)從學(xué)習(xí)率衰減到早停策略的實(shí)戰(zhàn)配置YOLOv1 訓(xùn)練不是“run train.py 等 100 epoch”而是一場(chǎng)與 loss 曲線的耐心博弈。本方案的train.py提供了開箱即用的配置但真正決定成敗的是以下三個(gè)超參的協(xié)同。4.1 學(xué)習(xí)率調(diào)度階梯式衰減 warmup 的雙階段控制YOLOv1 原文使用lr0.001但直接使用會(huì)導(dǎo)致初期 loss 震蕩劇烈。本方案采用warmup step decay# warmup前 5 個(gè) epochlr 從 1e-5 線性升到 0.001 def warmup_step_decay(epoch): if epoch 5: return 1e-5 (0.001 - 1e-5) * epoch / 5.0 else: # 階梯衰減每 30 epoch 降為 0.1 倍 return 0.001 * (0.1 ** (epoch // 30)) lr_scheduler LearningRateScheduler(warmup_step_decay)為什么是 5 和 30因?yàn)?backbone 的 24 層卷積參數(shù)量大前 5 epoch 是讓淺層特征提取器“熱身”避免初始梯度爆炸而 30 epoch 是經(jīng)驗(yàn)閾值——在多數(shù)小數(shù)據(jù)集2000 圖上loss 在此之后下降緩慢繼續(xù)訓(xùn)練易過擬合。4.2 優(yōu)化器選擇Adam 優(yōu)于 SGD 的實(shí)證依據(jù)YOLOv1 原文用 SGD momentum但本方案實(shí)測(cè) Adam 更穩(wěn)定。原因在于Adam 的自適應(yīng)學(xué)習(xí)率能更好處理loss_coord數(shù)值小、loss_conf數(shù)值大、loss_class數(shù)值中三者量綱差異beta_10.9, beta_20.999的默認(rèn)設(shè)置對(duì) YOLOv1 的梯度分布匹配度高不需要手動(dòng)調(diào)momentum和nesterov。optimizer Adam(learning_rate0.001, beta_10.9, beta_20.999, epsilon1e-07) model.compile(optimizeroptimizer, lossyolo_v1_loss)避坑 / 常見問題 / 排查 / 注意現(xiàn)象訓(xùn)練第 1 個(gè) epoch 后loss_coord突增至1e5以上loss_conf接近 0原因preprocess_image中x_cell S * x - j計(jì)算錯(cuò)誤j用了int(x * S)但x未歸一化導(dǎo)致x_cell為負(fù)數(shù)或 1sqrt(w)報(bào)錯(cuò)梯度爆炸解決檢查preprocess_image輸入的x,y,w,h是否已歸一化加斷言assert 0 x 1 and 0 y 1現(xiàn)象val_loss持續(xù)下降但val_loss_coord卻上升原因驗(yàn)證集標(biāo)注中存在w或h為 0 的無效 bbox如xminxmax導(dǎo)致sqrt(w)為 0loss_coord計(jì)算時(shí)出現(xiàn)nanKeras 自動(dòng)忽略該樣本但loss_coord分母變小數(shù)值虛高解決在voc_to_yolo1.py中加入if w 0.001 and h 0.001:過濾極小 bbox現(xiàn)象訓(xùn)練 50 epoch 后所有預(yù)測(cè) bbox 的conf都趨近于 0.5class輸出混亂原因lambda_noobj0.5過小負(fù)樣本置信度 loss 權(quán)重不足模型學(xué)會(huì)“保守預(yù)測(cè)”對(duì)所有 cell 都輸出中等 conf解決將lambda_noobj提高到1.0或2.0強(qiáng)制模型區(qū)分有/無物體 cell現(xiàn)象model.predict()輸出的(7,7,30)中conf值全為 0 或 1無中間值原因Dense層后未加sigmoid激活conf和class預(yù)測(cè)值未經(jīng)壓縮直接進(jìn)入 loss 計(jì)算導(dǎo)致梯度飽和解決在build_detection_head的Dense層后對(duì)conf和class部分加sigmoidoutput_tensor tf.concat([tf.sigmoid(conf_part), tf.sigmoid(class_part)], axis-1)現(xiàn)象訓(xùn)練過程 GPU 顯存占用從 2GB 漲到 12GB 后 OOM原因tf.data.Dataset或Sequence中batch_size過大且preprocess_image內(nèi)部未釋放臨時(shí)變量如cv2.imread返回的img解決preprocess_image結(jié)尾加del img, img_resized或改用tf.io.read_filetf.image.decode_jpeg由 TensorFlow 圖優(yōu)化內(nèi)存4.3 早停與模型保存基于val_loss_coord的精準(zhǔn)干預(yù)YOLOv1 的最終目標(biāo)是精確定位因此不能只看val_loss。本方案監(jiān)控val_loss_coordearly_stopping EarlyStopping( monitorval_loss_coord, # 自定義 metric需在 compile 時(shí)注冊(cè) patience15, verbose1, modemin, restore_best_weightsTrue ) model_checkpoint ModelCheckpoint( best_yolov1.h5, monitorval_loss_coord, save_best_onlyTrue, modemin )要讓EarlyStopping識(shí)別val_loss_coord需在compile時(shí)注冊(cè)自定義 metricdef loss_coord_metric(y_true, y_pred): # 復(fù)制 loss_coord 計(jì)算邏輯返回 scalar # 代碼同 loss 函數(shù)中 loss_coord 部分略 return loss_coord_scalar model.compile( optimizeroptimizer, lossyolo_v1_loss, metrics[loss_coord_metric, accuracy] # accuracy 此處無意義僅為占位 )5. 模型推理與結(jié)果可視化從 raw output 到可交付檢測(cè)圖的全流程訓(xùn)練完的.h5模型不能直接用于檢測(cè)必須經(jīng)過后處理Post-processing才能得到人類可讀的 bounding box。本方案的inference.py封裝了完整 pipeline。5.1 Raw Output 解析從(7,7,30)到候選 bbox 列表模型輸出pred model.predict(img_batch)后pred是(1,7,7,30)。解析步驟如下def parse_prediction(pred, S7, B2, C20, confidence_threshold0.3, iou_threshold0.4): # pred: (1, 7, 7, 30) pred pred[0] # (7, 7, 30) bboxes [] for i in range(S): for j in range(S): # 取該 cell 的兩個(gè) bbox 預(yù)測(cè) for b in range(B): # 置信度 conf pred[i, j, 4 b*5] if conf confidence_threshold: continue # 中心點(diǎn)相對(duì)于 cell x_cell pred[i, j, b*5] y_cell pred[i, j, b*5 1] # 寬高相對(duì)于整圖 w pred[i, j, b*5 2] h pred[i, j, b*5 3] # 還原到整圖坐標(biāo) [0,1] x (j x_cell) / S y (i y_cell) / S # 轉(zhuǎn)為 (xmin, ymin, xmax, ymax) 歸一化坐標(biāo) xmin max(0, x - w/2) ymin max(0, y - h/2) xmax min(1, x w/2) ymax min(1, y h/2) # 類別概率20 維 class_probs pred[i, j, B*5:] cls_id np.argmax(class_probs) cls_score class_probs[cls_id] final_score conf * cls_score # YOLOv1 的最終置信度 obj_conf * class_prob if final_score confidence_threshold: bboxes.append([xmin, ymin, xmax, ymax, final_score, cls_id]) # 轉(zhuǎn) numpy array 并做 NMS if len(bboxes) 0: return [] bboxes np.array(bboxes) keep non_max_suppression(bboxes, iou_threshold) return bboxes[keep] def non_max_suppression(bboxes, iou_thresh): # 標(biāo)準(zhǔn) NMS 實(shí)現(xiàn)按 score 降序計(jì)算 IOU抑制重疊 # 代碼略詳見 utils.py pass注意final_score conf * cls_score是 YOLOv1 的核心設(shè)計(jì)不是后加的 trick。conf表示“這個(gè) cell 里有物體的概率”cls_score表示“這個(gè)物體是某類的概率”二者相乘才是“這個(gè) bbox 是某類物體的置信度”。漏乘會(huì)導(dǎo)致高 conf 低 cls 的 bbox 被保留檢測(cè)結(jié)果全是“疑似物體”。5.2 可視化腳本支持 OpenCV 與 Matplotlib 雙引擎為適配不同環(huán)境服務(wù)器無 GUI / 本地調(diào)試visualize.py提供兩種模式def draw_bboxes_cv2(image, bboxes, classes, colors): # image: (H,W,3) uint8 h, w image.shape[:2] for box in bboxes: xmin, ymin, xmax, ymax, score, cls_id box # 歸一化坐標(biāo)轉(zhuǎn)像素 x1, y1, x2, y2 int(xmin*w), int(ymin*h), int(xmax*w), int(ymax*h) color colors[int(cls_id) % len(colors)] cv2.rectangle(image, (x1,y1), (x2,y2), color, 2) label f{classes[int(cls_id)]}: {score:.2f} cv2.putText(image, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1) return image def draw_bboxes_plt(image, bboxes, classes, colors): # image: (H,W,3) float32 [0,1] plt.figure(figsize(12,8)) plt.imshow(image) for box in bboxes: xmin, ymin, xmax, ymax, score, cls_id box rect patches.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, linewidth2, edgecolorcolors[int(cls_id)%len(colors)], facecolornone) plt.gca().add_patch(rect) plt.text(xmin, ymin-0.02, f{classes[int(cls_id)]}: {score:.2f}, colorcolors[int(cls_id)%len(colors)], fontsize10) plt.axis(off) plt.show()5.3 檢測(cè)性能評(píng)估m(xù)AP 計(jì)算的輕量級(jí)實(shí)現(xiàn)本方案不依賴 pycocotools安裝復(fù)雜而是用sklearn.metrics.average_precision_score實(shí)現(xiàn) VOC 風(fēng)格 mAPdef calculate_voc_ap(precisions, recalls): # VOC 11-point interpolation ap 0 for t in np.arange(0, 1.1, 0.1): if np.sum(recalls t) 0: p 0 else: p np.max(precisions[recalls t]) ap p / 11.0 return ap def evaluate_model(model, test_generator, classes, iou_thresh0.5): all_scores [] all_labels [] all_dets [] all_gts [] for i, (x_batch, y_batch) in enumerate(test_generator): preds model.predict(x_batch) for j in range(len(x_batch)): # 解析 pred[j] 得到 det_boxes det_boxes parse_prediction(preds[j:j1], ...) # 從 y_batch[j] 解析 gt_boxes逆向 preprocess_image gt_boxes decode_label(y_batch[j]) all_dets.append(det_boxes) all_gts.append(gt_boxes) # 計(jì)算 per-class AP aps {} for cls_id in range(len(classes)): scores, labels [], [] for dets, gts in zip(all_dets, all_gts): # 計(jì)算該類別的 TP/FP/FN tp, fp, fn compute_tp_fp_fn(dets, gts, cls_id, iou_thresh) scores.extend([det[4] for det in dets if det[5]cls_id]) labels.extend([1 if tp_i else 0 for tp_i in tp]) if len(labels) p a hrefhttps://download.csdn.net/download/2401_87496566/89843308 stylecolor:#ec7500;font-size:14px; 本文還有配套的精品資源點(diǎn)擊獲取 /a img altmenu-r.4af5f7ec.gif srchttps://csdnimg.cn/release/wenkucmsfe/public/img/menu-r.4af5f7ec.gif stylewidth:16px;margin-left:4px;vertical-align:text-bottom;cursor:text; /p