Python 在Keras的本地化
我有一个机器学习CNN,它应该对图像中的物体进行分类和定位。输入是一个尺寸为(448、448、3)的RGB图像,输出是24(对于边界框坐标,因为图像中有多个对象,最多6个,图像的id为6)。下面是我如何定义模型的:Python 在Keras的本地化,python,python-3.x,tensorflow,keras,Python,Python 3.x,Tensorflow,Keras,我有一个机器学习CNN,它应该对图像中的物体进行分类和定位。输入是一个尺寸为(448、448、3)的RGB图像,输出是24(对于边界框坐标,因为图像中有多个对象,最多6个,图像的id为6)。下面是我如何定义模型的: def define_model(): input = Input(shape = (448,448,3) x = Conv2D(32, (3,3), activation = 'relu')(input) x = MaxPooling2D((3,3))(x
def define_model():
input = Input(shape = (448,448,3)
x = Conv2D(32, (3,3), activation = 'relu')(input)
x = MaxPooling2D((3,3))(x)
x = Conv2D(64, (3,3), activation = 'relu')(x)
x = MaxPooling2D((3,3))(x)
x = Conv2D(64, (3,3), activation = 'relu')(x)
x = Conv2D(32, (3,3), activation = 'relu')(x)
x = GlobalAveragePooling2D()(x)
classification_output_head = Flatten()(x)
classification_output_head = Dropout(0.1)(classification_output_head)
classification_output_head = Dense(6, activation = 'sigmoid', name = 'class_of_objs')(classification_output_head)
regression_for_bounding_box_output_head = Flatten()(x)
regression_for_bounding_box_output_head = Dense(64, activation = 'relu')((regression_for_bounding_box_output_head))
regression_for_bounding_box_output_head = Dense(32, activation = 'relu')(regression_for_bounding_box_output_head)
regression_for_bounding_box_output_head = Dense(24, activation = 'sigmoid', name = 'bounding_box')(regression_for_bounding_box_output_head)
return Model(inputs=[input], outputs=[classification_output_head, regression_for_bounding_box_output_head])
model = define_model()
然后我定义模型:
def define_model():
input = Input(shape = (448,448,3)
x = Conv2D(32, (3,3), activation = 'relu')(input)
x = MaxPooling2D((3,3))(x)
x = Conv2D(64, (3,3), activation = 'relu')(x)
x = MaxPooling2D((3,3))(x)
x = Conv2D(64, (3,3), activation = 'relu')(x)
x = Conv2D(32, (3,3), activation = 'relu')(x)
x = GlobalAveragePooling2D()(x)
classification_output_head = Flatten()(x)
classification_output_head = Dropout(0.1)(classification_output_head)
classification_output_head = Dense(6, activation = 'sigmoid', name = 'class_of_objs')(classification_output_head)
regression_for_bounding_box_output_head = Flatten()(x)
regression_for_bounding_box_output_head = Dense(64, activation = 'relu')((regression_for_bounding_box_output_head))
regression_for_bounding_box_output_head = Dense(32, activation = 'relu')(regression_for_bounding_box_output_head)
regression_for_bounding_box_output_head = Dense(24, activation = 'sigmoid', name = 'bounding_box')(regression_for_bounding_box_output_head)
return Model(inputs=[input], outputs=[classification_output_head, regression_for_bounding_box_output_head])
model = define_model()
以下是剩下的:
losses = {'class_of_objs': 'sparse_categorical_crossentropy',
'bounding_box': 'mse'}
model.compile('adam', loss=losses, metrics=['mae'])
tloader = tf.data.Dataset.from_tensor_slices((x, y_class, y_bbox))
model.fit(tloader,epochs=100)
运行model.fit时,出现以下错误:
Epoch 1/100
WARNING:tensorflow:Model was constructed with shape (None, 448, 448, 3) for input Tensor("input_25:0", shape=(None, 448, 448, 3), dtype=float32), but it was called on an input with incompatible shape (448, 448, 3).
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-308-70dc0cc6919c> in <module>
----> 1 model.fit(tloader,epochs=100)
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
106 def _method_wrapper(self, *args, **kwargs):
107 if not self._in_multi_worker_mode(): # pylint: disable=protected-access
--> 108 return method(self, *args, **kwargs)
109
110 # Running inside `run_distribute_coordinator` already.
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing) 1096 batch_size=batch_size): 1097 callbacks.on_train_batch_begin(step)
-> 1098 tmp_logs = train_function(iterator) 1099 if data_handler.should_sync: 1100 context.async_wait()
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
778 else:
779 compiler = "nonXla"
--> 780 result = self._call(*args, **kwds)
781
782 new_tracing_count = self._get_tracing_count()
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
821 # This is the first call of __call__, so we have to initialize.
822 initializers = []
--> 823 self._initialize(args, kwds, add_initializers_to=initializers)
824 finally:
825 # At this point we know that the initialization is complete (or less
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
695 self._concrete_stateful_fn = (
--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected(
# pylint: disable=protected-access
697 *args, **kwds))
698
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args,
**kwargs) 2853 args, kwargs = None, None 2854 with self._lock:
-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) 2856 return graph_function 2857
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) 3211 3212 self._function_cache.missed.add(call_context_key)
-> 3213 graph_function = self._create_graph_function(args, kwargs) 3214 self._function_cache.primary[cache_key] = graph_function 3215 return graph_function, args, kwargs
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 3063 arg_names = base_arg_names + missing_arg_names 3064 graph_function = ConcreteFunction(
-> 3065 func_graph_module.func_graph_from_py_func( 3066 self._name, 3067 self._python_function,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
984 _, original_func = tf_decorator.unwrap(python_func)
985
--> 986 func_outputs = python_func(*func_args, **func_kwargs)
987
988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
598 # __wrapped__ allows AutoGraph to swap in a converted function. We give
599 # the function a weak reference to itself to avoid a reference cycle.
--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)
601 weak_wrapped_fn = weakref.ref(wrapped_fn)
602
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
971 except Exception as e: # pylint:disable=broad-except
972 if hasattr(e, "ag_error_metadata"):
--> 973 raise e.ag_error_metadata.to_exception(e)
974 else:
975 raise
纪元1/100
警告:tensorflow:为输入张量(“input_25:0”,shape=(None,448,448,3),dtype=float32)构造了形状(None,448,448,3)的模型,但在具有不兼容形状(448,448,3)的输入上调用了该模型。
---------------------------------------------------------------------------中的ValueError回溯(最近一次调用)
---->1型号配合(t装载机,历代=100)
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in\u method\u包装(self,*args,**kwargs)
106定义方法包装(self,*args,**kwargs):
107如果不是self._处于_multi_worker_模式():#pylint:disable=受保护的访问
-->108返回方法(self、*args、**kwargs)
109
110#已经在“运行分配协调器”内部运行了。
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in-fit(self、x、y、批大小、历元、冗余、回调、验证拆分、验证数据、洗牌、类权重、样本权重、初始历元、每个历元的步骤、验证步骤、验证批次大小、验证频率、最大队列大小、工作人员、使用多处理)1096批大小=批大小):1097回调。列车上的批处理开始(步骤)
->1098 tmp_logs=训练函数(迭代器)1099 if data_handler.should_sync:1100 context.async_wait()
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py在调用中(self,*args,**kwds)
778其他:
779 compiler=“nonXla”
-->780结果=自身调用(*args,**kwds)
781
782 new_tracing_count=self._get_tracing_count()
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in_调用(self,*args,**kwds)
821#这是"调用"的第一个调用,因此我们必须初始化。
822个初始值设定项=[]
-->823自身初始化(参数、KWD、添加初始化器到=初始化器)
824最后:
825#此时我们知道初始化已完成(或更少)
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in_initialize(self、args、kwds、add_initializers_to)
694 self.\u graph\u deleter=函数deleter(self.\u lifted\u initializer\u graph)
695自具体状态fn=(
-->696自我状态功能获取具体功能内部垃圾收集(
#pylint:disable=受保护的访问
697*args,**科威特第纳尔)
698
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in\u get\u concrete\u function\u internal\u garbage\u collected(self,*args,
**kwargs)2853 args,kwargs=None,None 2854带self.\u锁:
->2855图形函数,可能定义函数(args,kwargs)2856返回图形函数2857
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in\u maybe\u define\u function(self、args、kwargs)3211 3212 self.\u function\u cache.missed.add(调用上下文键)
->3213图形函数=自。\创建图形函数(args,kwargs)3214自。\函数\u缓存。主[缓存\u键]=图形函数3215返回图形函数,args,kwargs
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in\u create\u graph\u function(self、args、kwargs、override\u flat\u arg\u shapes)3063 arg\u names=基本arg\u names+缺少arg\u names 3064 graph\u function=具体函数(
->3065函数图模块。函数图来自于函数(3066 self.\u名称,3067 self.\u python函数,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func\u graph.py in func\u graph\u from\u py func(name,python\u func,args,kwargs,signature,func\u graph,autograph,options,add\u control\u依赖项,arg\u名称,op\u返回值,集合,按值捕获,覆盖平面arg\u形状)
984,original_func=tf_decorator.unwrap(python_func)
985
-->986 func_输出=python_func(*func_参数,**func_参数)
987
988#不变量:`func_outputs`只包含张量、复合传感器、,
~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args,**kwds)
598#uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
599#函数对自身进行弱引用以避免引用循环。
-->600返回弱_-wrapped_-fn()
601弱包层=弱包层参考(包层)
602
包装器中的~/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py(*args,**kwargs)
971例外情况为e:#pylint:disable=broad except
972如果hasattr(e,“AGU错误元数据”):
-->973将e.ag\u错误\u元数据引发到\u异常(e)
974其他:
975提高
如何修复它在调用model.fit之前,您必须使用model.complile编译模型,在该模型上设置losse,并按照以下方式选择优化器:
model.compile(optimizer=“Adam”,loss=“mse”,metrics=[“mae”])
很抱歉,我确实这么做了,但没有把它放在帖子里。您的回溯海报不完整。@Dr.Snoopy您能详细说明一下吗,我似乎不明白您的意思