【问题标题】:ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type generator)ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型生成器)
【发布时间】:2021-09-19 01:03:04
【问题描述】:

由于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")

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

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:
    1. 您应该阅读如何load datasets via tfds。当您可以使用原生 tensorflow 操作时,您不应该在 tensorflow 处理管道中使用 NumPy。
    2. 您的神经网络架构不适合这个问题。有convolutional net 的示例。

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2020-09-09
      • 1970-01-01
      • 2020-12-08
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多