[FIXED] Error when trying to import Tensorflow Datasets

Issue

I am following this tutorial: https://www.tensorflow.org/guide/keras and am getting an error when trying to use tf.data.Dataset.

import tensorflow as tf
import tensorflow.data
import numpy as np
from tensorflow.keras import layers

model = tf.keras.Sequential([
# Adds a densely-connected layer with 64 units to the model:
layers.Dense(64, activation='relu', input_shape=(32,)),
# Add another:
layers.Dense(64, activation='relu'),
# Add a softmax layer with 10 output units:
layers.Dense(10, activation='softmax')])

model.compile(optimizer=tf.train.AdamOptimizer(0.001),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# Instantiates a toy dataset instance:
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
dataset = dataset.batch(32)
dataset = dataset.repeat()

# Don't forget to specify `steps_per_epoch` when calling `fit` on a dataset.
model.fit(dataset, epochs=10, steps_per_epoch=30)

I get this error:

Colocations handled automatically by placer.
Traceback (most recent call last):
  File "tutorial.py", line 19, in <module>
    dataset = tensorflow.data.Dataset.from_tensor_slices((data, labels))
NameError: name 'data' is not defined

I have pip installed both Tensorflow and the Tensorflow-Datasets API. Not sure what is going on.

Solution

Here data and labels are undefined.

You can initialize data and labels by adding

data = tf.random_uniform([1000, 32])
labels = tf.random_uniform([1000, 10])

before dataset = tf.data.Dataset.from_tensor_slices((data, labels))

Answered By – Ajanyan Pradeep

Answer Checked By – Robin (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published