gpt4 book ai didi

python - ValueError : Layer expects 2 input(s), 但它在训练 CNN 时收到 1 个输入张量

转载 作者:行者123 更新时间:2023-12-05 02:00:36 27 4
gpt4 key购买 nike

我是 tensorflow 的新手,正在尝试构建一个类似于 this guide 中的 Siamese CNN。 .
我的模型是使用基础模型构建的,然后通过同一网络向该模型提供两次不同的图片。
这是构建网络的代码:

class BaseModel(Model):

def __init__(self, base_network):
super(BaseModel, self).__init__()
self.network = base_network

def call(self, inputs):
print(inputs)
return self.network(inputs)

def get_base_model():
inputs = tf.keras.Input(shape=INPUT)

conv2d_1 = layers.Conv2D(name='seq_1', filters=64,
kernel_size=20,
activation='relu')(inputs)
maxpool_1 = layers.MaxPooling2D(pool_size=(2, 2))(conv2d_1)

conv2d_2 = layers.Conv2D(filters=128,
kernel_size=20,
activation='relu')(maxpool_1)
maxpool_2 = layers.MaxPooling2D(pool_size=(2, 2))(conv2d_2)

conv2d_3 = layers.Conv2D(filters=128,
kernel_size=20,
activation='relu')(maxpool_2)
maxpool_3 = layers.MaxPooling2D(pool_size=(2, 2))(conv2d_3)

conv2d_4 = layers.Conv2D(filters=256,
kernel_size=10,
activation='relu')(maxpool_3)

flatten_1 = layers.Flatten()(conv2d_4)
outputs = layers.Dense(units=4096,
activation='sigmoid')(flatten_1)

model = Model(inputs=inputs, outputs=outputs)

return model

然后,我正在使用以前的方法构建 Siamese 网络:

INPUT = (250, 250, 3)

def get_siamese_model():
left_input = layers.Input(name='img1', shape=INPUT)
right_input = layers.Input(name='img2', shape=INPUT)

base_model = get_base_model()
base_model = BaseModel(base_model)

# bind the two input layers to the base network
left = base_model(left_input)
right = base_model(right_input)

# build distance measuring layer
l1_lambda = layers.Lambda(lambda tensors:abs(tensors[0] - tensors[1]))
l1_dist = l1_lambda([left, right])

pred = layers.Dense(1,activation='sigmoid')(l1_dist)

return Model(inputs=[left_input, right_input], outputs=pred)

class SiameseNetwork(Model):

def __init__(self, siamese_network):
super(SiameseNetwork, self).__init__()
self.siamese_network = siamese_network

def call(self, inputs):
print(inputs)
return self.siamese_network(inputs)

然后我通过将 tf.data.Dataset 传递给它来训练网络:

net.fit(x=train_dataset, epochs=10 ,verbose=True)

train_dataset 的类型:

<PrefetchDataset shapes: ((None, 250, 250, 3), (None, 250, 250, 3)), types: (tf.float32, tf.float32)>

似乎输入的形状定义得很好,但我仍然遇到错误:

ValueError                                Traceback (most recent call last)
<ipython-input-144-6c5586e1e205> in <module>()
----> 1 net.fit(x=train_dataset, epochs=10 ,verbose=True)

9 frames
/usr/local/lib/python3.7/dist-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)
1098 _r=1):
1099 callbacks.on_train_batch_begin(step)
-> 1100 tmp_logs = self.train_function(iterator)
1101 if data_handler.should_sync:
1102 context.async_wait()

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
826 tracing_count = self.experimental_get_tracing_count()
827 with trace.Trace(self._name) as tm:
--> 828 result = self._call(*args, **kwds)
829 compiler = "xla" if self._experimental_compile else "nonXla"
830 new_tracing_count = self.experimental_get_tracing_count()

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
869 # This is the first call of __call__, so we have to initialize.
870 initializers = []
--> 871 self._initialize(args, kwds, add_initializers_to=initializers)
872 finally:
873 # At this point we know that the initialization is complete (or less

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
724 self._concrete_stateful_fn = (
725 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access
--> 726 *args, **kwds))
727
728 def invalid_creator_scope(*unused_args, **unused_kwds):

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
2967 args, kwargs = None, None
2968 with self._lock:
-> 2969 graph_function, _ = self._maybe_define_function(args, kwargs)
2970 return graph_function
2971

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
3359
3360 self._function_cache.missed.add(call_context_key)
-> 3361 graph_function = self._create_graph_function(args, kwargs)
3362 self._function_cache.primary[cache_key] = graph_function
3363

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
3204 arg_names=arg_names,
3205 override_flat_arg_shapes=override_flat_arg_shapes,
-> 3206 capture_by_value=self._capture_by_value),
3207 self._function_attributes,
3208 function_spec=self.function_spec,

/usr/local/lib/python3.7/dist-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)
988 _, original_func = tf_decorator.unwrap(python_func)
989
--> 990 func_outputs = python_func(*func_args, **func_kwargs)
991
992 # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
632 xla_context.Exit()
633 else:
--> 634 out = weak_wrapped_fn().__wrapped__(*args, **kwds)
635 return out
636

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
975 except Exception as e: # pylint:disable=broad-except
976 if hasattr(e, "ag_error_metadata"):
--> 977 raise e.ag_error_metadata.to_exception(e)
978 else:
979 raise

ValueError: in user code:

/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function *
return step_function(self, iterator)
<ipython-input-125-de3a74f810c3>:9 call *
return self.siamese_network(inputs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:998 __call__ **
input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/input_spec.py:207 assert_input_compatibility
' input tensors. Inputs received: ' + str(inputs))

ValueError: Layer model_16 expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 250, 250, 3) dtype=float32>]

我确实知道 model_16 是 BaseModel,但是我不知道我在这里做错了什么。

最佳答案

我已经找到问题了。经过时tf.data.Dataset作为xtensorflow默认 fit方法,它希望在相同的 Dataset 中接收两者 输入 目标。 .
因此,当传递具有两个输入图像的数据集时,第一个被传递到实际网络,第二个被忽略并被视为 true_y。 (目标)值。

这种情况下的修复,网络期望 n输入,是要有一个数据集,其中每个条目的长度都是 2 , 其中第一个是 tuple长度n代表网络的输入,第二个值是true_y ,例如 0 or 1在二元分类任务中。

在我的案例中,上面的解释归结为 train_dataset 的以下结构, validation_datasettest_dataset .

<PrefetchDataset shapes: (((None, 250, 250, 3), (None, 250, 250, 3)), (None,)), types: ((tf.float32, tf.float32), tf.int32)>

关于python - ValueError : Layer expects 2 input(s), 但它在训练 CNN 时收到 1 个输入张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67202194/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com