Error when use L1 loss in U-Net

Hi,

I’m trying to synthesise MRI image derived from CT using U-Net segmentation. I tried to use L1 as loss function. But when i fit the model, error shows. Please help me on possible reasons. i’m pretty new to deep learning.

File “/var/folders/l0/z8r9pfhd6ls5r030zy0c3lrh0000gn/T/ipykernel_4657/4045245122.py”, line 39, in l1_loss *
for b in range(y_true_deonehot.shape[0]):
TypeError: ‘NoneType’ object cannot be interpreted as an integer

Basic parameters: batch size = 5, num_classes = 20, epoch = 90. input shape = [None, 300,300,1], output shape (None, 300, 300, 20). (20 is correspond to one-hot num_classes).

definition of model:
kernel_size = 3
filters_orig = 32
layer_depth = 4
use_batch_norm = batch_size > 1

inputs = Input(shape=(*image_size, num_channels), name=‘input’)
outputs = unet(inputs, out_channels=num_classes,
layer_depth=layer_depth, filters_orig=filters_orig,
kernel_size=kernel_size, batch_norm=use_batch_norm,
final_activation=“softmax”
)

unet_model = Model(inputs, outputs)

optimizer = tf.keras.optimizers.legacy.Adam()
unet_model.compile(optimizer=optimizer, loss=l1_loss,
metrics=[‘accuracy’])

train = tf.data.Dataset.zip((train_image,train_label))
val = tf.data.Dataset.zip((val_image,val_label))

def l1_loss(y_true,y_pred):
#input shape: one-hotted [batch,m,n,num_classes]
y_true_deonehot = tf.argmax(y_true, axis=-1)
y_pred_deonehot = tf.argmax(y_pred, axis=-1)

loss = []

for b in range(y_true_deonehot.shape[0]):
    t = tf.cast(y_true_deonehot[b,:,:],tf.float32)
    p = tf.cast(y_pred_deonehot[b,:,:],tf.float32)
    
    loss.append(np.mean(tf.abs(t-p)))

l1_loss = np.mean(loss)
return l1_loss

history = unet_model.fit(train, epochs=num_epochs, steps_per_epoch=train_steps_per_epoch,
validation_data=val, validation_steps=val_steps_per_epoch,
verbose=0)

Hi @Duo and Welcome to the Tensorflow forum.
Ain’t saying this will resolve your problem, but what I’m seeing reading fast through your code snippet is a star signe in the definition of your Input layer that shall probably not be there (?).
inputs = Input(shape=(*image_size, num_channels), name=‘input’)

thank you tagoma as my first replyer.

the star here is to unpack the parameter of image_size (defined as [300,300]) as correct operation of Input function. Thank you for your insights.

1 Like