'Training deep learning model with constraint between input and output

I have a feed forward neural network with 16 features as the input array and 17 targets as the output array. I want to use the customized loss function. enter image description here My python code using Tensorflow and keras:

from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

import keras.backend as K
def custom_loss_wrapper(input_tensor):
    def custom_loss(y_true, y_pred):
      # b=tf.keras.backend.mean(input_tensor)
      b=0
      for i in range(0,input_dims):
        b=b+y_pred[i]*input_tensor[i]
      b=(b-y_pred[input_dims+1])**2  
      return tf.keras.backend.mean(tf.keras.backend.square(y_true - y_pred)) + b
    return custom_loss

input_tensor = Input(shape=(input_dims,))
hidden1 = Dense(128, activation='relu')(input_tensor)
hidden2 = Dense(256, activation='relu')(hidden1)
hidden3 = Dense(128, activation='relu')(hidden2)
output_tensor = Dense(output_dims, activation='linear')(hidden3)

example_model = Model(input_tensor, output_tensor)
example_model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')

example_model.fit(X_train, y_train, batch_size = 128, epochs = 1, verbose=1)

I get the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-9809f576a6e9> in <module>()
      6 
      7 example_model = Model(input_tensor, output_tensor)
----> 8 example_model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')

6 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
    690       except Exception as e:  # pylint:disable=broad-except
    691         if hasattr(e, 'ag_error_metadata'):
--> 692           raise e.ag_error_metadata.to_exception(e)
    693         else:
    694           raise

ValueError: in user code:

    File "<ipython-input-64-5a6acb405980>", line 7, in custom_loss  *
        b=b+y_pred[i]*input_tensor[i]

    ValueError: Dimensions must be equal, but are 17 and 16 for '{{node loss_11/dense_78_loss/mul}} = Mul[T=DT_FLOAT](loss_11/dense_78_loss/strided_slice, loss_11/dense_78_loss/strided_slice_1)' with input shapes: [17], [16].

How to fix the dimension issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source