- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在keras blog上有一个VGG16微调的例子,但我无法重现它。
更准确地说,这里是用于在没有顶层的情况下初始化 VGG16 并卡住除最顶层以外的所有 block 的代码:
WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'
weights_path = get_file('vgg16_weights.h5', WEIGHTS_PATH_NO_TOP)
model = Sequential()
model.add(InputLayer(input_shape=(150, 150, 3)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3'))
model.add(MaxPooling2D((2, 2), strides=(2, 2), name='block5_maxpool'))
model.load_weights(weights_path)
for layer in model.layers:
layer.trainable = False
for layer in model.layers[-4:]:
layer.trainable = True
print("Layer '%s' is trainable" % layer.name)
接下来,创建一个只有一个隐藏层的顶层模型:
top_model = Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:]))
top_model.add(Dense(256, activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(1, activation='sigmoid'))
top_model.load_weights('top_model.h5')
请注意,它之前曾针对瓶颈特征进行过训练,如博文中所述。接下来,将这个顶层模型添加到基础模型中并编译:
model.add(top_model)
model.compile(loss='binary_crossentropy',
optimizer=SGD(lr=1e-4, momentum=0.9),
metrics=['accuracy'])
最终,适合猫/狗数据:
batch_size = 16
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_gen = train_datagen.flow_from_directory(
TRAIN_DIR,
target_size=(150, 150),
batch_size=batch_size,
class_mode='binary')
valid_gen = test_datagen.flow_from_directory(
VALID_DIR,
target_size=(150, 150),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_gen,
steps_per_epoch=nb_train_samples // batch_size,
epochs=nb_epoch,
validation_data=valid_gen,
validation_steps=nb_valid_samples // batch_size)
但这是我在尝试拟合时遇到的错误:
ValueError: Error when checking model target: expected block5_maxpool to have 4 > dimensions, but got array with shape (16, 1)
因此,基础模型中的最后一个池化层似乎有问题。或者可能我在尝试将基本模型与顶级模型连接时做错了什么。
有没有人有类似的问题?或者也许有更好的方法来构建这种“级联”模型?我正在使用 keras==2.0.0
和 theano
后端。
Note: I was using examples from gist and
applications.VGG16
utility, but has issues trying to concatenate models, I am not too familiar withkeras
functional API. So this solution I provide here is the most "successful" one, i.e. it fails only on fitting stage.
好的,这里是关于我正在尝试做的事情的一个小解释。首先,我从 VGG16 生成瓶颈特征如下:
def save_bottleneck_features():
datagen = ImageDataGenerator(rescale=1./255)
model = applications.VGG16(include_top=False, weights='imagenet')
generator = datagen.flow_from_directory(
TRAIN_DIR,
target_size=(150, 150),
batch_size=batch_size,
class_mode=None,
shuffle=False)
print("Predicting train samples..")
bottleneck_features_train = model.predict_generator(generator, nb_train_samples)
np.save(open('bottleneck_features_train.npy', 'w'), bottleneck_features_train)
generator = datagen.flow_from_directory(
VALID_DIR,
target_size=(150, 150),
batch_size=batch_size,
class_mode=None,
shuffle=False)
print("Predicting valid samples..")
bottleneck_features_valid = model.predict_generator(generator, nb_valid_samples)
np.save(open('bottleneck_features_valid.npy', 'w'), bottleneck_features_valid)
然后,我创建了一个顶级模型,并按如下方式对这些特征进行训练:
def train_top_model():
train_data = np.load(open('bottleneck_features_train.npy'))
train_labels = np.array([0]*(nb_train_samples / 2) +
[1]*(nb_train_samples / 2))
valid_data = np.load(open('bottleneck_features_valid.npy'))
valid_labels = np.array([0]*(nb_valid_samples / 2) +
[1]*(nb_valid_samples / 2))
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(train_data, train_labels,
nb_epoch=nb_epoch,
batch_size=batch_size,
validation_data=(valid_data, valid_labels),
verbose=1)
model.save_weights('top_model.h5')
基本上,有两个经过训练的模型,base_model
具有 ImageNet 权重,top_model
具有从瓶颈特征生成的权重。我想知道如何连接它们?有可能还是我做错了什么?因为正如我所见,来自@thomas-pinetz 的响应假设顶级模型没有单独训练并立即附加到模型。不确定我是否清楚,这里引用博客:
In order to perform fine-tuning, all layers should start with properly trained weights: for instance you should not slap a randomly initialized fully-connected network on top of a pre-trained convolutional base. This is because the large gradient updates triggered by the randomly initialized weights would wreck the learned weights in the convolutional base. In our case this is why we first train the top-level classifier, and only then start fine-tuning convolutional weights alongside it.
最佳答案
我认为 vgg 网络描述的权重不适合您的模型,错误源于此。无论如何,如 ( https://keras.io/applications/#vgg16 ) 中所述,有一种更好的方法可以使用网络本身来执行此操作。
你可以只使用:
base_model = keras.applications.vgg16.VGG16(include_top=False, weights='imagenet', input_tensor=None, input_shape=None)
实例化一个预训练的 vgg 网络。然后你可以卡住图层并使用模型类来实例化你自己的模型,如下所示:
x = base_model.output
x = Flatten()(x)
x = Dense(your_classes, activation='softmax')(x) #minor edit
new_model = Model(input=base_model.input, output=x)
要组合底部网络和顶部网络,您可以使用以下代码片段。使用了以下函数(Input Layer ( https://keras.io/getting-started/functional-api-guide/ )/load_model ( https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model ) 和keras的函数式API):
final_input = Input(shape=(3, 224, 224))
base_model = vgg...
top_model = load_model(weights_file)
x = base_model(final_input)
result = top_model(x)
final_model = Model(input=final_input, output=result)
关于python - Keras VGG16 微调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43386463/
我有兴趣在 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
我是一名优秀的程序员,十分优秀!