- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在使用 Keras 微调 Inception 模型时遇到问题。
我已经成功地使用教程和文档生成了一个完全连接的顶层模型,该模型使用 Inception 中的瓶颈特征将我的数据集分类到正确的类别中,准确率超过 99%。
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras import applications
# dimensions of our images.
img_width, img_height = 150, 150
#paths for saving weights and finding datasets
top_model_weights_path = 'Inception_fc_model_v0.h5'
train_data_dir = '../data/train2'
validation_data_dir = '../data/train2'
#training related parameters?
inclusive_images = 1424
nb_train_samples = 1424
nb_validation_samples = 1424
epochs = 50
batch_size = 16
def save_bottlebeck_features():
datagen = ImageDataGenerator(rescale=1. / 255)
# build bottleneck features
model = applications.inception_v3.InceptionV3(include_top=False, weights='imagenet', input_shape=(img_width,img_height,3))
generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
shuffle=False)
bottleneck_features_train = model.predict_generator(
generator, nb_train_samples // batch_size)
np.save('bottleneck_features_train', bottleneck_features_train)
generator = datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
shuffle=False)
bottleneck_features_validation = model.predict_generator(
generator, nb_validation_samples // batch_size)
np.save('bottleneck_features_validation', bottleneck_features_validation)
def train_top_model():
train_data = np.load('bottleneck_features_train.npy')
train_labels = np.array(range(inclusive_images))
validation_data = np.load('bottleneck_features_validation.npy')
validation_labels = np.array(range(inclusive_images))
print('base size ', train_data.shape[1:])
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(1000, activation='relu'))
model.add(Dense(inclusive_images, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy',
optimizer='Adam',
metrics=['accuracy'])
proceed = True
#model.load_weights(top_model_weights_path)
while proceed:
history = model.fit(train_data, train_labels,
epochs=epochs,
batch_size=batch_size)#,
#validation_data=(validation_data, validation_labels), verbose=1)
if history.history['acc'][-1] > .99:
proceed = False
model.save_weights(top_model_weights_path)
save_bottlebeck_features()
train_top_model()
Epoch 50/50 1424/1424 [==============================] - 17s 12ms/step - loss: 0.0398 - acc: 0.9909
我还能够将这个模型堆叠在初始之上以创建我的完整模型并使用该完整模型成功地对我的训练集进行分类。
from keras import Model
from keras import optimizers
from keras.callbacks import EarlyStopping
img_width, img_height = 150, 150
top_model_weights_path = 'Inception_fc_model_v0.h5'
train_data_dir = '../data/train2'
validation_data_dir = '../data/train2'
#how many inclusive examples do we have?
inclusive_images = 1424
nb_train_samples = 1424
nb_validation_samples = 1424
epochs = 50
batch_size = 16
# build the complete network for evaluation
base_model = applications.inception_v3.InceptionV3(weights='imagenet', include_top=False, input_shape=(img_width,img_height,3))
top_model = Sequential()
top_model.add(Flatten(input_shape=base_model.output_shape[1:]))
top_model.add(Dense(1000, activation='relu'))
top_model.add(Dense(inclusive_images, activation='softmax'))
top_model.load_weights(top_model_weights_path)
#combine base and top model
fullModel = Model(input= base_model.input, output= top_model(base_model.output))
#predict with the full training dataset
results = fullModel.predict_generator(ImageDataGenerator(rescale=1. / 255).flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
shuffle=False))
检查此完整模型的处理结果与瓶颈生成的全连接模型的准确性相匹配。
import matplotlib.pyplot as plt
import operator
#retrieve what the softmax based class assignments would be from results
resultMaxClassIDs = [ max(enumerate(result), key=operator.itemgetter(1))[0] for result in results]
#resultMaxClassIDs should be equal to range(inclusive_images) so we subtract the two and plot the log of the absolute value
#looking for spikes that indicate the values aren't equal
plt.plot([np.log(np.abs(x)+10) for x in (np.array(resultMaxClassIDs) - np.array(range(inclusive_images)))])
问题是:当我使用这个完整的模型并尝试对其进行训练时,即使验证率保持在 99% 以上,准确性也会下降到 0。
model2 = fullModel
for layer in model2.layers[:-2]:
layer.trainable = False
# compile the model with a SGD/momentum optimizer
# and a very slow learning rate.
#model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), metrics=['accuracy'])
model2.compile(loss='categorical_crossentropy',
optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
metrics=['accuracy'])
train_datagen = ImageDataGenerator(rescale=1. / 255)
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical')
callback = [EarlyStopping(monitor='acc', min_delta=0, patience=3, verbose=0, mode='auto', baseline=None)]
# fine-tune the model
model2.fit_generator(
#train_generator,
validation_generator,
steps_per_epoch=nb_train_samples//batch_size,
validation_steps = nb_validation_samples//batch_size,
epochs=epochs,
validation_data=validation_generator)
Epoch 1/50 89/89 [==============================] - 388s 4s/step - loss: 13.5787 - acc: 0.0000e+00 - val_loss: 0.0353 - val_acc: 0.9937
随着事情的进展,情况会变得更糟
Epoch 21/50 89/89 [==============================] - 372s 4s/step - loss: 7.3850 - acc: 0.0035 - val_loss: 0.5813 - val_acc: 0.8272
我唯一能想到的是,在最后一列火车上训练标签以某种方式分配不当,但我之前使用 VGG16 使用类似代码成功地做到了这一点。
我搜索了代码,试图找到一个差异来解释为什么在 99% 的时间内做出准确预测的模型会降低其训练准确性,同时在微调期间保持验证准确性,但我无法弄清楚。任何帮助将不胜感激。
关于代码和环境的信息:
看起来很奇怪的事情,但本来就是这样的:
我正在使用:
我已经 checkout :
但它们似乎无关。
最佳答案
注意:由于您的问题有点奇怪并且在没有经过训练的模型和数据集的情况下难以调试,因此这个答案只是在考虑了许多可能出错的事情之后的(最佳)猜测。请提供您的反馈,如果它不起作用,我将删除此答案。
由于 inception_V3 包含 BatchNormalization
层,当您将 trainable
参数设置为 False 时,问题可能是由于该层的(不知何故模棱两可或意外的)行为
(1,2,3,4)。
现在,让我们看看这是否是问题的根源:as suggested by @fchollet , 定义微调模型时设置学习阶段:
from keras import backend as K
K.set_learning_phase(0)
base_model = applications.inception_v3.InceptionV3(weights='imagenet', include_top=False, input_shape=(img_width,img_height,3))
for layer in base_model.layers:
layer.trainable = False
K.set_learning_phase(1)
top_model = Sequential()
top_model.add(Flatten(input_shape=base_model.output_shape[1:]))
top_model.add(Dense(1000, activation='relu'))
top_model.add(Dense(inclusive_images, activation='softmax'))
top_model.load_weights(top_model_weights_path)
#combine base and top model
fullModel = Model(input= base_model.input, output= top_model(base_model.output))
fullModel.compile(loss='categorical_crossentropy',
optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
metrics=['accuracy'])
#####################################################################
# Here, define the generators and then fit the model same as before #
#####################################################################
旁注:这不会对您的情况造成任何问题,但请记住,当您使用 top_model(base_model.output)
时,整个 Sequential 模型(即top_model
) 存储为 fullModel
的一层。您可以使用 fullModel.summary()
或 print(fullModel.layers[-1])
来验证这一点。因此,当您使用时:
for layer in model2.layers[:-2]:
layer.trainable = False
你实际上并没有卡住 base_model
的最后一层。但是,由于它是一个 Concatenate
层,因此没有可训练的参数,因此不会出现任何问题,它会按照您的预期运行。
关于python - Keras:微调 Inception 时精度下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52282108/
我有兴趣在 tf.keras 中训练一个模型,然后用 keras 加载它。我知道这不是高度建议,但我对使用 tf.keras 来训练模型很感兴趣,因为 tf.keras 更容易构建输入管道 我想利用
我进行了大量搜索,但仍然无法弄清楚如何编写具有多个交互输出的自定义损失函数。 我有一个神经网络定义为: def NeuralNetwork(): inLayer = Input((2,));
我正在阅读一篇名为 Differential Learning Rates 的文章在 Medium 上,想知道这是否可以应用于 Keras。我能够找到在 pytorch 中实现的这项技术。这可以在 K
我正在实现一个神经网络分类器,以打印我正在使用的这个神经网络的损失和准确性: score = model.evaluate(x_test, y_test, verbose=False) model.m
我最近在查看模型摘要时遇到了这个问题。 我想知道,[(None, 16)] 和有什么区别?和 (None, 16) ?为什么输入层有这样的输入形状? 来源:model.summary() can't
我正在尝试使用 Keras 创建自定义损失函数。我想根据输入计算损失函数并预测神经网络的输出。 我尝试在 Keras 中使用 customloss 函数。我认为 y_true 是我们为训练提供的输出,
我有一组样本,每个样本都是一组属性的序列(例如,一个样本可以包含 10 个序列,每个序列具有 5 个属性)。属性的数量总是固定的,但序列的数量(时间戳)可能因样本而异。我想使用这个样本集在 Keras
Keras 在训练集和测试集文件夹中发现了错误数量的类。我有 3 节课,但它一直说有 4 节课。有人可以帮我吗? 这里的代码: cnn = Sequential() cnn.add(Conv2D(32
我想编写一个自定义层,在其中我可以在两次运行之间将变量保存在内存中。例如, class MyLayer(Layer): def __init__(self, out_dim = 51, **kwarg
我添加了一个回调来降低学习速度: keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=100,
在 https://keras.io/layers/recurrent/我看到 LSTM 层有一个 kernel和一个 recurrent_kernel .它们的含义是什么?根据我的理解,我们需要 L
问题与标题相同。 我不想打开 Python,而是使用 MacOS 或 Ubuntu。 最佳答案 Python 库作者将版本号放入 .__version__ 。您可以通过在命令行上运行以下命令来打印它:
Keras 文档并不清楚这实际上是什么。我知道我们可以用它来将输入特征空间压缩成更小的空间。但从神经设计的角度来看,这是如何完成的呢?它是一个自动编码器,RBM吗? 最佳答案 据我所知,嵌入层是一个简
我想实现[http://ydwen.github.io/papers/WenECCV16.pdf]中解释的中心损失]在喀拉斯 我开始创建一个具有 2 个输出的网络,例如: inputs = Input
我正在尝试实现多对一模型,其中输入是大小为 的词向量d .我需要输出一个大小为 的向量d 在 LSTM 结束时。 在此 question ,提到使用(对于多对一模型) model = Sequenti
我有不平衡的训练数据集,这就是我构建自定义加权分类交叉熵损失函数的原因。但问题是我的验证集是平衡的,我想使用常规的分类交叉熵损失。那么我可以在 Keras 中为验证集传递不同的损失函数吗?我的意思是用
DL 中的一项常见任务是将输入样本归一化为零均值和单位方差。可以使用如下代码“手动”执行规范化: mean = np.mean(X, axis = 0) std = np.std(X, axis =
我正在尝试学习 Keras 并使用 LSTM 解决分类问题。我希望能够绘制 准确率和损失,并在训练期间更新图。为此,我正在使用 callback function . 由于某种原因,我在回调中收到的准
在 Keras 内置函数中嵌入使用哪种算法?Word2vec?手套?其他? https://keras.io/layers/embeddings/ 最佳答案 简短的回答是都不是。本质上,GloVe 的
我有一个使用 Keras 完全实现的 LSTM RNN,我想使用梯度剪裁,梯度范数限制为 5(我正在尝试复制一篇研究论文)。在实现神经网络方面,我是一个初学者,我将如何实现? 是否只是(我正在使用 r
我是一名优秀的程序员,十分优秀!