keras-yolo3: NameError: name 'yolo_head' is not defined

When I save weights during training using your original code, I got:

InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 12675 values, but the requested shape requires a multiple of 3042
	 [[Node: Reshape_3 = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv2d_59/BiasAdd, Reshape_3/shape)]]

Does this mean I should save model instead of weights? May I ask why in your code “model.save_weights” is used instead of “model.save_path”?

When I saved checkpoints in train.py as keras model, I wasn’t able to use it in yolo.py using load_model.

checkpoint = ModelCheckpoint(log_dir + "checkpoint.h5", monitor='val_loss', save_best_only=True)

history = model.fit([image_data, *y_true],
          np.zeros(len(image_data)),
          validation_split=.1,
          batch_size=Batch_Size,
          epochs=10000,
          callbacks=[checkpoint])

When I use yolo.py to test the trained model on images, model is loaded using

self.yolo_model = load_model(model_path, compile=False)

I got this error:

2018-05-10 05:47:25.060203: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
Traceback (most recent call last):
  File "/home/jin/workspace/Intersection_TrafficFlow/detection/keras-yolo3-noaug/keras-yolo3-1/yolo.py", line 229, in <module>
    detect_img(YOLO())
  File "/home/jin/workspace/Intersection_TrafficFlow/detection/keras-yolo3-noaug/keras-yolo3-1/yolo.py", line 58, in __init__
    self.boxes, self.scores, self.classes = self.generate()
  File "/home/jin/workspace/Intersection_TrafficFlow/detection/keras-yolo3-noaug/keras-yolo3-1/yolo.py", line 80, in generate
    self.yolo_model = load_model(model_path, compile=False)
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/models.py", line 243, in load_model
    model = model_from_config(model_config, custom_objects=custom_objects)
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/models.py", line 317, in model_from_config
    return layer_module.deserialize(config, custom_objects=custom_objects)
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/layers/__init__.py", line 55, in deserialize
    printable_module_name='layer')
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/utils/generic_utils.py", line 144, in deserialize_keras_object
    list(custom_objects.items())))
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/engine/topology.py", line 2524, in from_config
    process_node(layer, node_data)
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/engine/topology.py", line 2483, in process_node
    layer(input_tensors, **kwargs)
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/engine/topology.py", line 619, in __call__
    output = self.call(inputs, **kwargs)
  File "/home/jin/anaconda3/envs/keras-yolo3-noaug/lib/python3.6/site-packages/keras/layers/core.py", line 663, in call
    return self.function(inputs, **arguments)
  File "/home/jinz1/Jin/Intersection_TrafficFlow/detection/keras-yolo3-noaug/keras-yolo3-1/yolo3/model.py", line 347, in yolo_loss
NameError: name 'yolo_head' is not defined

Thank you very much for your help and for creating this repo!

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 32 (1 by maintainers)

Most upvoted comments

you can

model = load_model('smoke_final.h5',{'yolo_head': yolo_head})

but is other error

  File "D:\yolov3\keras-yolo3_phone\yolo3\model.py", line 376, in yolo_loss
    anchors[anchor_mask[l]], num_classes, input_shape, calc_loss=True)
TypeError: list indices must be integers or slices, not list

Error 2, yolo_head is in yolo3/model.py, so the error shouldn’t happen.

I got this error too.

With weight files, you can run model = yolo_body(Input(shape=(None, None, 3)), 3, num_classes) to create model structure, then model.load_weights('weights.h5') to load weights.

Your error 1, the model handles 20 classes, but you want it to handle 1. There is a conflict. Error 2, yolo_head is in yolo3/model.py, so the error shouldn’t happen.

Excitedly, I have solved the problem.

The core problem is “the trained model that you want to save and the model defined in the —.cfg file must be same”.

Nacturally, during training, the model has only one output in this code, i.e., L2 loss. However, in the —.cfg file, the output is a group of feature maps that is determined by the number of classes and the number of anchors.

So, the solution is that “First, defining a network that is same with the model in the —.cfg file. Then, loading the learned parameters to this defined network and using ‘model.save(‘model.h5’)’ to save this model. Final, convert it to any form”.

This way has been verified on the task of converting a keras model (.h5) to a darknet model.

you can

model = load_model('smoke_final.h5',{'yolo_head': yolo_head})

but is other error

  File "D:\yolov3\keras-yolo3_phone\yolo3\model.py", line 376, in yolo_loss
    anchors[anchor_mask[l]], num_classes, input_shape, calc_loss=True)
TypeError: list indices must be integers or slices, not list

I stuck with exactly this error when trying to load an model which is saved with model.save instead of model.save_weights.

I transform it sucessfully. It doesnot need to change save function, I use the below function to save weights and got ‘trained_weights.h5’. model.save_weights(log_dir + ‘trained_weights.h5’)

Then I use the below code:

from keras.layers import * import os import tensorflow as tf from yolo3.model import yolo_body def keras_to_tensorflow(keras_model, output_dir, model_name,out_prefix=“output_”, log_tensorboard=True): if os.path.exists(output_dir) == False: os.mkdir(output_dir) out_nodes = [] for i in range(len(keras_model.outputs)): out_nodes.append(out_prefix + str(i + 1)) tf.identity(keras_model.output[i], out_prefix + str(i + 1)) sess = K.get_session() from tensorflow.python.framework import graph_util, graph_io init_graph = sess.graph.as_graph_def() main_graph = graph_util.convert_variables_to_constants(sess, init_graph, out_nodes) graph_io.write_graph(main_graph, output_dir, name=model_name, as_text=False) if log_tensorboard: from tensorflow.python.tools import import_pb_to_tensorboard import_pb_to_tensorboard.import_to_tensorboard( os.path.join(output_dir, model_name), output_dir) keras_model = yolo_body(Input(shape=(None,None,3)), 3, 2) # my class_num=2 keras_model.load_weights(“D:\workspace\yolo\keras-yolo3-master\logs/000/trained_weights.h5”) output_dir = os.path.join(os.getcwd(),“checkpoint”) keras_to_tensorflow(keras_model,output_dir=“D:\workspace\yolo\keras-yolo3-master\logs/000”,model_name=“model.pb”) print(“MODEL SAVED”)

you can

model = load_model('smoke_final.h5',{'yolo_head': yolo_head})

but is other error

  File "D:\yolov3\keras-yolo3_phone\yolo3\model.py", line 376, in yolo_loss
    anchors[anchor_mask[l]], num_classes, input_shape, calc_loss=True)
TypeError: list indices must be integers or slices, not list

哥,我用你的方法进行测试

from tensorflow import keras 
from yolo3.model import yolo_head

model = keras.models.load_model('./trained_final.h5', {'yolo_head': yolo_head})

但是 谜一样的报错出现了:

  File "/home/keras-YOLOv3-mobilenet/yolo3/model.py", line 386, in yolo_loss
NameError: name 'tf' is not defined

没有改动过model.py文件,并且也明确了有 import tensorflow as tf 能帮忙看看么 谢谢

@vector-1127 哥们,你的意思是要用tensorflow按照—.cfg文件自己把Yolov3构建出来么?

对的,因为保存的模型要和cfg中的模型一样。

Error 2, yolo_head is in yolo3/model.py, so the error shouldn’t happen.

I got this error too.

Yes, me too, and I can confirm that yolo_head is there right in the file, this is tricky.