如何转换Tensorflow数据集的数据类型[EMNSTbalanced](从uint8到float32)



我使用的是Tensorflow数据集"emnist/balanced"。默认情况下,特征值的数据类型为uint8。然而,Tensorflow模型只接受浮点值。

如何将功能和标签数据类型转换为float32。

代码在这里:

#########################################################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

类型错误:传递给参数"features"的值的DataType uint8不在允许值列表中:float16、bfloat16、float32、float64

请参考工作代码为MNIST数据集训练ANN

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)

输出:

T/F版本:2.1.0

列车精度:91.06

测试精度:0.8871

最新更新