Lorenzo Viola
Lorenzo Viola

Reputation: 1

Weighted custom loss

I want to write the model using a custom loss, something like loss = sum(abs(y_true-y_pred)*returns), where returns is a vector containing different weights for each prediction (different vector for each dataset, and so different for training and test sets).

Here is my network using categorical_crossentropy loss. How is possible to change it?

model = Sequential()
model.add(Dense(2, activation='relu',input_shape=(X_train.shape[1],)) )
model.add(Dropout(0.1))
model.add(Dense(2, activation='relu', input_shape=(X_train.shape[1],)))
model.add(Dense(3, activation='softmax'))

callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=50)
model.compile(loss='categorical_crossentropy', optimizer='RMSprop', metrics=['AUC'])
epochs=1000

history = model.fit(X_train, y_train, epochs=epochs, batch_size=32,validation_data=(X_test, y_test),callbacks=[callback])

Upvotes: 0

Views: 57

Answers (1)

user7369463
user7369463

Reputation: 174

You need to declare a custom loss function:

def my_loss(y_true,y_pred): 
  return someFunc(y_true, y_pred)

And then pass it to model.compile:

model.compile(loss=my_loss, optimizer='RMSprop', metrics=['AUC'])

Upvotes: 0

Related Questions