【问题标题】:Trying to train a network outputs: Negative dimension size caused by subtracting 2 from 1 for max_pooling2d尝试训练网络输出:maxpooling2d 从 1 中减去 2 导致的负维度大小
【发布时间】:2019-06-02 03:12:07
【问题描述】:

尝试在形状为 (256, 256, 3) 的样本数据集上训练卷积神经网络时会出现 ValueError。

我检查了我的数据的形状(它已经在最后一个通道中,就像 tensorflow 想要的那样)。我尝试使用与其他人相同的代码,但它不起作用。我检查了我的数据集,看看数据的格式是否正确,我似乎没有发现任何错误。

我的 CNN 的代码如下:

X = pickle.load(open("X.pickle", "rb")) # Shape (256, 256, 3)
y = pickle.load(open("y.pickle", "rb")) # The labels

X = X / 255.0 # Normalizing the data

model = Sequential()
model.add(Conv2D(64, (3,3), input_shape=(256, 256, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))

model.add(Dense(1))
model.add(Activation("sigmoid"))

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

model.fit(X, y, batch_size=32, validation_split=0.1)

我希望网络能够顺利运行,但它输出了以下内容(不会发布整个错误日志,因为它太长了):

File "neuralnet.py", line 18, in <module>
    model.add(MaxPooling2D(pool_size=(2,2)))

ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,64,128,1].

编辑 发布我的 keras.json 文件:

{
    "epsilon": 1e-07, 
    "floatx": "float32", 
    "image_data_format": "channels_last", 
    "backend": "tensorflow"
}

它以前在 data_format channels_first 和后端 theano 上。我已经改了,但我不得不说我是直接使用 Keras 的 tensorflow 实现的。

更改为 channels_last 和后端 tensorflow 已更改控制台的输出,现在它在 model.fit 行出现此错误:

ValueError: You are passing a target array of shape (8118, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:
```
from keras.utils import to_categorical
y_binary = to_categorical(y_int)
```

Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.

【问题讨论】:

  • 您以前使用过 Theano 后端吗?你的 ~/.keras/keras.json 的内容是什么?
  • @MatiasValdenegro 我想我以前用过theano,但这是在一个新环境中。张量流是否有 keras.json 文件?我在哪里可以找到它?
  • 在 ~/.keras/keras.json 中,和我之前指出的一样
  • @MatiasValdenegro 我已经用你所说的更新了我的帖子。我尝试将其更改为应有的状态,但仍然出现错误(现在它们不同了)。

标签: python python-3.x tensorflow keras


【解决方案1】:

要解决你的最后一个问题,你有这个解决方案。

首先,将损失函数改为"binary_crossentropy",而不是"categorical_crossentropy"。 (因为我假设你有两个类,使用 sigmoid 激活),前提是你的数据是一次性编码的。

如果您不想对数据进行一次热编码(这是将 0 和 1 转换为 [1,0] 和 [0,1]),您可以使用“sparse_categorical_crossentropy”,就像错误提示的那样.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 2020-04-23
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多