> ## Content Index
> Fetch the complete content index at: https://bongholee.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Custom Loss Function in Keras
- URL: https://bongholee.com/custom-loss-function-in-keras/
- Published: 2023-07-10T05:21:14.000Z
- Updated: 2023-07-10T05:23:07.000Z
- Author: Bongho Lee
- Tags: Deep Learning, Data, #Import 2026-11-22 06:32

# Summary

- Business Impact에 기반해서 Loss Function을 수정해야할 필요가 있다.
- 예를 들어 비대칭 구조(예: 지수분포)에서는 Loss값에 Weight를 줘야하는 상황이 그렇다.
- Keras에서는 Model에 필요한 제반 환경을 Complie이라는 단계에서 설정하는데 이 때 Loss Function을 Keras 라이브러리에서 불러올 수도 있지만 앞서 언급한 바와 같이 Custom Loss Function을 설정할 수 있다.

# Example

- 여기서 AMSE는 Asymmetric Mean Squared Error의 준말이다.

```python

import keras.backend as K
from keras import models
from keras import layers

def AMSE(y_true, y_pred):
	loss = K.square(y_pred - y_true)
	loss = (loss**2)*10.0 if loss < 0 else loss**2
	return loss

def build_model():
	model = models.Sequential()
	model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
	model.add(layers.Dense(64, activation='relu'))
	model.add(layers.Dense(1))
	model.compile(optimizer='rmsprop', loss = AMSE, metrics=['mae'])
	return model 

```

# References

- [https://keras.io/api/losses/regression\_losses/#meansquarederror-class](https://keras.io/api/losses/regression%5Flosses/?ref=bongholee.com#meansquarederror-class)
- [Long Tail Event에서 예측시 정확도 높이기 (Doordash Case)](https://bongholee.com/long-tail-eventeseo-yeceugsi-jeonghwagdo-nopigi-doordash-case/)