Keras custom loss function (elastic net)

2024/10/7 12:25:21

I'm try to code Elastic-Net. It's look likes:

elsticnet formula

And I want to use this loss function into Keras:

def nn_weather_model():ip_weather = Input(shape = (30, 38, 5))x_weather = BatchNormalization(name='weather1')(ip_weather)x_weather = Flatten()(x_weather)Dense100_1 = Dense(100, activation='relu', name='weather2')(x_weather)Dense100_2 = Dense(100, activation='relu', name='weather3')(Dense100_1)Dense18 = Dense(18, activation='linear', name='weather5')(Dense100_2)model_weather = Model(inputs=[ip_weather], outputs=[Dense18])model = model_weatherip = ip_weatherop = Dense18return model, ip, op

my loss function is:

def cost_function(y_true, y_pred):return ((K.mean(K.square(y_pred - y_true)))+L1+L2)return cost_function

It's mse+L1+L2

and L1 and L2 is

weight1=model.layers[3].get_weights()[0]
weight2=model.layers[4].get_weights()[0]
weight3=model.layers[5].get_weights()[0]
L1 = Calculate_L1(weight1,weight2,weight3)
L2 = Calculate_L2(weight1,weight2,weight3)

I use Calculate_L1 function to sum of the weight of dense1 & dense2 & dense3 and Calculate_L2 do it again.

When I train RB_model.compile(loss = cost_function(),optimizer= 'RMSprop') the L1 and L2 variable didn't update every batch. So I try to use callback when batch_begin while using:

class update_L1L2weight(Callback):def __init__(self):super(update_L1L2weight, self).__init__()def on_batch_begin(self,batch,logs=None):weight1=model.layers[3].get_weights()[0]weight2=model.layers[4].get_weights()[0]weight3=model.layers[5].get_weights()[0]L1 = Calculate_L1(weight1,weight2,weight3)L2 = Calculate_L2(weight1,weight2,weight3)

How could I use callback in the batch_begin calculate L1 and L2 done, and pass L1,L2 variable into loss funtion?

Answer

You can simply use built-in weight regularization in Keras for each layer. To do that you can use kernel_regularizer parameter of the layer and specify a regularizer for that. For example:

from keras import regularizersmodel.add(Dense(..., kernel_regularizer=regularizers.l2(0.1)))

Those regularizations would create a loss tensor which would be added to the loss function, as implemented in Keras source code:

# Add regularization penalties
# and other layer-specific losses.
for loss_tensor in self.losses:total_loss += loss_tensor
https://en.xdnf.cn/q/70242.html

Related Q&A

Django Models / SQLAlchemy are bloated! Any truly Pythonic DB models out there?

"Make things as simple as possible, but no simpler."Can we find the solution/s that fix the Python database world?Update: A lustdb prototype has been written by Alex Martelli - if you know a…

Fabric Sudo No Password Solution

This question is about best practices. Im running a deployment script with Fabric. My deployment user deploy needs sudo to restart services. So I am using the sudo function from fabric to run these com…

cartopy: higher resolution for great circle distance line

I am trying to plot a great circle distance between two points. I have found an in the cartopy docs (introductory_examples/01.great_circle.html):import matplotlib.pyplot as plt import cartopy.crs as cc…

Python Flask date update real-time

I am building a web app with Python Flask with JavaScript. I am a beginner of Javascript.The process I do now:In Flask Python code, 1. I get data by scrapping the web (numeric data that updates every m…

How do I force pip to install from the last commit of a branch in a repo?

I want pip to install from the latest commit on a master branch of my github repository. I tried many options mentioned here on StackOverflow, none helped. For instance, that does not work:pip install …

Emacs: pass arguments to inferior Python shell during buffer evaluation

recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buff…

How to edit a wheel package (.whl)?

I have a python wheel package, when extracted I find some python code, Id like to edit this code and re-generate the same .whl package again and test it to see the edits .. How do I do that?

Choosing order of bars in Bokeh bar chart

As part of trying to learn to use Bokeh I am trying to make a simple bar chart. I am passing the labels in a certain order (days of the week) and Bokeh seems to be sorting them alphabetically. How ca…

buildout - using different python version

i have set up buildout project (django to be specific) that has to run in old machine, it works fine in my local system with python 2.7. In production server it runs python 2.5 and i want to configure…

Receive an error from lingnutls/Hogweed when importing CV2

Ive never seen an error like this and dont know where to start. I installed opencv with conda install opencvand am running Ubuntu Linux 18.04 using a conda environment named fpn. How should I even appr…