卷积神经网络中的图像预处理在 Keras 与 Tflearn 中产生较低的准确度

东京部落

我正在尝试将此 tflearn DCNN 样本(使用图像预处理和增强)转换为 keras:

Tflearn 示例:

import tflearn
from tflearn.data_utils import shuffle, to_categorical
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.estimator import regression
from tflearn.data_preprocessing import ImagePreprocessing
from tflearn.data_augmentation import ImageAugmentation

# Data loading and preprocessing
from tflearn.datasets import cifar10
(X, Y), (X_test, Y_test) = cifar10.load_data()
X, Y = shuffle(X, Y)
Y = to_categorical(Y, 10)
Y_test = to_categorical(Y_test, 10)

# Real-time data preprocessing
img_prep = ImagePreprocessing()
img_prep.add_featurewise_zero_center()
img_prep.add_featurewise_stdnorm()

# Real-time data augmentation
img_aug = ImageAugmentation()
img_aug.add_random_flip_leftright()
img_aug.add_random_rotation(max_angle=25.)

# Convolutional network building
network = input_data(shape=[None, 32, 32, 3],
                     data_preprocessing=img_prep,
                     data_augmentation=img_aug)
network = conv_2d(network, 32, 3, activation='relu')
network = max_pool_2d(network, 2)
network = conv_2d(network, 64, 3, activation='relu')
network = conv_2d(network, 64, 3, activation='relu')
network = max_pool_2d(network, 2)
network = fully_connected(network, 512, activation='relu')
network = dropout(network, 0.5)
network = fully_connected(network, 10, activation='softmax')
network = regression(network, optimizer='adam',
                     loss='categorical_crossentropy',
                     learning_rate=0.001)

# Train using classifier
model = tflearn.DNN(network, tensorboard_verbose=0)
model.fit(X, Y, n_epoch=50, shuffle=True, validation_set=(X_test, Y_test),
          show_metric=True, batch_size=96, run_id='cifar10_cnn')

这在 50 个 epoch 后产生了以下结果:

Training Step: 26050  | total loss: 0.35260 | time: 144.306s
| Adam | epoch: 050 | loss: 0.35260 - acc: 0.8785 | val_loss: 0.64622 - val_acc: 0.8212 -- iter: 50000/50000

然后我尝试使用相同的 DCNN 层、参数和图像预处理/增强将其转换为 Keras:

import numpy as np
from keras.datasets import cifar10
from keras.callbacks import TensorBoard
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, UpSampling2D, AtrousConvolution2D
from keras.layers.advanced_activations import LeakyReLU, PReLU
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
import matplotlib
from matplotlib import pyplot as plt

np.random.seed(1337)

batch_size = 96 # how many images to process at once
nb_classes = 10 # how many types of objects we can detect in this set
nb_epoch = 50 # how long we train the system
img_rows, img_cols = 32, 32 # image dimensions
nb_filters = 32 # number of convolutional filters to use
pool_size = (2, 2) # size of pooling area for max pooling
kernel_size = (3, 3) # convolution kernel size

(X_train, Y_train), (X_test, Y_test) = cifar10.load_data()
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 3)
input_shape = (img_rows, img_cols, 3)
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')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(Y_train, nb_classes)
Y_test = np_utils.to_categorical(Y_test, nb_classes)

datagen = ImageDataGenerator(featurewise_center=True,
                             featurewise_std_normalization=True,
                             horizontal_flip=True,
                             rotation_range=25)
datagen.fit(X_train)

model = Sequential()
model.add(Conv2D(nb_filters, kernel_size, padding='valid', input_shape=input_shape, activation='relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Conv2D(nb_filters*2, kernel_size, activation='relu'))
model.add(Conv2D(nb_filters*2, kernel_size, activation='relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes, activation='softmax'))

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

# Set up TensorBoard
tb = TensorBoard(log_dir='./logs')

history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size), epochs=nb_epoch, shuffle=True, verbose=1, validation_data=(X_test, Y_test), callbacks=[tb])
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print("Accuracy: %.2f%%" % (score[1]*100))

plt.plot(history.epoch,history.history['val_acc'],'-o',label='validation')
plt.plot(history.epoch,history.history['acc'],'-o',label='training')
plt.legend(loc=0)
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.grid(True)
plt.show()

这产生了更糟糕的验证准确性结果:

Epoch 50/50
521/521 [==============================] - 84s 162ms/step - loss: 0.4723 - acc: 0.8340 - val_loss: 3.2970 - val_acc: 0.2729
Test score: 3.2969648239135743
Accuracy: 27.29%

谁能帮我理解为什么?我是否误用/误解了 Keras 中的图像预处理/增强?

今天

在您的 Keras 模型中,您也忘记了规范化验证数据。您可以通过使用datagen.meandatagen.std计算训练数据来做到这一点

# normalize test data; add a small constant to avoid division by zero,
# you can alternatively use `keras.backend.epsilon()`
X_test = (X_test - datagen.mean) / (datagen.std + 1e-8) 

或者您可以使用该datagen.standardize()方法对测试数据进行标准化:

X_test = datagen.standardize(X_test)

有关更多信息,请查看 SO 上的这个问题:在预测期间数据规范化如何在 keras 中工作?

不要忘记您应该通过对训练数据计算的统计数据来规范化测试数据。永远不要通过自己的统计数据规范化测试数据。

警告:似乎也standardize 改变了它的论点......是的,你可以在源代码中确认这一点

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在 Keras 中获得训练准确度输出?

来自分类Dev

使用 tflearn 进行回归的神经网络

来自分类Dev

即使 keras 中的准确度为 1.00,categorical_crossentropy 也会返回小的损失值

来自分类Dev

在 Keras 的 MNIST 数字识别中获得不同的测试数据准确度

来自分类Dev

改变 keras 指标=准确度

来自分类Dev

我如何使用 TFLearn 与训练指标(当前验证准确度、训练准确度等)进行交互?

来自分类Dev

转换为 CoreMLModel 的 Keras 卷积神经网络的输入是多阵列而不是图像?

来自分类Dev

在Keras中实现神经网络的准确性非常低

来自分类Dev

为什么在卷积神经网络中可能具有较低的损失,但准确性却很低?

来自分类Dev

将tflearn模型转换为keras

来自分类Dev

Keras model.fit 输出中的 acc 是什么意思?一个时期内最终迭代的准确度还是一个时期内的平均准确度?

来自分类Dev

使用Keras的神经网络

来自分类Dev

您如何准确计算卷积神经网络中滤波器的梯度?

来自分类Dev

如何在用 Keras 构建和训练的神经网络中处理错误预测?

来自分类Dev

表征股市神经网络的Keras损失和准确性

来自分类Dev

Keras/Tensorflow 中简单神经网络的错误

来自分类Dev

tflearn(CNN)中的损失增加

来自分类Dev

为什么我的神经网络序列模型一开始就达到了 0.9998 的准确度?

来自分类Dev

使用Keras /神经网络分类数据

来自分类Dev

用Keras实现神经网络

来自分类Dev

前馈-神经网络Keras

来自分类Dev

Keras多层神经网络精度

来自分类Dev

如何在 TFLearn 中显示召回率和准确率?

来自分类Dev

Keras图像分类:显示的准确性较高,但测试图像的准确性较低

来自分类Dev

处理图像以将数据馈送到卷积神经网络

来自分类Dev

为什么在卷积神经网络 3 个通道中卷积成 3 个通道时过滤器只产生 1 个通道

来自分类Dev

keras:准确度为98%,但NN始终预测相同。可能是什么原因?

来自分类Dev

Keras model.fit_generator() 提供 0.0% 的验证准确度

来自分类Dev

为什么在 Keras 的 model.evaluate() 中使用损失来计算准确度?

Related 相关文章

  1. 1

    如何在 Keras 中获得训练准确度输出?

  2. 2

    使用 tflearn 进行回归的神经网络

  3. 3

    即使 keras 中的准确度为 1.00,categorical_crossentropy 也会返回小的损失值

  4. 4

    在 Keras 的 MNIST 数字识别中获得不同的测试数据准确度

  5. 5

    改变 keras 指标=准确度

  6. 6

    我如何使用 TFLearn 与训练指标(当前验证准确度、训练准确度等)进行交互?

  7. 7

    转换为 CoreMLModel 的 Keras 卷积神经网络的输入是多阵列而不是图像?

  8. 8

    在Keras中实现神经网络的准确性非常低

  9. 9

    为什么在卷积神经网络中可能具有较低的损失,但准确性却很低?

  10. 10

    将tflearn模型转换为keras

  11. 11

    Keras model.fit 输出中的 acc 是什么意思?一个时期内最终迭代的准确度还是一个时期内的平均准确度?

  12. 12

    使用Keras的神经网络

  13. 13

    您如何准确计算卷积神经网络中滤波器的梯度?

  14. 14

    如何在用 Keras 构建和训练的神经网络中处理错误预测?

  15. 15

    表征股市神经网络的Keras损失和准确性

  16. 16

    Keras/Tensorflow 中简单神经网络的错误

  17. 17

    tflearn(CNN)中的损失增加

  18. 18

    为什么我的神经网络序列模型一开始就达到了 0.9998 的准确度?

  19. 19

    使用Keras /神经网络分类数据

  20. 20

    用Keras实现神经网络

  21. 21

    前馈-神经网络Keras

  22. 22

    Keras多层神经网络精度

  23. 23

    如何在 TFLearn 中显示召回率和准确率?

  24. 24

    Keras图像分类:显示的准确性较高,但测试图像的准确性较低

  25. 25

    处理图像以将数据馈送到卷积神经网络

  26. 26

    为什么在卷积神经网络 3 个通道中卷积成 3 个通道时过滤器只产生 1 个通道

  27. 27

    keras:准确度为98%,但NN始终预测相同。可能是什么原因?

  28. 28

    Keras model.fit_generator() 提供 0.0% 的验证准确度

  29. 29

    为什么在 Keras 的 model.evaluate() 中使用损失来计算准确度?

热门标签

归档