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))
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))>
CodePudding user response:
You are trying to feed your model a dataset object while it expects a batch of samples. You should use .as_numpy_iterator
, then .next
to get one batch of data.
train_dataset = tf.data.Dataset.from_tensor_slices((train.values, trainLabel.values))
train_iterator = train_dataset.as_numpy_iterator()
one_batch = train_iterator.next()
model(one_batch)
The model expects a batch of input (that is a 2d numpy array, where the first dimension is the size of the batch, and the second dimension is the input size, which is 9 in your case), this is the meaning of None
when you look at what is printed by model.summary()
.
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 10) 100
_________________________________________________________________
dense_1 (Dense) (None, 10) 110
_________________________________________________________________
dense_2 (Dense) (None, 3) 33
=================================================================
Total params: 243
Trainable params: 243
Non-trainable params: 0
_________________________________________________________________
See https://www.tensorflow.org/api_docs/python/tf/data/Dataset