Search code examples
pythonpython-3.xmachine-learningscikit-learn

model.compile loss TypeError: Missing required positional argument


The minimum example is

import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras.losses import huber

# create dataset
x = np.random.rand(10, 1)
y = 2 * x + np.random.randn(10, 1) * 0.1

# define model
model = keras.Sequential([
    keras.layers.Dense(1, input_shape=[1])
])

# compile model
# model.compile(loss=huber, optimizer='adam')  # works
# model.compile(loss='huber', optimizer='adam')  # works
model.compile(loss=huber(delta=0.1), optimizer='adam')

# training
model.fit(x, y, epochs=5)

when I use huber loss in model.compile(), these two ways work.

from keras.losses import huber
model.compile(loss="huber", optimizer=optimizer='adam')

or 

model.compile(loss=huber, optimizer=optimizer='adam')

But if I want to add delta, there will be a TypeError. What's the right way to add delta? Thank you for advance.


---> 18 model.compile(loss=huber(delta=delta), optimizer='adam')
     

File ~/anaconda3/envs/py38/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    151 except Exception as e:
...
-> 1170 result = api_dispatcher.Dispatch(args, kwargs)
   1171 if result is not NotImplemented:
   1172   return result

TypeError: Missing required positional argument

Solution

  • You need to build a partial function with delta set. There are several ways to do this. One would be the following:

    model.compile(loss=lambda x, y: huber(x, y, delta=delta), optimizer='adam')
    

    or just use the capital H Huber:

    model.compile(loss=lambda x, y: tf.keras.losses.Huber(delta=delta), optimizer='adam')