TypeError : Inputs to a layer should be tensor

Viewed 125

I am new to deep learning currently trying to learn neural network.However,I encountered this problem while training the neural network.

This is the input .I thought by using the tensor Dataset I am ready to pass the values into the model I build.

train_dataset = tf.data.Dataset.from_tensor_slices((train.values, trainLabel.values))
test_dataset = tf.data.Dataset.from_tensor_slices((test.values, testLabel.values))
cv_dataset = tf.data.Dataset.from_tensor_slices((val.values, valLabel.values))

for features, targets in train_dataset.take(5):
  print ('Features: {}, Target: {}'.format(features, targets))

This is the output shown from the print method above:

Features: [ 0 40  0  0  0  1 31 33 17], Target: 29
Features: [ 0 32  0  1  0  1 50 55 44], Target: 7
Features: [ 0 32  1  0  1  1 12 43 31], Target: 34
Features: [ 0 29  1  1  1  0 56 52 37], Target: 14
Features: [ 0 25  0  0  1  1 29 30 15], Target: 17

This is my model using Keras API:

model = tf.keras.Sequential([
  tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(9,)),  # input shape required
  tf.keras.layers.Dense(10, activation=tf.nn.relu),
  tf.keras.layers.Dense(3)
])

I am trying to preview the output before training the neural network.

predictions = model(train_dataset)
predictions[:5]

However, I got this error :

TypeError: Inputs to a layer should be tensors. Got: <BatchDataset element_spec=(TensorSpec(shape=(None, 9), dtype=tf.int64, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>

I googled myself to search for the error and found this line of code but still not working, at least for me

train_dataset = train_dataset.shuffle(buffer_size=1024).batch(32)
1 Answers

The reason for this error, you're providing BatchDataset to the model. Instead, you must change the input data into an array before feeding that into the model and do the model definition and compile the model.

train = np.array(train)
train

train_dataset = tf.data.Dataset.from_tensor_slices((train, trainLabel)

for features, targets in train_dataset.take(5):
  print ('Features: {}, Target: {}'.format(features, targets))

train_dataset = train_dataset.shuffle(buffer_size=1024).batch(32) 
#type(train_dataset) --->tensorflow.python.data.ops.dataset_ops.BatchDataset

The below code will give you only a preview of an already existing dataset without any changes:

predictions = model(train)
predictions[:5]

Hence, you need to train the model with input data and then check for predictions:

model.fit(train_dataset, epochs=10)

predictions = model(train)
predictions[:5]

Output:

<tf.Tensor: shape=(5, 1), dtype=float32, numpy=
array([[ 7.51 ],
       [10.033],
       [11.349],
       [ 9.586],
       [ 9.86 ]], dtype=float32)>

Note: I have used the abalone dataset to replicate this code.

Related