Keras 中的展平函数

joh*_*der 4 keras tensorflow

定义神经网络架构的问题

我正在尝试使用 Keras 为 CIFAR-10 图像数据集(https://keras.io/datasets/)创建一个 CNN,但即使 Flatten 函数出现在 Keras 库中,我也无法使其工作:https://keras.io/layers/core/#flatten

这是错误消息:

NameError                                 Traceback (most recent call last)
<ipython-input-9-aabd6bce9082> in <module>()
     12 nn.add(Conv2D(64, 3, 3, activation='relu'))
     13 nn.add(MaxPooling2D(pool_size=(2, 2)))
---> 14 nn.add(Flatten())
     15 nn.add(Dense(128, activation='relu'))
     16 nn.add(Dense(10, activation='softmax'))

NameError: name 'Flatten' is not defined
Run Code Online (Sandbox Code Playgroud)

我正在使用运行 Python 2.7 和 Keras 1.1.1 的 Jupyter。下面是神经网络的代码:

from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.layers import Dense, Activation

nn = Sequential()
nn.add(Conv2D(32, 3, 3, activation='relu', input_shape=(32, 32, 3)))

# Max-pool reduces the size of inputs, by taking the largest pixel-value from a grid
nn.add(MaxPooling2D(pool_size=(2, 2)))
nn.add(Conv2D(64, 3, 3, activation='relu'))
nn.add(MaxPooling2D(pool_size=(2, 2)))
nn.add(Flatten())
nn.add(Dense(128, activation='relu'))
nn.add(Dense(10, activation='softmax'))
Run Code Online (Sandbox Code Playgroud)

提前致谢,

-约翰·B.

Pad*_*ddy 5

尝试先导入图层:

from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten

nn = Sequential()
nn.add(Conv2D(32, 3, 3, activation='relu', input_shape=(32, 32, 3)))

# Max-pool reduces the size of inputs, by taking the largest pixel-value from a grid
nn.add(MaxPooling2D(pool_size=(2, 2)))
nn.add(Conv2D(64, 3, 3, activation='relu'))
nn.add(MaxPooling2D(pool_size=(2, 2)))
nn.add(Flatten())
nn.add(Dense(128, activation='relu'))
nn.add(Dense(10, activation='softmax'))
Run Code Online (Sandbox Code Playgroud)

  • 我建议您升级keras和tensorflow(或theano),因为您使用的是相当旧版本的Keras (2认同)