【问题标题】:TypeError: 'NoneType' object is not iterable adding layers in kerasTypeError:“NoneType”对象不可迭代在 keras 中添加层
【发布时间】:2020-10-12 13:31:12
【问题描述】:

我试图运行以下代码在 keras 中创建网络:

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np

(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape)

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)

num_classes=len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

batch_size = 128
num_classes = 10
epochs = 10
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))

但我收到以下错误消息

TypeError: 'NoneType' object is not iterable

这里是完整的错误回溯:

Traceback (most recent call last):
  File ".../filename.py", line 31, in <module>
    model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
  File "...\Python38\lib\site-packages\keras\engine\sequential.py", line 166, in add
    layer(x)
  File "...\Python38\lib\site-packages\keras\backend\tensorflow_backend.py", line 75, in symbolic_fn_wrapper
    return func(*args, **kwargs)
  File "...\Python38\lib\site-packages\keras\engine\base_layer.py", line 463, in __call__
    self.build(unpack_singleton(input_shapes))
  File "...\Python38\lib\site-packages\keras\layers\convolutional.py", line 137, in build
    self.kernel = self.add_weight(shape=kernel_shape,
  File "...\Python38\lib\site-packages\keras\engine\base_layer.py", line 279, in add_weight
    weight = K.variable(initializer(shape, dtype=dtype),
  File "...\Python38\lib\site-packages\keras\initializers.py", line 226, in __call__
    x = K.random_uniform(shape, -limit, limit,
  File "...\Python38\lib\site-packages\keras\backend\tensorflow_backend.py", line 4356, in random_uniform
    return tf_keras_backend.random_uniform(
  File "...\Python38\lib\site-packages\tensorflow\python\keras\backend.py", line 5685, in random_uniform
    return random_ops.random_uniform(
  File "...\Python38\lib\site-packages\tensorflow\python\ops\random_ops.py", line 282, in random_uniform
    shape = tensor_util.shape_tensor(shape)
  File "...\Python38\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 1015, in shape_tensor
    return ops.convert_to_tensor(shape, dtype=dtype, name="shape")
  File "...\Python38\lib\site-packages\tensorflow\python\framework\ops.py", line 1341, in convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "...\Python38\lib\site-packages\tensorflow\python\framework\constant_op.py", line 321, in _constant_tensor_conversion_function
    return constant(v, dtype=dtype, name=name)
  File "...\Python38\lib\site-packages\tensorflow\python\framework\constant_op.py", line 261, in constant
    return _constant_impl(value, dtype, shape, name, verify_shape=False,
  File "...\Python38\lib\site-packages\tensorflow\python\framework\constant_op.py", line 270, in _constant_impl
    t = convert_to_eager_tensor(value, ctx, dtype)
  File "...\Python38\lib\site-packages\tensorflow\python\framework\constant_op.py", line 95, in convert_to_eager_tensor
    ctx.ensure_initialized()
  File "...\Python38\lib\site-packages\tensorflow\python\eager\context.py", line 502, in ensure_initialized
    config_str = self.config.SerializeToString()
  File "...\Python38\lib\site-packages\tensorflow\python\eager\context.py", line 880, in config
    self._initialize_physical_devices()
  File "...\Python38\lib\site-packages\tensorflow\python\eager\context.py", line 1167, in _initialize_physical_devices
    self._physical_devices = [

据我所知,查看 Tracebabk,问题出在文件 context.py 的第 1166 行: devs = pywrap_tfe.TF_ListPhysicalDevices() devs 是 然后在以下行 self._physical_devices = [PhysicalDevice(name=d.decode(),device_type=d.decode().split(":")[1]) for d in devs] 当它尝试对其进行迭代时,显然会引发 TypeError: 'NoneType' object is not iterable。

由于某种原因,物理设备列表为空,但函数 TF_ListPhysicalDevices() 不会产生和清空列表,而是 None。

无论如何,即使我将self._physical_devices 设置为一个空列表,它也会在其他地方引发另一个错误 (tensorflow.python.framework.errors_impl.NotFoundError: No CPU devices are available in this process)

关于如何解决这个问题的任何想法。谢谢。

我已经从网页https://data-flair.training/blogs/python-deep-learning-project-handwritten-digit-recognition复制了我试图运行的代码

【问题讨论】:

  • 请使用完整的错误回溯更新您的问题。
  • 我已经添加了完整的错误回溯。谢谢
  • 好的,但您似乎错过了命名错误的底部以及导致错误的行号。
  • 错误是 TypeError: 'NoneType' object is not iterable
  • 是的,但我不知道它发生在哪一行以及涉及哪个变量。

标签: python tensorflow keras deep-learning


【解决方案1】:

当您尝试迭代 None 值时会发生此错误(即变量没有值)。 你可以看到here一个类似的帖子。

通过堆栈跟踪,您应该能够识别错误的来源并修复它,但只要您不提供它,我们就无法帮助您。

在这里,我在您的代码中看不到任何循环,这意味着错误可能来自另一个方法,您为其传递了 None 类型的参数。

【讨论】:

  • 您好,我已在我的问题中添加了错误 Traceback 和更多详细信息。我希望它有助于澄清一点问题。如果您能提供帮助,我将不胜感激。
【解决方案2】:

检查您的 keras 版本。 2.3.1 不存在这个问题。

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np

(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape)

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)

num_classes=len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

batch_size = 128
num_classes = 10
epochs = 10
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
print("seems fine")

给予

(60000, 28, 28) (60000,)
x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
seems fine

【讨论】:

  • 我确实有 2.3.1 版本的 keras
猜你喜欢
  • 2012-08-25
  • 1970-01-01
  • 2011-04-22
  • 2017-08-29
  • 2016-08-30
相关资源
最近更新 更多