You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:解决TensorFlow中NumPy数组转Tensor时的Unsupported object type generator错误

解决ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type generator)

嘿,我一眼就揪出问题所在了!你的错误根源不在图像重塑或者类型转换,而是出在train_labels和test_labels的生成方式上。

问题分析

看这两行代码:

train_labels = np.array(example['label'].numpy() for example in ds_train)
test_labels = np.array(example['label'].numpy() for example in ds_test)

你用的是生成器表达式(没有方括号[]),当你把生成器传给np.array()时,它并不会把生成器里的元素转换成数组,而是直接把生成器本身变成了一个包含生成器对象的数组——这就导致TensorFlow在训练时无法把这个奇怪的对象转换成Tensor。

另外还有个小疏漏:你的代码里用了np但没导入numpy,得补上import numpy as np。

修复方案

把生成器表达式改成列表推导式(加上方括号),让np.array()能正确把所有标签转换成NumPy数组:

import matplotlib.pyplot as plt
import numpy as np  # 补上缺失的numpy导入
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")根本没触及核心问题——因为train_labels还是生成器对象,而不是数组,所以TensorFlow在处理标签时还是会报错。

现在修改后,train_labels和test_labels都会变成标准的NumPy数组,TensorFlow就能正常处理了。

内容的提问来源于stack exchange,提问作者WojKie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:18:15