How do convert data type of Tensorflow Dataset [EMNIST/balanced] (From uint8 to float32)

Viewed 1073

I am using Tensorflow dataset "emnist/balanced". The data type of features value is uint8 by default. However, Tensorflow model accept only float values.

How can I convert the features and labels data type to float32.

The code is here:

#########################################################3
import tensorflow as tf
import tensorflow_datasets as tfds

datasets, info = tfds.load(name="emnist/balanced", with_info=True, as_supervised=True)

emnist_train, emnist_test = datasets['train'], datasets['test']

.
.
.
.
.
.

history = model.fit(emnist_train, epochs = 10)

#validation

test_loss, test_acc = model.evaluate(emnist_test, verbose=2)

print(test_acc)


Error --
      2 
      3 
----> 4 history = model.fit(emnist_train, epochs = 10)
      5 
      6 #validation

TypeError: Value passed to parameter 'features' has DataType uint8 not in list of allowed values: float16, bfloat16, float32, float64

TypeError: Value passed to parameter 'features' has DataType uint8 not in list of allowed values: float16, bfloat16, float32, float64

1 Answers

Please refer working code to train a ANN for MNIST dataset

try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass
from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print("T/F Version:",tf.__version__)
#### Import the Fashion MNIST dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
##Scale these values to a range of 0 to 1 before feeding them to the neural network model
train_images = train_images / 255.0
test_images = test_images / 255.0
###Build the model
##the neural network requires configuring the layers of the model
##Set up the layers
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])
###Compile the model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
###Train the model
##Feed the model
model.fit(train_images, train_labels, epochs=10)
###Evaluate accuracy
##compare how the model performs on the test dataset
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

output:

T/F Version: 2.1.0

Train accuracy:91.06

Test accuracy: 0.8871

Related