اذهب إلى المحتوى

السؤال

نشر

قمت ببناء نموذج لتصنيف الصور مكون من عدة طبقات CNN و AveragePooling  لكن لا أعلم سبب الخطأ التالي:

# write your model here, we prefer that you call it model2 to make comparisions easier later:
model2 = keras.Sequential()
model2.add(layers.Conv2D(filters=6, kernel_size=(3, 3), activation='relu', input_shape=(150,150,3)))
model2.add(layers.AveragePooling2D())
model2.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu'))
model2.add(layers.AveragePooling2D())
model2.add(layers.Dense(units=120, activation='tanh'))
model2.add(layers.Dense(units=84, activation='tanh'))
model2.add(layers.Dense(units=6, activation = 'softmax'))
model2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])
model2.fit(train_images, train_labels, batch_size=32, epochs=5, validation_split = 0.2)
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-9-89da9186b401> in <module>
      9 model2.add(layers.Dense(units=6, activation = 'softmax'))
     10 model2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])
---> 11 model2.fit(train_images, train_labels, batch_size=32, epochs=5, validation_split = 0.2)

~\anaconda3\lib\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)
   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()

~\anaconda3\lib\site-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()

~\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
    886         # Lifting succeeded, so variables are initialized and we can run the
    887         # stateless function.
--> 888         return self._stateless_fn(*args, **kwds)
    889     else:
    890       _, _, _, filtered_flat_args = \

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in __call__(self, *args, **kwargs)
   2941        filtered_flat_args) = self._maybe_define_function(args, kwargs)
   2942     return graph_function._call_flat(
-> 2943         filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access
   2944 
   2945   @property

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1917       # No tape is watching; skip to running the function.
   1918       return self._build_call_outputs(self._inference_function.call(
-> 1919           ctx, args, cancellation_manager=cancellation_manager))
   1920     forward_backward = self._select_forward_and_backward_functions(
   1921         args,

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    558               inputs=args,
    559               attrs=attrs,
--> 560               ctx=ctx)
    561         else:
    562           outputs = execute.execute_with_cancellation(

~\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [41472,6] and labels shape [32]
	 [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at <ipython-input-9-89da9186b401>:11) ]] [Op:__inference_train_function_1875]

Function call stack:
train_function

 

Recommended Posts

  • 1
نشر

يجب إضافة طبقة Flatten قبل أول طبقة Dense.
إن المرحلة الأخيرة من الشبكة العصبية التلافيفية (CNN) هي المصنف. يطلق عليه طبقة/طبقات Dense، وهي مجرد مصنف شبكة عصبية اصطناعية (ANN). ويحتاج مصنف ANN إلى ميزات فردية "individual features" ، تماماً مثل أي مصنف آخر. هذا يعني أنه يحتاج إلى "feature vector". لذلك، تحتاج إلى تحويل خرج الجزء التلافيفي من CNNs إلى Vector1D، ليتم استخدامه بواسطة جزء ANN. هذه العملية تسمى التسطيح "Flatten ".

# write your model here, we prefer that you call it model2 to make comparisions easier later:
model2 = keras.Sequential()
model2.add(layers.Conv2D(filters=6, kernel_size=(3, 3), activation='relu', input_shape=(150,150,3)))
model2.add(layers.AveragePooling2D())
model2.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu'))
model2.add(layers.AveragePooling2D())
model2.add(layers.Flatten()) # هنا
model2.add(layers.Dense(units=120, activation='tanh'))
model2.add(layers.Dense(units=84, activation='tanh'))
model2.add(layers.Dense(units=6, activation = 'softmax'))
model2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])
model2.fit(train_images, train_labels, batch_size=32, epochs=1, validation_split = 0.2)

 

  • 1
نشر

كما ذكر @Ali Haidar Ahmad فإن الناتج من الشبكة يجب أن يحصل لها تسطيح flatten ذلك لأن dense layer لا تقوم بهذه العملية بل تأخذه بنفس الشكل و توصله بالعقد في الشبكة العصبية، و مهمتها الأساسية هي تحويل multidimensional tensor لarray 1d وهي القيمة التي تستقبلها dense layer في neural network، وهي لا تؤثر على حجم batch في عملية التدريب.

اقتباس

class Flatten(Layer):

"""Flattens the input. Does not affect the batch size.

Note: If inputs are shaped `(batch,)` without a feature axis, then

flattening adds an extra channel dimension and output shape is `(batch, 1)`.

".

يمكن مراجعة المزيد من التفاصيل بالتعرف على classes في keras من هنا.

والان إذا قمنا بطباعة شكل النموذج بإستخدام model.summary قبل إضافة الflatten و بعدها سنحصل على الأشكال التالية بالتوالي:

Model: "sequential_21"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_36 (Conv2D)           (None, 148, 148, 6)       168       
_________________________________________________________________
average_pooling2d_34 (Averag (None, 74, 74, 6)         0         
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 72, 72, 16)        880       
_________________________________________________________________
average_pooling2d_35 (Averag (None, 36, 36, 16)        0         
_________________________________________________________________
dense_56 (Dense)             (None, 36, 36, 120)       2040      
_________________________________________________________________
dense_57 (Dense)             (None, 36, 36, 84)        10164     
_________________________________________________________________
dense_58 (Dense)             (None, 36, 36, 6)         510       
=================================================================
Total params: 13,762
Trainable params: 13,762
Non-trainable params: 0

و بعد الإضافة:

Model: "sequential_22"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_38 (Conv2D)           (None, 148, 148, 6)       168       
_________________________________________________________________
average_pooling2d_36 (Averag (None, 74, 74, 6)         0         
_________________________________________________________________
conv2d_39 (Conv2D)           (None, 72, 72, 16)        880       
_________________________________________________________________
average_pooling2d_37 (Averag (None, 36, 36, 16)        0         
_________________________________________________________________
flatten_9 (Flatten)          (None, 20736)             0         
_________________________________________________________________
dense_59 (Dense)             (None, 120)               2488440   
_________________________________________________________________
dense_60 (Dense)             (None, 84)                10164     
_________________________________________________________________
dense_61 (Dense)             (None, 6)                 510       
=================================================================
Total params: 2,500,162
Trainable params: 2,500,162
Non-trainable params: 0

لاحظ تغير عدد الparameters بعد إضافة flatten من (None, 36, 36, 16) إلى (None, 20736).

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...