官术网_书友最值得收藏!

Defining the custom loss function

In the previous section, we used the predefined mean absolute error loss function to perform the optimization. In this section, we will learn about defining a custom loss function to perform optimization.

The custom loss function that we shall build is a modified mean squared error value, where the error is the difference between the square root of the actual value and the square root of the predicted value.

The custom loss function is defined as follows:

import keras.backend as K
def loss_function(y_true, y_pred):
return K.square(K.sqrt(y_pred)-K.sqrt(y_true))

Now that we have defined the loss function, we will be reusing the same input and output datasets that we prepared in previous section, and we will also be using the same model that we defined earlier.

Now, let's compile the model:

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

In the preceding code, note that we defined the loss value as the custom loss function that we defined earlier—loss_function.

history = model.fit(train_data2, train_targets, validation_data=(test_data2, test_targets), epochs=100, batch_size=32, verbose=1)

Once we fit the model, we will note that the mean absolute error is ~6.5 units, which is slightly less than the previous iteration where we used the mean_absolute_error loss function.

主站蜘蛛池模板: 兰州市| 泾源县| 获嘉县| 若尔盖县| 青阳县| 丹阳市| 瑞金市| 绥中县| 阳高县| 寻甸| 临澧县| 太仆寺旗| 高雄市| 长顺县| 丹东市| 会泽县| 福清市| 同江市| 鄂托克旗| 麟游县| 宝应县| 浠水县| 石泉县| 临安市| 读书| 亳州市| 漳州市| 滕州市| 驻马店市| 阜宁县| 常德市| 南充市| 孝义市| 道真| 清原| 微博| 正宁县| 光山县| 广丰县| 沾益县| 忻州市|