自定义训练YOLOv4-tiny模型转换为TensorFlow模型时出现Reshape错误的解决方案咨询
The ValueError: cannot reshape array of size 607322 into shape (256,384,3,3) error occurs because the structure of your custom YOLOv4-Tiny model (defined in yolov4-tiny-device.cfg) doesn’t align with the hardcoded model architecture in the hunglc007/tensorflow-yolov4-tflite repository. Here’s how to fix it step by step:
1. Validate Your Custom YOLOv4-Tiny Config
First, confirm critical parameters in your yolov4-tiny-device.cfg match your single-class setup:
- Check that the
classesvalue under every[yolo]layer is set to1(since you have one custom class). - For each
[yolo]layer, the immediately preceding[convolutional]layer must havefilters = (classes + 5) * 3. For your single-class model, this equals(1 + 5)*3 = 18—ensure both of these convolutional layers in your cfg use this filter count. - Compare your cfg line-by-line with Darknet’s default
yolov4-tiny.cfgto catch any other structural changes (like modified filter counts in intermediate layers) that could break weight loading.
2. Update TensorFlow Repository Configs
Even though you updated __C.YOLO.CLASSES, you need to adjust additional settings to match your custom model:
- Open
core/config.pyand set__C.YOLO.NUM_CLASSES = 1—this tells the TensorFlow model how many classes to expect. - If you modified any intermediate convolutional layers in your cfg (e.g., changed filter counts), update the corresponding layers in
core/yolov4.py’syolov4_tiny()function. For example, if you changed a conv layer’s filter count from 256 to 128, adjust thefiltersparameter in the matchingconv2dcall in the TF code.
3. Debug the Weight Mismatch
The error points to a specific convolutional layer where the weight array size doesn’t fit the expected shape. To pinpoint the issue:
- Calculate the expected parameter count for each convolutional layer in your cfg:
For a conv layer with
filters=F,in_channels=I,kernel_size=K, total parameters =F * I * K * K(weights) +F(biases) =F*(I*K*K +1). - Add print statements in
core/utils.py’sload_weightsfunction to log the expected shape and actual weight size for each layer, then cross-reference with your cfg’s parameters. - Sync the TensorFlow code’s layer parameters with your cfg once you find the mismatched layer.
4. Re-run the Conversion Command
Double-check your command (yours looks correct, but confirm all flags align):
py ./save_model.py --weights ./data/yolov4-tiny-device_last.weights --output ./checkpoint/yolov4-tiny-device-416 --input_size 416 --model yolov4 --tiny
After updating configs and model structure, this command should load weights without reshaping errors.
内容的提问来源于stack exchange,提问作者Daniel Botnik

