[FIXED] Keras symbolic inputs/outputs do not implement __len__ Error

Issue

I want to build an AI to solve an optimization problem in a given environment, but I get the following error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-352-765c5782fe72> in <module>()
      1 model=Model(inputs=input_layer,outputs=output)
----> 2 model.compile(optimizer='adam',loss=-RewardFn,metrics=['acc'])
      3 model.summary()

1 frames
/usr/local/lib/python3.7/dist-packages/keras/engine/keras_tensor.py in __len__(self)
    219 
    220   def __len__(self):
--> 221     raise TypeError('Keras symbolic inputs/outputs do not '
    222                     'implement `__len__`. You may be '
    223                     'trying to pass Keras symbolic inputs/outputs '

TypeError: Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.

I found out about this error and it is said to be a problem with tensorflow. But I don’t know how to solve it. This is my model

!pip install keras-rl2
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from google.colab import files
import io
# %matplotlib inline
import seaborn as sns

sns.set(style='darkgrid')
uploaded=files.upload()
cols=['node1x','node2x','node3x','node4x','node1y','node2y','node3y','node4y','Rmin']
Dataset=pd.read_csv(io.StringIO(uploaded['DNNsamples.csv'].decode('utf-8')),names=cols,header=None)

Dataset.head(20)

from sklearn.model_selection import train_test_split
X_train,X_test=train_test_split(Dataset,test_size=0.2,random_state=42)

from tensorflow.keras.layers import Input,Dense,Activation,Dropout,Flatten
from tensorflow.keras.models import Model
------

input_layer=Input(shape=(Dataset.shape[1],))
dense_layer1=Dense(21,activation='relu')(input_layer)
dense_layer2=Dense(21,activation='relu')(dense_layer1)
dense_layer3=Dense(21,activation='relu')(dense_layer2)
dense_layer4=Dense(21,activation='relu')(dense_layer3)
dense_layer5=Dense(21,activation='relu')(dense_layer4)
dense_layer6=Dense(21,activation='relu')(dense_layer5)
output=Dense(outputss,activation='sigmoid')(dense_layer6)
-----
RewardFn=Ravg+Constraint1+Constraint2+Constraint3+Constraint4+Constraint5
tf.shape(RewardFn)

model=Model(inputs=input_layer,outputs=output)
model.compile(loss=-RewardFn,optimizer='adam',metrics=['acc'])
model.summary()

Could it be a problem to use input and output values ​​in a loss function?
I use Google Colab.

Solution

You do not need to specifically install the Keras package separately. You can import Keras from TensorFlow. Also, please provide the right alias while importing Input as below. Input is submodule of tf.keras API, not part of tensorflow.keras.layers API.

from tensorflow import keras
from tensorflow.keras import Input
from tensorflow.keras.layers import Dense,Activation,Dropout,Flatten

Please check the tensorflow and keras version should be as per this tested build configurations. Let us know if the issue still persists.

Answered By – TFer2

Answer Checked By – Candace Johnson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published