首页 > 解决方案 > 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")

但遗憾的是它对我不起作用,所以我将不胜感激。

标签: pythontensorflowkeras

解决方案


  1. 您应该阅读如何通过 tfds 加载数据集。当您可以使用原生 tensorflow 操作时,您不应该在 tensorflow 处理管道中使用 NumPy。
  2. 你的神经网络架构不适合这个问题。有卷积网络的例子。

至于代码,可以这样修改:

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)

推荐阅读