转换NumPy数组到张量失败(不支持的对象类型生成器)

2022-01-30 10:58:59 标签 pythontensorflowkeras

我有一些问题与我的代码由于ValueError:未能转换NumPy数组到一个张量(不支持的对象类型生成器)。错误。

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)
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码