gpt4 book ai didi

python - 预测取决于 Keras 中的批量大小

转载 作者:太空狗 更新时间:2023-10-29 21:05:11 25 4
gpt4 key购买 nike

我正在尝试使用 keras 对图像进行二进制分类。

我的 CNN 模型在训练数据上训练有素(训练准确率约为 90%,验证准确率约为 93%)。但是在训练期间,如果我设置 batch size=15000,我会得到 Figure I 输出,如果我设置 batch size=50000,我会得到 Figure II 作为输出。有人可以告诉我出了什么问题吗?预测不应该取决于批量大小,对吗?

我用于预测的代码:

y=model.predict_classes(补丁,batch_size=50000,verbose=1)
y=y.reshape((256,256))

Figure 1 Figure 2

我的模型:-

model = Sequential()

model.add(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)))
model.add(Activation('relu'))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Convolution2D(64, 3, 3, border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

# let's train the model using SGD + momentum (how original).
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])

最佳答案

Keras 在 predict 函数中自动标准化输入。标准化所需的统计数据是按批处理计算的——这就是为什么您的输出可能取决于批处理大小的原因。您可以通过以下方式解决此问题:

  1. 如果 Keras > 1.0,您可以简单地在函数式 API 中定义您的模型,然后简单地将经过训练的函数应用于自标准化数据。
  2. 如果您的模型经过训练 - 您可以将其恢复为 Theano 函数,并将其应用于自标准化数据。
  3. 如果您的数据不是很大,您也可以简单地将批量大小设置为数据集中的示例数。

更新:这是第二种解决方案的代码:

import theano

input = model.layers[0].input # Gets input Theano tensor
output = model.layers[-1].output # Gets output Theano tensor
model_theano = theano.function(input, output) # Compiling theano function

# Now model_theano is a function which behaves exactly like your classifier

predicted_score = model_theano(example) # returns predicted_score for an example argument

现在,如果你想使用这个新的 theano_model,你应该自己标准化主要数据集(例如,通过减去图像中的每个像素的平均值并除以标准差)并应用 theano_model 以获得整个数据集的分数(您可以在遍历示例或使用 numpy.apply_along_axisnumpy.apply_over_axes 函数的循环中执行此操作)。

更新 2:为了使此解决方案有效更改

model.add(Dense(nb_classes))
model.add(Activation('softmax'))

到:

model.add(Dense(nb_classes, activation = "softmax"))

关于python - 预测取决于 Keras 中的批量大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37429728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com