- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我为 mnist 数据集开发了一个 3 层深度自动编码器模型,因为我只是这个微调范例的初学者,所以我正在练习这个玩具数据集
下面是代码
from keras import layers
from keras.layers import Input, Dense
from keras.models import Model,Sequential
from keras.datasets import mnist
import numpy as np
# Deep Autoencoder
# this is the size of our encoded representations
encoding_dim = 32 # 32 floats -> compression factor 24.5, assuming the input is 784 floats
# this is our input placeholder; 784 = 28 x 28
input_img = Input(shape=(784, ))
my_epochs = 100
# "encoded" is the encoded representation of the inputs
encoded = Dense(encoding_dim * 4, activation='relu')(input_img)
encoded = Dense(encoding_dim * 2, activation='relu')(encoded)
encoded = Dense(encoding_dim, activation='relu')(encoded)
# "decoded" is the lossy reconstruction of the input
decoded = Dense(encoding_dim * 2, activation='relu')(encoded)
decoded = Dense(encoding_dim * 4, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
# this model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
# Separate Encoder model
# this model maps an input to its encoded representation
encoder = Model(input_img, encoded)
# Separate Decoder model
# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(encoding_dim, ))
# retrieve the layers of the autoencoder model
decoder_layer1 = autoencoder.layers[-3]
decoder_layer2 = autoencoder.layers[-2]
decoder_layer3 = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer3(decoder_layer2(decoder_layer1(encoded_input))))
# Train to reconstruct MNIST digits
# configure model to use a per-pixel binary crossentropy loss, and the Adadelta optimizer
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
# prepare input data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# normalize all values between 0 and 1 and flatten the 28x28 images into vectors of size 784
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
# Train autoencoder for 50 epochs
autoencoder.fit(x_train, x_train, epochs=my_epochs, batch_size=256, shuffle=True, validation_data=(x_test, x_test),
verbose=2)
# after 100 epochs the autoencoder seems to reach a stable train/test lost value
# Visualize the reconstructed encoded representations
# encode and decode some digits
# note that we take them from the *test* set
encodedTrainImages=encoder.predict(x_train)
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
# From here I want to fine tune just the encoder model
model=Sequential()
model=Sequential()
for layer in encoder.layers:
model.add(layer)
model.add(layers.Flatten())
model.add(layers.Dense(20, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(10, activation='softmax'))
以下是我想要微调的编码器模型。
encoder.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 784) 0
_________________________________________________________________
dense_1 (Dense) (None, 128) 100480
_________________________________________________________________
dense_2 (Dense) (None, 64) 8256
_________________________________________________________________
dense_3 (Dense) (None, 32) 2080
=================================================================
Total params: 110,816
Trainable params: 110,816
Non-trainable params: 0
_________________________________________________________________
问题:1
构建自动编码器模型后,我只想使用编码器模型并对其进行微调以执行 mnist 数据集中的分类任务,但出现错误。
错误:
Traceback (most recent call last):
File "C:\Users\samer\Anaconda3\envs\tensorflow-gpu\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-15-528c079e5325>", line 3, in <module>
model.add(layers.Flatten())
File "C:\Users\samer\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\sequential.py", line 181, in add
output_tensor = layer(self.outputs[0])
File "C:\Users\samer\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\base_layer.py", line 414, in __call__
self.assert_input_compatibility(inputs)
File "C:\Users\samer\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\base_layer.py", line 327, in assert_input_compatibility
str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer flatten_4: expected min_ndim=3, found ndim=2
问题2:
类似地,我稍后会使用预训练模型,其中每个自动编码器将以贪婪的方式进行训练,然后对最终模型进行微调。有人可以指导我如何进一步完成这两项任务吗?
问候
最佳答案
问题是您试图展平已经平坦的层:您的编码器由一维 Densense 层组成,其形状为 (batch_size, dim)
。
Flatten 层至少需要一个 2D 输入,即具有 3 维形状 (batch_size, dim1, dim2)
(例如 Conv2D 层的输出),通过删除它,模型将正确构建:
encoding_dim = 32
input_img = layers.Input(shape=(784, ))
encoded = layers.Dense(encoding_dim * 4, activation='relu')(input_img)
encoded = layers.Dense(encoding_dim * 2, activation='relu')(encoded)
encoded = layers.Dense(encoding_dim, activation='relu')(encoded)
encoder = Model(input_img, encoded)
[...]
model = Sequential()
for layer in encoder.layers:
print(layer.name)
model.add(layer)
model.add(layers.Dense(20, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
哪些输出:
input_1
dense_1
dense_2
dense_3
Model: "sequential_1"
________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 128) 100480
_________________________________________________________________
dense_2 (Dense) (None, 64) 8256
_________________________________________________________________
dense_3 (Dense) (None, 32) 2080
_________________________________________________________________
dense_4 (Dense) (None, 20) 660
_________________________________________________________________
dropout_1 (Dropout) (None, 20) 0
_________________________________________________________________
dense_5 (Dense) (None, 10) 210
=================================================================
Total params: 111,686
Trainable params: 111,686
Non-trainable params: 0
_________________________________________________________________
___
问:如何确定新模型将使用与之前训练的编码器相同的权重?
答:在您的代码中,您所做的是迭代编码器内部包含的层,然后将每个层传递给 model.add()
。您在这里所做的是将引用直接传递给每个层,因此您的新模型中将具有完全相同的层。以下是使用图层名称的概念证明:
encoding_dim = 32
input_img = Input(shape=(784, ))
encoded = Dense(encoding_dim * 4, activation='relu')(input_img)
encoded = Dense(encoding_dim * 2, activation='relu')(encoded)
encoded = Dense(encoding_dim, activation='relu')(encoded)
decoded = Dense(encoding_dim * 2, activation='relu')(encoded)
decoded = Dense(encoding_dim * 4, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
autoencoder = Model(input_img, decoded)
print("autoencoder first Dense layer reference:", autoencoder.layers[1])
encoder = Model(input_img, encoded)
print("encoder first Dense layer reference:", encoder.layers[1])
new_model = Sequential()
for i, layer in enumerate(encoder.layers):
print("Before: ", layer.name)
new_model.add(layer)
if i != 0:
new_model.layers[i-1].name = "new_model_"+layer.name
print("After: ", layer.name)
哪些输出:
autoencoder first Dense layer reference: <keras.layers.core.Dense object at
0x7fb5f138e278>
encoder first Dense layer reference: <keras.layers.core.Dense object at
0x7fb5f138e278>
Before: input_1
Before: dense_1
After: new_model_dense_1
Before: dense_2
After: new_model_dense_2
Before: dense_3
After: new_model_dense_3
如您所见,编码器和自动编码器中的图层引用是相同的。此外,通过更改新模型内部的层名称,我们还更改了编码器相应层内部的层名称。有关通过引用传递 python 参数的更多详细信息,请查看此 answer .
<小时/>问:我的数据是否需要进行 one-hot 编码?如果是这样,那么如何?
答:您确实需要一种单热编码,因为您正在处理多标签分类问题。编码只需使用方便的 keras 函数即可完成:
from keras.utils import np_utils
one_hot = np_utils.to_categorical(y_train)
这里是 documentation 的链接.
___
<小时/>关于你的第二个问题,目前还不清楚你的目标是什么,但在我看来,你想要构建一个包含多个并行自动编码器的架构,这些自动编码器专门用于不同的任务,然后将它们连接起来通过添加一些最终的公共(public)层来输出。
无论如何,到目前为止我能做的就是建议你看看这个 guide ,其中解释了如何构建多输入和多输出模型并将其用作开始自定义实现的基线。
___
关于贪婪训练任务,方法是通过在追加新层时卡住所有前一层来一次训练一层。以下是 3(+1) 贪婪训练层网络的示例,稍后将其用作新模型的基础:
(x_train, y_train), (x_test, y_test) = mnist.load_data()
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
x_train = np.reshape(x_train, (x_train.shape[0], -1))
x_test = np.reshape(x_test, (x_test.shape[0], -1))
model = Sequential()
model.add(Dense(256, activation="relu", kernel_initializer="he_uniform", input_shape=(28*28,)))
model.add(Dense(10, activation="softmax"))
model.compile(optimizer=SGD(lr=0.01, momentum=0.9), loss="categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=64, epochs=50, verbose=1)
# Remove last layer
model.pop()
# 'Freeze' previous layers, so to single-train the new one
for layer in model.layers:
layer.trainable = False
# Append new layer + classification layer
model.add(Dense(64, activation="relu", kernel_initializer="he_uniform"))
model.add(Dense(10, activation="softmax"))
model.fit(x_train, y_train, batch_size=64, epochs=50, verbose=0)
# Remove last layer
model.pop()
# 'Freeze' previous layers, so to single-train the new one
for layer in model.layers:
layer.trainable = False
# Append new layer + classification layer
model.add(Dense(32, activation="relu", kernel_initializer="he_uniform"))
model.add(Dense(10, activation="softmax"))
model.fit(x_train, y_train, batch_size=64, epochs=50, verbose=0)
# Create new model which will use the pre-trained layers
new_model = Sequential()
# Discard the last layer from the previous model
model.pop()
# Optional: you can decide to set the pre-trained layers as trainable, in
# which case it would be like having initialized their weights, or not.
for l in model.layers:
l.trainable = True
new_model.add(model)
new_model.add(Dense(20, activation='relu'))
new_model.add(Dropout(0.5))
new_model.add(Dense(10, activation='softmax'))
new_model.compile(optimizer=SGD(lr=0.01, momentum=0.9), loss="categorical_crossentropy", metrics=["accuracy"])
new_model.fit(x_train, y_train, batch_size=64, epochs=100, verbose=1)
大致就是这样,但是我必须说贪婪层训练可能不再是一个合适的解决方案:现在的 ReLU、Dropout 和其他正则化技术使得贪婪层训练成为过时且耗时的权重初始化,因此你可能想要在进行贪婪训练之前先看看其他可能性。
___
关于python - 微调 mnist 深度自动编码器模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56131203/
我正在使用python 2.7 当我尝试在其上运行epsilon操作时出现此错误, 这是我的代码 import cv2 import numpy as np img = cv2.imread('img
1 很多程序员对互联网行业中广泛讨论的“35岁危机”表示不满,似乎所有的程序员都有着35岁的职业保质期。然而,随着AI技术的兴起,这场翻天覆地的技术革命正以更加残酷且直接的方式渗透到各行各业。程序员
我有一个包含多个子模块的项目,我想列出每个子模块的相对深度 该项目: main_project submodule1 submodule1\submodule1_1 submo
我有一张彩色图像及其深度图,它们都是由 Kinect 捕获的。我想将它投影到另一个位置(以查看它在另一个视角下的样子)。由于我没有 Kinect 的内在参数(相机参数);我该如何实现? P.S:我正在
给出了这三个网址: 1) https://example.com 2) https://example.com/app 3) https://example.com/app?param=hello 假
这个着色器(最后的代码)使用 raymarching 来渲染程序几何: 但是,在图像(上图)中,背景中的立方体应该部分遮挡粉红色实体;不是因为这个: struct fragmentOutput {
我希望能够在 ThreeJS 中创建一个房间。这是我到目前为止所拥有的: http://jsfiddle.net/7oyq4yqz/ var camera, scene, renderer, geom
我正在尝试通过编写小程序来学习 Haskell...所以我目前正在为简单表达式编写一个词法分析器/解析器。 (是的,我可以使用 Alex/Happy...但我想先学习核心语言)。 我的解析器本质上是一
我想使用像 [parse_ini_file][1] 这样的东西。 例如,我有一个 boot.ini 文件,我将加载该文件以进行进一步的处理: ;database connection sett
我正在使用 Mockito 来测试我的类(class)。我正在尝试使用深度 stub ,因为我没有办法在 Mockito 中的另一个模拟对象中注入(inject) Mock。 class MyServ
我试图在调整设备屏幕大小时重新排列布局,所以我这样做: if(screenOrientation == SCREEN_ORIENTATION_LANDSCAPE) { document
我正在 Ubuntu 上编写一个简单的 OpenGL 程序,它使用顶点数组绘制两个正方形(一个在另一个前面)。由于某种原因,GL_DEPTH_TEST 似乎不起作用。后面的物体出现在前面的物体前面
static FAST_FUNC int fileAction(const char *pathname, struct stat *sb UNUSED_PARAM, void *mo
我有这样的层次结构: namespace MyService{ class IBase { public: virtual ~IBase(){} protected: IPointer
我正在制作一个图片库,需要一些循环类别方面的帮助。下一个深度是图库配置文件中的已知设置,因此这不是关于无限深度循环的问题,而是循环已知深度并输出所有结果的最有效方法。 本质上,我想创建一个 包含系统中
如何以编程方式在树状结构上获取 n 深度迭代器?在根目录中我有 List 每个节点有 Map> n+1 深度。 我已修复 1 个深度: // DEPTH 1 nodeData.forEach(base
我正在构建一个包含大量自定义元素的 Polymer 单页界面。 现在我希望我的元素具有某种主样式,我可以在 index.html 或我的主要内容元素中定义它。可以这样想: index.html
我正在尝试每 25 秒连接到配对的蓝牙设备,通过 AlarmManager 安排,它会触发 WakefulBroadcastReceiver 以启动服务以进行连接。设备进入休眠状态后,前几个小时一切正
假设有一个有默认值的函数: int foo(int x=42); 如果这被其他人这样调用: int bar(int x=42) { return foo(x); } int moo(int x=42)
是否可以使用 Javascript 获取 url 深度(级别)? 如果我有这个网址:www.website.com/site/product/category/item -> depth=4www.w
我是一名优秀的程序员,十分优秀!