pythondeep-learningconv-neural-networktensorflow-datasets

'str' object is not callable when fitting CNN model


I'm doing a deep learning project on detecting if a person has tuberculosis based on chest x-ray images. After reading and preprocess my data, I run into a problem when building my CNN model.

import tensorflow as tf
from tensorflow.keras import layers, models

input_shape = (32, 256, 256, 3)

model = models.Sequential([
    resize_and_rescale,
    layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
    layers.MaxPooling2D((2,2)),
    layers.Conv2D(64, (3,3), activation='relu'),
    layers.MaxPooling2D((2,2)),
    layers.Conv2D(64, (3,3), activation='relu'),
    layers.MaxPooling2D((2,2)),
    layers.Flatten(),

    layers.Dense(100, activation='relu'),
    layers.Dense(50, activation='relu'),
    layers.Dense(2, activation='softmax')
])

model.build(input_shape=input_shape)
model.summary()

Output:

Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 sequential (Sequential)     (32, 256, 256, 3)         0         
                                                                 
 conv2d (Conv2D)             (32, 254, 254, 32)        896       
                                                                 
 max_pooling2d (MaxPooling2  (32, 127, 127, 32)        0         
 D)                                                              
                                                                 
 conv2d_1 (Conv2D)           (32, 125, 125, 64)        18496     
                                                                 
 max_pooling2d_1 (MaxPoolin  (32, 62, 62, 64)          0         
 g2D)                                                            
                                                                 
 conv2d_2 (Conv2D)           (32, 60, 60, 64)          36928     
                                                                 
 max_pooling2d_2 (MaxPoolin  (32, 30, 30, 64)          0         
 g2D)                                                            
                                                                 
 flatten (Flatten)           (32, 57600)               0         
                                                                 
 dense (Dense)               (32, 100)                 5760100   
                                                                 
 dense_1 (Dense)             (32, 50)                  5050      
                                                                 
 dense_2 (Dense)             (32, 2)                   102       
                                                                 
=================================================================
Total params: 5821572 (22.21 MB)
Trainable params: 5821572 (22.21 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(),
              metrics=['accurary'])
model.fit(train_ds, batch_size=32, epochs=15, verbose=1, validation_data=val_ds)

Then this error pops up:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[16], line 1
----> 1 model.fit(train_ds, batch_size=32, epochs=15, verbose=1, validation_data=val_ds)

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\utils\traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     68     # To get the full stack trace, call:
     69     # `tf.debugging.disable_traceback_filtering()`
---> 70     raise e.with_traceback(filtered_tb) from None
     71 finally:
     72     del filtered_tb

File ~\AppData\Local\Temp\__autograph_generated_file_o3ecbkc.py:15, in outer_factory.<locals>.inner_factory.<locals>.tf__train_function(iterator)
     13 try:
     14     do_return = True
---> 15     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
     16 except:
     17     do_return = False

TypeError: in user code:

    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 1338, in train_function  *
        return step_function(self, iterator)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 1322, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 1303, in run_step  **
        outputs = model.train_step(data)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 1085, in train_step
        return self.compute_metrics(x, y, y_pred, sample_weight)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\training.py", line 1179, in compute_metrics
        self.compiled_metrics.update_state(y, y_pred, sample_weight)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\engine\compile_utils.py", line 605, in update_state
        metric_obj.update_state(y_t, y_p, sample_weight=mask)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\utils\metrics_utils.py", line 77, in decorated
        update_op = update_state_fn(*args, **kwargs)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\metrics\base_metric.py", line 140, in update_state_fn
        return ag_update_state(*args, **kwargs)
    File "C:\Users\tangb\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\metrics\base_metric.py", line 723, in update_state  **
        matches = ag_fn(y_true, y_pred, **self._fn_kwargs)

    TypeError: 'str' object is not callable

Notes:

This is my train dataset and validation dataset:

type(train_ds) # type(val_ds) gives the same output

Output:

tensorflow.python.data.ops.prefetch_op._PrefetchDataset

I visited this website: https://www.freecodecamp.org/news/typeerror-str-object-is-not-callable-how-to-fix-in-python/ to understand the cause but I can't still figure it out. I really appreciate any help, thanks.


Solution

  • It's just a typo in your code. In your model.compile(..., it's accuracy not accurary :v

    Here's the corrected:

    model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(),
                  metrics=['accuracy'])