python - ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型生成器)
问题描述
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type generator).
由于错误,我的代码有一些问题。
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow import keras
builder = tfds.builder('horses_or_humans')
ds_train = tfds.load(name = 'horses_or_humans', split = 'train')
ds_test = tfds.load(name = 'horses_or_humans', split = 'test')
train_images = np.array([example['image'].numpy()[:,:,0] for example in ds_train])
train_labels = np.array(example['label'].numpy() for example in ds_train)
test_images = np.array([example['image'].numpy()[:,:,0] for example in ds_test])
test_labels = np.array(example['label'].numpy() for example in ds_test)
train_images = train_images.reshape(1027, 300, 300, 1)
test_images = test_images.reshape(256, 300, 300, 1)
我读过这个问题可能会出现在这里。
train_images = train_images.astype('float32')
test_images = test_images.astype('float32')
train_images /= 255
test_images /= 255
model = keras.Sequential([
keras.layers.Flatten(),
keras.layers.Dense(512, activation = 'relu'),
keras.layers.Dense(256, activation = 'relu'),
keras.layers.Dense(2, activation = 'softmax')
])
model.compile(
optimizer = 'adam',
loss = keras.losses.SparseCategoricalCrossentropy(),
metrics = ['accuracy']
)
model.fit(train_images, train_labels, epochs = 5, batch_size = 32)
我试过这样做
train_images = np.array(train_images).astype("float32")
test_images = np.array(test_images).astype("float32")
但遗憾的是它对我不起作用,所以我将不胜感激。
解决方案
- 您应该阅读如何通过 tfds 加载数据集。当您可以使用原生 tensorflow 操作时,您不应该在 tensorflow 处理管道中使用 NumPy。
- 你的神经网络架构不适合这个问题。有卷积网络的例子。
至于代码,可以这样修改:
ds_train = tfds.load(name='horses_or_humans', split='train', as_supervised=True)
ds_test = tfds.load(name='horses_or_humans', split='test', as_supervised=True)
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return tf.cast(image, tf.float32) / 255., label
ds_train = ds_train.map(normalize_img)
ds_train = ds_train.cache()
ds_train = ds_train.batch(32)
ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)
model.fit(ds_train, epochs=6)
推荐阅读
- javascript - 在 d3 中用不同的颜色在一个散点图矩阵中可视化两个数据集
- javascript - d3.csv(...).then 不是函数
- azure - Azure 函数和实体框架
- java - Apache HTTP 客户端 connectTimeout 与 connectionRequestTimeout
- azure - 如何在不暴露源代码的情况下部署到 Azure?
- sql - ORM与外键中的可选列的一对多关系?
- unity3d - Unity+PUN: "Instantiate" sometimes creates too many GameObjects
- php - 函数在 PHP 中不返回任何内容
- azure-cosmosdb - 嵌套集合中的 Azure 搜索选择
- go - golang 分析正在运行的生产应用程序而无需重新启动